context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Threading; using System.Threading.Tasks; using DotJEM.Json.Index; using DotJEM.Json.Index.Util; using DotJEM.Json.Storage; using DotJEM.Json.Storage.Adapter; using DotJEM.Json.Storage.Adapter.Materialize.ChanceLog; using DotJEM.Json.Storage.Adapter.Materialize.Log; using DotJEM.Json.Storage.Configuration; using DotJEM.Web.Host.Configuration.Elements; using DotJEM.Web.Host.Diagnostics; using DotJEM.Web.Host.Initialization; using DotJEM.Web.Host.Providers.Concurrency.Snapshots; using DotJEM.Web.Host.Providers.Scheduler; using DotJEM.Web.Host.Providers.Scheduler.Tasks; using DotJEM.Web.Host.Tasks; using DotJEM.Web.Host.Util; using NCrontab; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace DotJEM.Web.Host.Providers.Concurrency { public interface IStorageIndexManager { IDictionary<string, long> Generations { get; } IStorageIndexManagerInfoStream InfoStream { get; } Task Generation(string area, long gen, IProgress<StorageIndexChangeLogWatcherInitializationProgress> progress = null); event EventHandler<IndexInitializedEventArgs> IndexInitialized; event EventHandler<IndexChangesEventArgs> IndexChanged; event EventHandler<IndexResetEventArgs> IndexReset; void Start(); void Stop(); void UpdateIndex(); void QueueUpdate(JObject entity); void QueueDelete(JObject entity); Task ResetIndex(); } public interface IStorageIndexManagerInfoStream { void Track(string area, int creates, int updates, int deletes, int faults); void Record(string area, IList<FaultyChange> faults); void Publish(IStorageChangeCollection changes); } //TODO: Not really a stream, but we need some info for now, then we can make it into a true info stream later. public class StorageIndexManagerInfoStream : IStorageIndexManagerInfoStream { private readonly ConcurrentDictionary<string, AreaInfo> areas = new ConcurrentDictionary<string, AreaInfo>(); public void Track(string area, int creates, int updates, int deletes, int faults) { AreaInfo info = areas.GetOrAdd(area, s => new AreaInfo(s)); info.Track(creates, updates, deletes, faults); } public void Record(string area, IList<FaultyChange> faults) { AreaInfo info = areas.GetOrAdd(area, s => new AreaInfo(s)); info.Record(faults); } public virtual void Publish(IStorageChangeCollection changes) { } public JObject ToJObject() { JObject json = new JObject(); long creates = 0, updates = 0, deletes = 0, faults = 0; //NOTE: This places them at top which is nice for human readability, machines don't care. json["creates"] = creates; json["updates"] = updates; json["deletes"] = deletes; json["faults"] = faults; foreach (AreaInfo area in areas.Values) { creates += area.Creates; updates += area.Updates; deletes += area.Deletes; faults += area.Faults; json[area.Area] = area.ToJObject(); } json["creates"] = creates; json["updates"] = updates; json["deletes"] = deletes; json["faults"] = faults; return json; } private class AreaInfo { private long creates = 0, updates = 0, deletes = 0, faults = 0; private readonly ConcurrentBag<FaultyChange> faultyChanges = new ConcurrentBag<FaultyChange>(); public string Area { get; } public long Creates => creates; public long Updates => updates; public long Deletes => deletes; public long Faults => faults; public FaultyChange[] FaultyChanges => faultyChanges.ToArray(); public AreaInfo(string area) { Area = area; } public void Track(int creates, int updates, int deletes, int faults) { Interlocked.Add(ref this.creates, creates); Interlocked.Add(ref this.updates, updates); Interlocked.Add(ref this.deletes, deletes); Interlocked.Add(ref this.faults, faults); } public void Record(IList<FaultyChange> faults) { faults.ForEach(faultyChanges.Add); } public JObject ToJObject() { JObject json = new JObject(); json["creates"] = creates; json["updates"] = updates; json["deletes"] = deletes; json["faults"] = faults; if (faultyChanges.Any()) json["faultyChanges"] = JArray.FromObject(FaultyChanges.Select(c => c.CreateEntity())); return json; } } } public interface IStorageManager { void Start(); void Stop(); } public class StorageManager : IStorageManager { private IScheduledTask task; private readonly IWebScheduler scheduler; private readonly Dictionary<string, IStorageHistoryCleaner> cleaners = new Dictionary<string, IStorageHistoryCleaner>(); private readonly TimeSpan interval; public StorageManager(IStorageContext storage, IWebHostConfiguration configuration, IWebScheduler scheduler) { this.scheduler = scheduler; this.interval = AdvConvert.ConvertToTimeSpan(configuration.Storage.Interval); foreach (StorageAreaElement areaConfig in configuration.Storage.Items) { IStorageAreaConfigurator areaConfigurator = storage.Configure.Area(areaConfig.Name); if (!areaConfig.History) continue; areaConfigurator.EnableHistory(); if (string.IsNullOrEmpty(areaConfig.HistoryAge)) continue; TimeSpan historyAge = AdvConvert.ConvertToTimeSpan(areaConfig.HistoryAge); if(historyAge <= TimeSpan.Zero) continue; cleaners.Add(areaConfig.Name, new StorageHistoryCleaner( new Lazy<IStorageAreaHistory>(() => storage.Area(areaConfig.Name).History), historyAge)); } } public void Start() { task = scheduler.ScheduleTask("StorageManager.CleanHistory", b => CleanHistory(), interval); } private void CleanHistory() { foreach (IStorageHistoryCleaner cleaner in cleaners.Values) { cleaner.Execute(); } } public void Stop() => task.Dispose(); } public interface IStorageHistoryCleaner { void Execute(); } public class StorageHistoryCleaner : IStorageHistoryCleaner { private readonly TimeSpan maxAge; private readonly Lazy<IStorageAreaHistory> serviceProvider; private IStorageAreaHistory History => serviceProvider.Value; public StorageHistoryCleaner(Lazy<IStorageAreaHistory> serviceProvider, TimeSpan maxAge) { this.serviceProvider = serviceProvider; this.maxAge = maxAge; } public void Execute() { History.Delete(maxAge); } } public class StorageIndexManager : IStorageIndexManager { public event EventHandler<IndexResetEventArgs> IndexReset; public event EventHandler<IndexInitializedEventArgs> IndexInitialized; public event EventHandler<IndexChangesEventArgs> IndexChanged; private readonly IStorageIndex index; private readonly IWebScheduler scheduler; private readonly IInitializationTracker tracker; private readonly IDiagnosticsLogger logger; //private readonly Dictionary<string, IStorageAreaLog> logs = new Dictionary<string, IStorageAreaLog>(); private readonly Dictionary<string, IStorageIndexChangeLogWatcher> watchers; private readonly TimeSpan interval; private readonly int buffer = 512; public IDictionary<string, long> Generations => watchers.ToDictionary(k => k.Key, k => k.Value.Generation); public IStorageIndexManagerInfoStream InfoStream { get; } = new StorageIndexManagerInfoStream(); private IScheduledTask task; private readonly bool debugging; private readonly IIndexSnapshotManager snapshot; //TODO: To many dependencies, refactor! public StorageIndexManager( IStorageIndex index, IStorageContext storage, IWebHostConfiguration configuration, IPathResolver path, IWebScheduler scheduler, IInitializationTracker tracker, IIndexSnapshotManager snapshot, IDiagnosticsLogger logger) { this.index = index; this.debugging = configuration.Index.Debugging.Enabled; if (this.debugging) this.index.Writer.InfoEvent += (sender, args) => logger.Log("indexdebug", Severity.Critical, args.Message, new { args }); this.scheduler = scheduler; this.tracker = tracker; this.logger = logger; interval = TimeSpan.FromSeconds(configuration.Index.Watch.Interval); if (!string.IsNullOrEmpty(configuration.Index.Watch.RamBuffer)) buffer = (int)AdvConvert.ConvertToByteCount(configuration.Index.Watch.RamBuffer) / (1024 * 1024); WatchElement starWatch = configuration.Index.Watch.Items.FirstOrDefault(w => w.Area == "*"); if (starWatch != null) { watchers = storage.AreaInfos .ToDictionary(info => info.Name, info => (IStorageIndexChangeLogWatcher) new StorageChangeLogWatcher(info.Name, storage.Area(info.Name).Log, starWatch.BatchSize < 1 ? configuration.Index.Watch.BatchSize : starWatch.BatchSize, logger, InfoStream)); } else { watchers = configuration.Index.Watch.Items .ToDictionary(we => we.Area, we => (IStorageIndexChangeLogWatcher) new StorageChangeLogWatcher(we.Area, storage.Area(we.Area).Log, we.BatchSize < 1 ? configuration.Index.Watch.BatchSize : we.BatchSize, logger, InfoStream)); } this.snapshot = snapshot; } public async Task ResetIndex() { Stop(); index.Storage.Purge(); StorageIndexManagerInitializationProgressTracker initTracker = new StorageIndexManagerInitializationProgressTracker(watchers.Keys.Select(k => k)); using (ILuceneWriteContext writer = index.Writer.WriteContext(buffer)) { if (debugging) writer.InfoEvent += (sender, args) => logger.Log("indexdebug", Severity.Critical, args.Message, new { args }); await Task.WhenAll(watchers.Values.Select(watcher => watcher.Reset(writer,0, new Progress<StorageIndexChangeLogWatcherInitializationProgress>( progress => tracker.SetProgress($"{initTracker.Capture(progress)}"))))); } this.snapshot.TakeSnapshot(); OnIndexReset(new IndexResetEventArgs()); task = scheduler.ScheduleTask("ChangeLogWatcher", b => UpdateIndex(), interval); } public void Start() { InitializeIndex(); task = scheduler.ScheduleTask("ChangeLogWatcher", b => UpdateIndex(), interval); } public void Stop() => task.Dispose(); private void InitializeIndex() { this.snapshot.RestoreSnapshot(); StorageIndexManagerInitializationProgressTracker initTracker = new StorageIndexManagerInitializationProgressTracker(watchers.Keys.Select(k => k)); using (ILuceneWriteContext writer = index.Writer.WriteContext(buffer)) { if(debugging) writer.InfoEvent += (sender, args) => logger.Log("indexdebug", Severity.Critical, args.Message, new {args}); Sync.Await(watchers.Values.Select(watcher => watcher .Initialize(writer, new Progress<StorageIndexChangeLogWatcherInitializationProgress>( progress => tracker.SetProgress($"{initTracker.Capture(progress)}"))))); } this.snapshot.Initialize(); OnIndexInitialized(new IndexInitializedEventArgs()); } public async Task Generation(string area, long gen, IProgress<StorageIndexChangeLogWatcherInitializationProgress> progress = null) { if(!watchers.ContainsKey(area)) return; using (ILuceneWriteContext writer = index.Writer.WriteContext(buffer)) { if (debugging) writer.InfoEvent += (sender, args) => logger.Log("indexdebug", Severity.Critical, args.Message, new { args }); await watchers[area].Reset(writer, gen, progress); } } public void UpdateIndex() { IStorageChangeCollection[] changes = Sync .Await(watchers.Values.Select(watcher => watcher.Update(index.Writer))); OnIndexChanged(new IndexChangesEventArgs(changes.ToDictionary(c => c.StorageArea))); index.Flush(); } public void QueueUpdate(JObject entity) { //Note: This will cause the entity to be updated in the index twice // but it ensures that the entity is prepared for us if we query it right after this... index.Write(entity); task?.Signal(); } public void QueueDelete(JObject entity) { //Note: This will cause the entity to be updated in the index twice // but it ensures that the entity is prepared for us if we query it right after this... index.Delete(entity); task?.Signal(); } protected virtual void OnIndexChanged(IndexChangesEventArgs args) { IndexChanged?.Invoke(this, args); } protected virtual void OnIndexInitialized(IndexInitializedEventArgs e) { IndexInitialized?.Invoke(this, e); } protected virtual void OnIndexReset(IndexResetEventArgs e) { IndexReset?.Invoke(this, e); } public class StorageIndexManagerInitializationProgressTracker { private readonly ConcurrentDictionary<string, InitializationState> states; public StorageIndexManagerInitializationProgressTracker(IEnumerable<string> areas) { states = new ConcurrentDictionary<string, InitializationState>(areas.ToDictionary(v => v, v => new InitializationState(v))); } public string Capture(StorageIndexChangeLogWatcherInitializationProgress progress) { states.AddOrUpdate(progress.Area, s => new InitializationState(s), (s, state) => state.Add(progress.Token, progress.Latest, progress.Count, progress.Done)); return string.Join(Environment.NewLine, states.Values); } private class InitializationState { private readonly string area; private ChangeCount count; private long token; private long latest; private string done; public InitializationState(string area) { this.area = area; } public InitializationState Add(long token, long latest, ChangeCount count, bool done) { this.done = done ? "Completed" : "Indexing"; this.count += count; this.token = token; this.latest = latest; return this; } public override string ToString() => $" -> {area}: {token} / {latest} changes processed, {count.Total} objects indexed. {done}"; } } } }
using System.Collections.Generic; using System.Linq; using hw.DebugFormatter; using hw.Helper; using hw.Scanner; using Reni.TokenClasses; using Reni.TokenClasses.Whitespace; using Reni.Validation; namespace ReniUI.Classification; public abstract class Item : DumpableObject { public sealed class Trimmed : DumpableObject { [DisableDump] internal readonly Item Item; [DisableDump] internal readonly SourcePart SourcePart; internal Trimmed(Item item, SourcePart sourcePart) { Item = item; SourcePart = sourcePart.Intersect(item.SourcePart) ?? item.SourcePart.Start.Span(0); } public IEnumerable<char> GetCharArray() => SourcePart .Id .ToCharArray(); } internal BinaryTree Anchor { get; } protected Item(BinaryTree anchor) => Anchor = anchor; [DisableDump] public virtual SourcePart SourcePart => Anchor.Token; [DisableDump] public virtual bool IsKeyword => false; [DisableDump] public virtual bool IsIdentifier => false; [DisableDump] public virtual bool IsText => false; [DisableDump] public virtual bool IsNumber => false; [DisableDump] public virtual bool IsComment => false; [DisableDump] public virtual bool IsSpace => false; [DisableDump] public virtual bool IsBraceLike => false; [DisableDump] public virtual bool IsLineEnd => false; [DisableDump] public virtual bool IsError => false; [DisableDump] public virtual bool IsBrace => false; [DisableDump] public virtual bool IsPunctuation => false; [DisableDump] public virtual string State => ""; [DisableDump] public virtual IEnumerable<SourcePart> ParserLevelGroup => null; [DisableDump] public virtual Issue Issue => null; internal virtual IWhitespaceItem GetItem<TItemType>() where TItemType : IItemType => null; public override bool Equals(object obj) { if(ReferenceEquals(null, obj)) return false; if(ReferenceEquals(this, obj)) return true; if(obj.GetType() != GetType()) return false; return Equals((Item)obj); } public override int GetHashCode() => SourcePart.GetHashCode(); internal TokenClass TokenClass => Anchor.TokenClass as TokenClass; public char TypeCharacter { get { if(IsError) return 'e'; if(IsComment) return 'c'; if(IsSpace) return 'w'; if(IsLineEnd) return '$'; if(IsNumber) return 'n'; if(IsText) return 't'; if(IsKeyword) return 'k'; if(IsIdentifier) return 'i'; if(IsBrace) return 'b'; NotImplementedMethod(); return '?'; } } string Types => GetTypes().Stringify(","); public int StartPosition => SourcePart.Position; public int EndPosition => SourcePart.EndPosition; [DisableDump] internal Reni.SyntaxTree.Syntax Master => Anchor.Syntax; [DisableDump] public int Index => Master.Anchor.Items.IndexWhere(item => item == Anchor).AssertValue(); public IEnumerable<Item> Belonging { get { if(IsBraceLike) return Anchor.ParserLevelGroup.Select(item => new Syntax(item)); return new Item[0]; } } IEnumerable<string> GetTypes() { if(IsError) yield return "error"; if(IsComment) yield return "comment"; if(IsSpace) yield return "space"; if(IsLineEnd) yield return "line-end"; if(IsNumber) yield return "number"; if(IsText) yield return "text"; if(IsKeyword) yield return "keyword"; if(IsIdentifier) yield return "identifier"; if(IsBrace) yield return "brace"; if(IsBraceLike) yield return "brace-like"; } internal Trimmed TrimLine(SourcePart span) => new(this, span); bool Equals(Item other) => SourcePart == other.SourcePart; internal static Item LocateByPosition(BinaryTree target, SourcePosition offset) { var result = target.FindItem(offset); result.AssertIsNotNull(); var item = result.WhiteSpaces.LocateItem(offset); if(item == null) return new Syntax(result); return new WhiteSpaceItem(item, result); } internal static BinaryTree Locate(BinaryTree target, SourcePart span) { var start = LocateByPosition(target, span.Start); var end = LocateByPosition(target, span.End); var result = start.Anchor.CommonRoot(end.Anchor); result.AssertIsNotNull(); return result; } internal static Item GetRightNeighbor(Helper.Syntax target, int current) { NotImplementedFunction(target, current); return default; } internal string ShortDump() { var start = SourcePart.Start.TextPosition; return $"{start.LineNumber}/{start.ColumnNumber}: {Types}: {SourcePart.Id.Quote()}"; } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ // #define SHOW_DK2_VARIABLES // Use the Unity new GUI with Unity 4.6 or above. #if UNITY_4_6 || UNITY_5_0 #define USE_NEW_GUI #endif using System; using System.Collections; using UnityEngine; #if USE_NEW_GUI using UnityEngine.UI; # endif //------------------------------------------------------------------------------------- // ***** OVRMainMenu // /// <summary> /// OVRMainMenu is used to control the loading of different scenes. It also renders out /// a menu that allows a user to modify various Rift settings, and allow for storing /// these settings for recall later. /// /// A user of this component can add as many scenes that they would like to be able to /// have access to. /// /// OVRMainMenu is currently attached to the OVRPlayerController prefab for convenience, /// but can safely removed from it and added to another GameObject that is used for general /// Unity logic. /// /// </summary> public class OVRMainMenu : MonoBehaviour { /// <summary> /// The amount of time in seconds that it takes for the menu to fade in. /// </summary> public float FadeInTime = 2.0f; /// <summary> /// An optional texture that appears before the menu fades in. /// </summary> public UnityEngine.Texture FadeInTexture = null; /// <summary> /// An optional font that replaces Unity's default Arial. /// </summary> public Font FontReplace = null; /// <summary> /// The key that toggles the menu. /// </summary> public KeyCode MenuKey = KeyCode.Space; /// <summary> /// The key that quits the application. /// </summary> public KeyCode QuitKey = KeyCode.Escape; /// <summary> /// Scene names to show on-screen for each of the scenes in Scenes. /// </summary> public string [] SceneNames; /// <summary> /// The set of scenes that the user can jump to. /// </summary> public string [] Scenes; private bool ScenesVisible = false; // Spacing for scenes menu private int StartX = 490; private int StartY = 250; private int WidthX = 300; private int WidthY = 23; // Spacing for variables that users can change #if !USE_NEW_GUI private int VRVarsSX = 553; private int VRVarsSY = 250; private int VRVarsWidthX = 175; private int VRVarsWidthY = 23; private float AlphaFadeValue = 1.0f; #endif private int StepY = 25; // Handle to OVRCameraRig private OVRCameraRig CameraController = null; // Handle to OVRPlayerController private OVRPlayerController PlayerController = null; // Controller buttons private bool PrevStartDown; private bool PrevHatDown; private bool PrevHatUp; private bool ShowVRVars; private bool OldSpaceHit; // FPS private float UpdateInterval = 0.5f; private float Accum = 0; private int Frames = 0; private float TimeLeft = 0; private string strFPS = "FPS: 0"; private string strIPD = "IPD: 0.000"; /// <summary> /// Prediction (in ms) /// </summary> public float PredictionIncrement = 0.001f; // 1 ms private string strPrediction = "Pred: OFF"; private string strFOV = "FOV: 0.0f"; private string strHeight = "Height: 0.0f"; /// <summary> /// Controls how quickly the player's speed and rotation change based on input. /// </summary> public float SpeedRotationIncrement = 0.05f; private string strSpeedRotationMultipler = "Spd. X: 0.0f Rot. X: 0.0f"; private bool LoadingLevel = false; private int CurrentLevel = 0; // Rift detection private bool HMDPresent = false; private float RiftPresentTimeout = 0.0f; private string strRiftPresent = ""; // Replace the GUI with our own texture and 3D plane that // is attached to the rendder camera for true 3D placement private OVRGUI GuiHelper = new OVRGUI(); private GameObject GUIRenderObject = null; private RenderTexture GUIRenderTexture = null; // We want to use new Unity GUI built in 4.6 for OVRMainMenu GUI // Enable the UsingNewGUI option in the editor, // if you want to use new GUI and Unity version is higher than 4.6 #if USE_NEW_GUI private GameObject NewGUIObject = null; private GameObject RiftPresentGUIObject = null; #endif /// <summary> /// We can set the layer to be anything we want to, this allows /// a specific camera to render it. /// </summary> public string LayerName = "Default"; /// <summary> /// Crosshair rendered onto 3D plane. /// </summary> public UnityEngine.Texture CrosshairImage = null; private OVRCrosshair Crosshair = new OVRCrosshair(); // Resolution Eye Texture private string strResolutionEyeTexture = "Resolution: 0 x 0"; // Latency values private string strLatencies = "Ren: 0.0f TWrp: 0.0f PostPresent: 0.0f"; // Vision mode on/off private bool VisionMode = true; #if SHOW_DK2_VARIABLES private string strVisionMode = "Vision Enabled: ON"; #endif // We want to hold onto GridCube, for potential sharing // of the menu RenderTarget OVRGridCube GridCube = null; #region MonoBehaviour Message Handlers /// <summary> /// Awake this instance. /// </summary> void Awake() { // Find camera controller OVRCameraRig[] CameraControllers; CameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig>(); if(CameraControllers.Length == 0) Debug.LogWarning("OVRMainMenu: No OVRCameraRig attached."); else if (CameraControllers.Length > 1) Debug.LogWarning("OVRMainMenu: More then 1 OVRCameraRig attached."); else{ CameraController = CameraControllers[0]; #if USE_NEW_GUI OVRUGUI.CameraController = CameraController; #endif } // Find player controller OVRPlayerController[] PlayerControllers; PlayerControllers = gameObject.GetComponentsInChildren<OVRPlayerController>(); if(PlayerControllers.Length == 0) Debug.LogWarning("OVRMainMenu: No OVRPlayerController attached."); else if (PlayerControllers.Length > 1) Debug.LogWarning("OVRMainMenu: More then 1 OVRPlayerController attached."); else{ PlayerController = PlayerControllers[0]; #if USE_NEW_GUI OVRUGUI.PlayerController = PlayerController; #endif } #if USE_NEW_GUI // Create canvas for using new GUI NewGUIObject = new GameObject(); NewGUIObject.name = "OVRGUIMain"; NewGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = NewGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localScale = new Vector3(0.001f, 0.001f, 0.001f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; Canvas c = NewGUIObject.AddComponent<Canvas>(); c.renderMode = RenderMode.WorldSpace; c.pixelPerfect = false; #endif } /// <summary> /// Start this instance. /// </summary> void Start() { CurrentLevel = 0; PrevStartDown = false; PrevHatDown = false; PrevHatUp = false; ShowVRVars = false; OldSpaceHit = false; strFPS = "FPS: 0"; LoadingLevel = false; ScenesVisible = false; // Set the GUI target GUIRenderObject = GameObject.Instantiate(Resources.Load("OVRGUIObjectMain")) as GameObject; if(GUIRenderObject != null) { // Chnge the layer GUIRenderObject.layer = LayerMask.NameToLayer(LayerName); if(GUIRenderTexture == null) { int w = Screen.width; int h = Screen.height; // We don't need a depth buffer on this texture GUIRenderTexture = new RenderTexture(w, h, 0); GuiHelper.SetPixelResolution(w, h); // NOTE: All GUI elements are being written with pixel values based // from DK1 (1280x800). These should change to normalized locations so // that we can scale more cleanly with varying resolutions GuiHelper.SetDisplayResolution(1280.0f, 800.0f); } } // Attach GUI texture to GUI object and GUI object to Camera if(GUIRenderTexture != null && GUIRenderObject != null) { GUIRenderObject.GetComponent<Renderer>().material.mainTexture = GUIRenderTexture; if(CameraController != null) { // Grab transform of GUI object Vector3 ls = GUIRenderObject.transform.localScale; Vector3 lp = GUIRenderObject.transform.localPosition; Quaternion lr = GUIRenderObject.transform.localRotation; // Attach the GUI object to the camera GUIRenderObject.transform.parent = CameraController.centerEyeAnchor; // Reset the transform values (we will be maintaining state of the GUI object // in local state) GUIRenderObject.transform.localScale = ls; GUIRenderObject.transform.localPosition = lp; GUIRenderObject.transform.localRotation = lr; // Deactivate object until we have completed the fade-in // Also, we may want to deactive the render object if there is nothing being rendered // into the UI GUIRenderObject.SetActive(false); } } // Make sure to hide cursor if(Application.isEditor == false) { #if UNITY_5_0 Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; #else Cursor.visible = false; Screen.lockCursor = true; #endif } // CameraController updates if(CameraController != null) { // Add a GridCube component to this object GridCube = gameObject.AddComponent<OVRGridCube>(); GridCube.SetOVRCameraController(ref CameraController); } // Crosshair functionality Crosshair.Init(); Crosshair.SetCrosshairTexture(ref CrosshairImage); Crosshair.SetOVRCameraController (ref CameraController); Crosshair.SetOVRPlayerController(ref PlayerController); // Check for HMD and sensor CheckIfRiftPresent(); #if USE_NEW_GUI if (!string.IsNullOrEmpty(strRiftPresent)){ ShowRiftPresentGUI(); } #endif } /// <summary> /// Update this instance. /// </summary> void Update() { if(LoadingLevel == true) return; // Main update UpdateFPS(); // CameraController updates if(CameraController != null) { UpdateIPD(); UpdateRecenterPose(); UpdateVisionMode(); UpdateFOV(); UpdateEyeHeightOffset(); UpdateResolutionEyeTexture(); UpdateLatencyValues(); } // PlayerController updates if(PlayerController != null) { UpdateSpeedAndRotationScaleMultiplier(); UpdatePlayerControllerMovement(); } // MainMenu updates UpdateSelectCurrentLevel(); // Device updates UpdateDeviceDetection(); // Crosshair functionality Crosshair.UpdateCrosshair(); #if USE_NEW_GUI if (ShowVRVars && RiftPresentTimeout <= 0.0f) { NewGUIObject.SetActive(true); UpdateNewGUIVars(); OVRUGUI.UpdateGUI(); } else { NewGUIObject.SetActive(false); } #endif // Toggle Fullscreen if(Input.GetKeyDown(KeyCode.F11)) Screen.fullScreen = !Screen.fullScreen; if (Input.GetKeyDown(KeyCode.M)) OVRManager.display.mirrorMode = !OVRManager.display.mirrorMode; #if !UNITY_ANDROID || UNITY_EDITOR // Escape Application if (Input.GetKeyDown(QuitKey)) Application.Quit(); #endif } /// <summary> /// Updates Variables for new GUI. /// </summary> #if USE_NEW_GUI void UpdateNewGUIVars() { #if SHOW_DK2_VARIABLES // Print out Vision Mode OVRUGUI.strVisionMode = strVisionMode; #endif // Print out FPS OVRUGUI.strFPS = strFPS; // Don't draw these vars if CameraController is not present if (CameraController != null) { OVRUGUI.strPrediction = strPrediction; OVRUGUI.strIPD = strIPD; OVRUGUI.strFOV = strFOV; OVRUGUI.strResolutionEyeTexture = strResolutionEyeTexture; OVRUGUI.strLatencies = strLatencies; } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { OVRUGUI.strHeight = strHeight; OVRUGUI.strSpeedRotationMultipler = strSpeedRotationMultipler; } OVRUGUI.strRiftPresent = strRiftPresent; } #endif void OnGUI() { // Important to keep from skipping render events if (Event.current.type != EventType.Repaint) return; #if !USE_NEW_GUI // Fade in screen if(AlphaFadeValue > 0.0f) { AlphaFadeValue -= Mathf.Clamp01(Time.deltaTime / FadeInTime); if(AlphaFadeValue < 0.0f) { AlphaFadeValue = 0.0f; } else { GUI.color = new Color(0, 0, 0, AlphaFadeValue); GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture ); return; } } #endif // We can turn on the render object so we can render the on-screen menu if(GUIRenderObject != null) { if (ScenesVisible || ShowVRVars || Crosshair.IsCrosshairVisible() || RiftPresentTimeout > 0.0f) { GUIRenderObject.SetActive(true); } else { GUIRenderObject.SetActive(false); } } //*** // Set the GUI matrix to deal with portrait mode Vector3 scale = Vector3.one; Matrix4x4 svMat = GUI.matrix; // save current matrix // substitute matrix - only scale is altered from standard GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale); // Cache current active render texture RenderTexture previousActive = RenderTexture.active; // if set, we will render to this texture if(GUIRenderTexture != null && GUIRenderObject.activeSelf) { RenderTexture.active = GUIRenderTexture; GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f)); } // Update OVRGUI functions (will be deprecated eventually when 2D renderingc // is removed from GUI) GuiHelper.SetFontReplace(FontReplace); // If true, we are displaying information about the Rift not being detected // So do not show anything else if(GUIShowRiftDetected() != true) { GUIShowLevels(); GUIShowVRVariables(); } // The cross-hair may need to go away at some point, unless someone finds it // useful Crosshair.OnGUICrosshair(); // Restore active render texture if (GUIRenderObject.activeSelf) { RenderTexture.active = previousActive; } // *** // Restore previous GUI matrix GUI.matrix = svMat; } #endregion #region Internal State Management Functions /// <summary> /// Updates the FPS. /// </summary> void UpdateFPS() { TimeLeft -= Time.unscaledDeltaTime; Accum += Time.unscaledDeltaTime; ++Frames; // Interval ended - update GUI text and start new interval if( TimeLeft <= 0.0 ) { // display two fractional digits (f2 format) float fps = Frames / Accum; if(ShowVRVars == true)// limit gc strFPS = System.String.Format("FPS: {0:F2}",fps); TimeLeft += UpdateInterval; Accum = 0.0f; Frames = 0; } } /// <summary> /// Updates the IPD. /// </summary> void UpdateIPD() { if(ShowVRVars == true) // limit gc { strIPD = System.String.Format("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f); } } void UpdateRecenterPose() { if(Input.GetKeyDown(KeyCode.R)) { OVRManager.display.RecenterPose(); } } /// <summary> /// Updates the vision mode. /// </summary> void UpdateVisionMode() { if (Input.GetKeyDown(KeyCode.F2)) { VisionMode = !VisionMode; OVRManager.tracker.isEnabled = VisionMode; #if SHOW_DK2_VARIABLES strVisionMode = VisionMode ? "Vision Enabled: ON" : "Vision Enabled: OFF"; #endif } } /// <summary> /// Updates the FOV. /// </summary> void UpdateFOV() { if(ShowVRVars == true)// limit gc { OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); strFOV = System.String.Format ("FOV (deg): {0:F3}", eyeDesc.fov.y); } } /// <summary> /// Updates resolution of eye texture /// </summary> void UpdateResolutionEyeTexture() { if (ShowVRVars == true) // limit gc { OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Right); float scale = OVRManager.instance.virtualTextureScale; float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x)); float h = (int)(scale * (float)Mathf.Max(leftEyeDesc.resolution.y, rightEyeDesc.resolution.y)); strResolutionEyeTexture = System.String.Format("Resolution : {0} x {1}", w, h); } } /// <summary> /// Updates latency values /// </summary> void UpdateLatencyValues() { #if !UNITY_ANDROID || UNITY_EDITOR if (ShowVRVars == true) // limit gc { OVRDisplay.LatencyData latency = OVRManager.display.latency; if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f) strLatencies = System.String.Format("Latency values are not available."); else strLatencies = System.String.Format("R: {0:F3} TW: {1:F3} PP: {2:F3} RE: {3:F3} TWE: {4:F3}", latency.render, latency.timeWarp, latency.postPresent, latency.renderError, latency.timeWarpError); } #endif } /// <summary> /// Updates the eye height offset. /// </summary> void UpdateEyeHeightOffset() { if(ShowVRVars == true)// limit gc { float eyeHeight = OVRManager.profile.eyeHeight; strHeight = System.String.Format ("Eye Height (m): {0:F3}", eyeHeight); } } /// <summary> /// Updates the speed and rotation scale multiplier. /// </summary> void UpdateSpeedAndRotationScaleMultiplier() { float moveScaleMultiplier = 0.0f; PlayerController.GetMoveScaleMultiplier(ref moveScaleMultiplier); if(Input.GetKeyDown(KeyCode.Alpha7)) moveScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown(KeyCode.Alpha8)) moveScaleMultiplier += SpeedRotationIncrement; PlayerController.SetMoveScaleMultiplier(moveScaleMultiplier); float rotationScaleMultiplier = 0.0f; PlayerController.GetRotationScaleMultiplier(ref rotationScaleMultiplier); if(Input.GetKeyDown(KeyCode.Alpha9)) rotationScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown(KeyCode.Alpha0)) rotationScaleMultiplier += SpeedRotationIncrement; PlayerController.SetRotationScaleMultiplier(rotationScaleMultiplier); if(ShowVRVars == true)// limit gc strSpeedRotationMultipler = System.String.Format ("Spd.X: {0:F2} Rot.X: {1:F2}", moveScaleMultiplier, rotationScaleMultiplier); } /// <summary> /// Updates the player controller movement. /// </summary> void UpdatePlayerControllerMovement() { if(PlayerController != null) PlayerController.SetHaltUpdateMovement(ScenesVisible); } /// <summary> /// Updates the select current level. /// </summary> void UpdateSelectCurrentLevel() { ShowLevels(); if (!ScenesVisible) return; CurrentLevel = GetCurrentLevel(); if (Scenes.Length != 0 && (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.A) || Input.GetKeyDown(KeyCode.Return))) { LoadingLevel = true; Application.LoadLevelAsync(Scenes[CurrentLevel]); } } /// <summary> /// Shows the levels. /// </summary> /// <returns><c>true</c>, if levels was shown, <c>false</c> otherwise.</returns> bool ShowLevels() { if (Scenes.Length == 0) { ScenesVisible = false; return ScenesVisible; } bool curStartDown = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Start); bool startPressed = (curStartDown && !PrevStartDown) || Input.GetKeyDown(KeyCode.RightShift); PrevStartDown = curStartDown; if (startPressed) { ScenesVisible = !ScenesVisible; } return ScenesVisible; } /// <summary> /// Gets the current level. /// </summary> /// <returns>The current level.</returns> int GetCurrentLevel() { bool curHatDown = false; if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true) curHatDown = true; bool curHatUp = false; if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true) curHatUp = true; if((PrevHatDown == false) && (curHatDown == true) || Input.GetKeyDown(KeyCode.DownArrow)) { CurrentLevel = (CurrentLevel + 1) % SceneNames.Length; } else if((PrevHatUp == false) && (curHatUp == true) || Input.GetKeyDown(KeyCode.UpArrow)) { CurrentLevel--; if(CurrentLevel < 0) CurrentLevel = SceneNames.Length - 1; } PrevHatDown = curHatDown; PrevHatUp = curHatUp; return CurrentLevel; } #endregion #region Internal GUI Functions /// <summary> /// Show the GUI levels. /// </summary> void GUIShowLevels() { if(ScenesVisible == true) { // Darken the background by rendering fade texture GUI.color = new Color(0, 0, 0, 0.5f); GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture ); GUI.color = Color.white; if(LoadingLevel == true) { string loading = "LOADING..."; GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref loading, Color.yellow); return; } for (int i = 0; i < SceneNames.Length; i++) { Color c; if(i == CurrentLevel) c = Color.yellow; else c = Color.black; int y = StartY + (i * StepY); GuiHelper.StereoBox (StartX, y, WidthX, WidthY, ref SceneNames[i], c); } } } /// <summary> /// Show the VR variables. /// </summary> void GUIShowVRVariables() { bool SpaceHit = Input.GetKey(MenuKey); if ((OldSpaceHit == false) && (SpaceHit == true)) { if (ShowVRVars == true) { ShowVRVars = false; } else { ShowVRVars = true; #if USE_NEW_GUI OVRUGUI.InitUIComponent = ShowVRVars; #endif } } OldSpaceHit = SpaceHit; // Do not render if we are not showing if (ShowVRVars == false) return; #if !USE_NEW_GUI int y = VRVarsSY; #if SHOW_DK2_VARIABLES // Print out Vision Mode GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strVisionMode, Color.green); #endif // Draw FPS GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFPS, Color.green); // Don't draw these vars if CameraController is not present if (CameraController != null) { GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strPrediction, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strIPD, Color.yellow); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFOV, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strResolutionEyeTexture, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strLatencies, Color.white); } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strHeight, Color.yellow); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strSpeedRotationMultipler, Color.white); } #endif } // RIFT DETECTION /// <summary> /// Checks to see if HMD and / or sensor is available, and displays a /// message if it is not. /// </summary> void CheckIfRiftPresent() { HMDPresent = OVRManager.display.isPresent; if (!HMDPresent) { RiftPresentTimeout = 15.0f; if (!HMDPresent) strRiftPresent = "NO HMD DETECTED"; #if USE_NEW_GUI OVRUGUI.strRiftPresent = strRiftPresent; #endif } } /// <summary> /// Show if Rift is detected. /// </summary> /// <returns><c>true</c>, if show rift detected was GUIed, <c>false</c> otherwise.</returns> bool GUIShowRiftDetected() { #if !USE_NEW_GUI if(RiftPresentTimeout > 0.0f) { GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref strRiftPresent, Color.white); return true; } #else if(RiftPresentTimeout < 0.0f) DestroyImmediate(RiftPresentGUIObject); #endif return false; } /// <summary> /// Updates the device detection. /// </summary> void UpdateDeviceDetection() { if(RiftPresentTimeout > 0.0f) RiftPresentTimeout -= Time.deltaTime; } /// <summary> /// Show rift present GUI with new GUI /// </summary> void ShowRiftPresentGUI() { #if USE_NEW_GUI RiftPresentGUIObject = new GameObject(); RiftPresentGUIObject.name = "RiftPresentGUIMain"; RiftPresentGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = RiftPresentGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; r.localScale = new Vector3(0.001f, 0.001f, 0.001f); Canvas c = RiftPresentGUIObject.AddComponent<Canvas>(); c.renderMode = RenderMode.WorldSpace; c.pixelPerfect = false; OVRUGUI.RiftPresentGUI(RiftPresentGUIObject); #endif } #endregion /// <summary> /// Initialize OVRUGUI on OnDestroy /// </summary> void OnDestroy() { #if USE_NEW_GUI OVRUGUI.isInited = false; #endif } }
//----------------------------------------------------------------------- // <copyright file="FlowConcatAllSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System.Linq; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Xunit; using Xunit.Abstractions; using Akka.Streams.Dsl.Internal; using Reactive.Streams; // ReSharper disable InvokeAsExtensionMethod namespace Akka.Streams.Tests.Dsl { public class FlowConcatAllSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public FlowConcatAllSpec(ITestOutputHelper helper) : base(helper) { var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 2); Materializer = ActorMaterializer.Create(Sys, settings); } private static readonly TestException TestException = new TestException("test"); [Fact] public void ConcatAll_must_work_in_the_happy_case() { this.AssertAllStagesStopped(() => { var s1 = Source.From(new[] {1, 2}); var s2 = Source.From(new int[] {}); var s3 = Source.From(new[] {3}); var s4 = Source.From(new[] {4, 5, 6}); var s5 = Source.From(new[] {7, 8, 9, 10}); var main = Source.From(new[] {s1, s2, s3, s4, s5}); var subscriber = TestSubscriber.CreateManualProbe<int>(this); main.ConcatMany(s => s).To(Sink.FromSubscriber(subscriber)).Run(Materializer); var subscription = subscriber.ExpectSubscription(); subscription.Request(10); for (var i = 1; i <= 10; i++) subscriber.ExpectNext(i); subscription.Request(1); subscriber.ExpectComplete(); }, Materializer); } [Fact] public void ConcatAll_must_work_together_with_SplitWhen() { var subscriber = TestSubscriber.CreateProbe<int>(this); var source = Source.From(Enumerable.Range(1, 10)) .SplitWhen(x => x%2 == 0) .PrefixAndTail(0) .Select(x => x.Item2) .ConcatSubstream() .ConcatMany(x => x); ((Source<int, NotUsed>) source).RunWith(Sink.FromSubscriber(subscriber), Materializer); for (var i = 1; i <= 10; i++) subscriber.RequestNext(i); subscriber.Request(1); subscriber.ExpectComplete();} [Fact] public void ConcatAll_must_on_OnError_on_master_stream_cancel_the_current_open_substream_and_signal_error() { this.AssertAllStagesStopped(() => { var publisher = TestPublisher.CreateManualProbe<Source<int, NotUsed>>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .ConcatMany(x => x) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1000); var substreamPublisher = TestPublisher.CreateManualProbe<int>(this); var substreamFlow = Source.FromPublisher(substreamPublisher); upstream.ExpectRequest(); upstream.SendNext(substreamFlow); var subUpstream = substreamPublisher.ExpectSubscription(); upstream.SendError(TestException); subscriber.ExpectError().Should().Be(TestException); subUpstream.ExpectCancellation(); }, Materializer); } [Fact] public void ConcatAll_must_on_OnError_on_master_stream_cancel_the_currently_opening_substream_and_signal_error() { this.AssertAllStagesStopped(() => { var publisher = TestPublisher.CreateManualProbe<Source<int, NotUsed>>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .ConcatMany(x => x) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1000); var substreamPublisher = TestPublisher.CreateManualProbe<int>(this, false); var substreamFlow = Source.FromPublisher(substreamPublisher); upstream.ExpectRequest(); upstream.SendNext(substreamFlow); var subUpstream = substreamPublisher.ExpectSubscription(); upstream.SendError(TestException); subUpstream.SendOnSubscribe(); subscriber.ExpectError().Should().Be(TestException); subUpstream.ExpectCancellation(); }, Materializer); } [Fact] public void ConcatAll_must_on_OnError_on_opening_substream_cancel_the_master_stream_and_signal_error() { this.AssertAllStagesStopped(() => { var publisher = TestPublisher.CreateManualProbe<Source<int, NotUsed>>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .ConcatMany<Source<int,NotUsed>,int,NotUsed>(x => { throw TestException; }) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1000); var substreamPublisher = TestPublisher.CreateManualProbe<int>(this); var substreamFlow = Source.FromPublisher(substreamPublisher); upstream.ExpectRequest(); upstream.SendNext(substreamFlow); subscriber.ExpectError().Should().Be(TestException); upstream.ExpectCancellation(); }, Materializer); } [Fact] public void ConcatAll_must_on_OnError_on_open_substream_cancel_the_master_stream_and_signal_error() { this.AssertAllStagesStopped(() => { var publisher = TestPublisher.CreateManualProbe<Source<int, NotUsed>>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .ConcatMany(x => x) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1000); var substreamPublisher = TestPublisher.CreateManualProbe<int>(this); var substreamFlow = Source.FromPublisher(substreamPublisher); upstream.ExpectRequest(); upstream.SendNext(substreamFlow); var subUpstream = substreamPublisher.ExpectSubscription(); subUpstream.SendError(TestException); subscriber.ExpectError().Should().Be(TestException); upstream.ExpectCancellation(); }, Materializer); } [Fact] public void ConcatAll_must_on_cancellation_cancel_the_current_open_substream_and_the_master_stream() { this.AssertAllStagesStopped(() => { var publisher = TestPublisher.CreateManualProbe<Source<int, NotUsed>>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .ConcatMany(x => x) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1000); var substreamPublisher = TestPublisher.CreateManualProbe<int>(this); var substreamFlow = Source.FromPublisher(substreamPublisher); upstream.ExpectRequest(); upstream.SendNext(substreamFlow); var subUpstream = substreamPublisher.ExpectSubscription(); downstream.Cancel(); subUpstream.ExpectCancellation(); upstream.ExpectCancellation(); }, Materializer); } [Fact] public void ConcatAll_must_on_cancellation_cancel_the_currently_opening_substream_and_the_master_stream() { this.AssertAllStagesStopped(() => { var publisher = TestPublisher.CreateManualProbe<Source<int, NotUsed>>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .ConcatMany(x => x) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var upstream = publisher.ExpectSubscription(); var downstream = subscriber.ExpectSubscription(); downstream.Request(1000); var substreamPublisher = TestPublisher.CreateManualProbe<int>(this, false); var substreamFlow = Source.FromPublisher(substreamPublisher); upstream.ExpectRequest(); upstream.SendNext(substreamFlow); var subUpstream = substreamPublisher.ExpectSubscription(); downstream.Cancel(); subUpstream.SendOnSubscribe(); subUpstream.ExpectCancellation(); upstream.ExpectCancellation(); }, Materializer); } [Fact] public void ConcatAll_must_pass_along_early_cancellation() { this.AssertAllStagesStopped(() => { var up = TestPublisher.CreateManualProbe<Source<int, NotUsed>>(this); var down = TestSubscriber.CreateManualProbe<int>(this); var flowSubscriber = Source.AsSubscriber<Source<int, NotUsed>>() .ConcatMany(x => x.MapMaterializedValue<ISubscriber<Source<int, NotUsed>>>(_ => null)) .To(Sink.FromSubscriber(down)) .Run(Materializer); var downstream = down.ExpectSubscription(); downstream.Cancel(); up.Subscribe(flowSubscriber); var upSub = up.ExpectSubscription(); upSub.ExpectCancellation(); }, Materializer); } } }
//------------------------------------------------------------------------------ // <copyright file="TrackBar.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Windows.Forms { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Diagnostics; using System; using System.Security.Permissions; using Microsoft.Win32; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.ComponentModel.Design; using System.Windows.Forms.Layout; using System.Globalization; /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar"]/*' /> /// <devdoc> /// The TrackBar is a scrollable control similar to the ScrollBar, but /// has a different UI. You can configure ranges through which it should /// scroll, and also define increments for off-button clicks. It can be /// aligned horizontally or vertically. You can also configure how many /// 'ticks' are shown for the total range of values /// </devdoc> [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), DefaultProperty("Value"), DefaultEvent("Scroll"), DefaultBindingProperty("Value"), Designer("System.Windows.Forms.Design.TrackBarDesigner, " + AssemblyRef.SystemDesign), SRDescription(SR.DescriptionTrackBar) ] public class TrackBar : Control, ISupportInitialize { private static readonly object EVENT_SCROLL = new object(); private static readonly object EVENT_VALUECHANGED = new object(); private static readonly object EVENT_RIGHTTOLEFTLAYOUTCHANGED = new object(); private bool autoSize = true; private int largeChange = 5; private int maximum = 10; private int minimum = 0; private Orientation orientation = System.Windows.Forms.Orientation.Horizontal; private int value = 0; private int smallChange = 1; private int tickFrequency = 1; private TickStyle tickStyle = System.Windows.Forms.TickStyle.BottomRight; private int requestedDim; // Mouse wheel movement private int cumulativeWheelData = 0; // Disable value range checking while initializing the control private bool initializing = false; private bool rightToLeftLayout = false; /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.TrackBar"]/*' /> /// <devdoc> /// Creates a new TrackBar control with a default range of 0..10 and /// ticks shown every value. /// </devdoc> public TrackBar() : base() { SetStyle(ControlStyles.UserPaint, false); SetStyle(ControlStyles.UseTextForAccessibility, false); requestedDim = PreferredDimension; } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.AutoSize"]/*' /> /// <devdoc> /// Indicates if the control is being auto-sized. If true, the /// TrackBar will adjust either its height or width [depending on /// orientation] to make sure that only the required amount of /// space is used. /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(true), SRDescription(SR.TrackBarAutoSizeDescr), Browsable(true), EditorBrowsable(EditorBrowsableState.Always), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] public override bool AutoSize { get { return autoSize; } set { // Note that we intentionally do not call base. Labels size themselves by // overriding SetBoundsCore (old RTM code). We let CommonProperties.GetAutoSize // continue to return false to keep our LayoutEngines from messing with TextBoxes. // This is done for backwards compatibility since the new AutoSize behavior differs. if (autoSize != value) { autoSize = value; if (orientation == Orientation.Horizontal) { SetStyle(ControlStyles.FixedHeight, autoSize); SetStyle(ControlStyles.FixedWidth, false); } else { SetStyle(ControlStyles.FixedWidth, autoSize); SetStyle(ControlStyles.FixedHeight, false); } AdjustSize(); OnAutoSizeChanged(EventArgs.Empty); } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.AutoSizeChanged"]/*' /> [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnAutoSizeChangedDescr)] [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] new public event EventHandler AutoSizeChanged { add { base.AutoSizeChanged += value; } remove { base.AutoSizeChanged -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.BackgroundImage"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Image BackgroundImage { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.BackgroundImageChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackgroundImageChanged { add { base.BackgroundImageChanged += value; } remove { base.BackgroundImageChanged -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.BackgroundImageLayout"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override ImageLayout BackgroundImageLayout { get { return base.BackgroundImageLayout; } set { base.BackgroundImageLayout = value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.BackgroundImageLayoutChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackgroundImageLayoutChanged { add { base.BackgroundImageLayoutChanged += value; } remove { base.BackgroundImageLayoutChanged -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.CreateParams"]/*' /> /// <devdoc> /// This is called when creating a window. Inheriting classes can override /// this to add extra functionality, but should not forget to first call /// base.getCreateParams() to make sure the control continues to work /// correctly. /// </devdoc> /// <internalonly/> protected override CreateParams CreateParams { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] get { CreateParams cp = base.CreateParams; cp.ClassName = NativeMethods.WC_TRACKBAR; switch (tickStyle) { case TickStyle.None: cp.Style |= NativeMethods.TBS_NOTICKS; break; case TickStyle.TopLeft: cp.Style |= (NativeMethods.TBS_AUTOTICKS | NativeMethods.TBS_TOP); break; case TickStyle.BottomRight: cp.Style |= (NativeMethods.TBS_AUTOTICKS | NativeMethods.TBS_BOTTOM); break; case TickStyle.Both: cp.Style |= (NativeMethods.TBS_AUTOTICKS | NativeMethods.TBS_BOTH); break; } if (orientation == Orientation.Vertical) { cp.Style |= NativeMethods.TBS_VERT; // HORIZ == 0 } if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) { //We want to turn on mirroring for Trackbar explicitly. cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL | NativeMethods.WS_EX_NOINHERITLAYOUT; //Don't need these styles when mirroring is turned on. cp.ExStyle &= ~(NativeMethods.WS_EX_RTLREADING | NativeMethods.WS_EX_RIGHT | NativeMethods.WS_EX_LEFTSCROLLBAR); } return cp; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.DefaultImeMode"]/*' /> /// <internalonly/> protected override ImeMode DefaultImeMode { get { return ImeMode.Disable; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.DefaultSize"]/*' /> /// <devdoc> /// Deriving classes can override this to configure a default size for their control. /// This is more efficient than setting the size in the control's constructor. /// </devdoc> protected override Size DefaultSize { get { return new Size(104, PreferredDimension); } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.DoubleBuffered"]/*' /> /// <devdoc> /// This property is overridden and hidden from statement completion /// on controls that are based on Win32 Native Controls. /// </devdoc> [EditorBrowsable(EditorBrowsableState.Never)] protected override bool DoubleBuffered { get { return base.DoubleBuffered; } set { base.DoubleBuffered = value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.Font"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Font Font { get { return base.Font; } set { base.Font = value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.FontChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler FontChanged { add { base.FontChanged += value; } remove { base.FontChanged -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.ForeColor"]/*' /> /// <devdoc> /// The current foreground color of the TrackBar. Note that users /// are unable to change this. It is always Color.WINDOWTEXT /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Color ForeColor { get { return SystemColors.WindowText; } set { } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.ForeColorChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler ForeColorChanged { add { base.ForeColorChanged += value; } remove { base.ForeColorChanged -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.ImeMode"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public ImeMode ImeMode { get { return base.ImeMode; } set { base.ImeMode = value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.ImeModeChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler ImeModeChanged { add { base.ImeModeChanged += value; } remove { base.ImeModeChanged -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.LargeChange"]/*' /> /// <devdoc> /// The number of ticks by which the TrackBar will change when an /// event considered a "large change" occurs. These include, Clicking the /// mouse to the side of the button, or using the PgUp/PgDn keys on the /// keyboard. /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(5), SRDescription(SR.TrackBarLargeChangeDescr) ] public int LargeChange { get { return largeChange; } set { if (value < 0) { throw new ArgumentOutOfRangeException("LargeChange", SR.GetString(SR.TrackBarLargeChangeError, value)); } if (largeChange != value) { largeChange = value; if (IsHandleCreated) { SendMessage(NativeMethods.TBM_SETPAGESIZE, 0, value); } } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.Maximum"]/*' /> /// <devdoc> /// The upper limit of the range this TrackBar is working with. /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(10), RefreshProperties(RefreshProperties.All), SRDescription(SR.TrackBarMaximumDescr) ] public int Maximum { get { return maximum; } set { if (maximum != value) { if (value < minimum) { minimum = value; } SetRange(minimum, value); } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.Minimum"]/*' /> /// <devdoc> /// The lower limit of the range this TrackBar is working with. /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(0), RefreshProperties(RefreshProperties.All), SRDescription(SR.TrackBarMinimumDescr) ] public int Minimum { get { return minimum; } set { if (minimum != value) { if (value > maximum) { maximum = value; } SetRange(value, maximum); } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.Orientation"]/*' /> /// <devdoc> /// <para>The orientation for this TrackBar. Valid values are from /// the Orientation enumeration. The control currently supports being /// oriented horizontally and vertically.</para> /// </devdoc> [ SRCategory(SR.CatAppearance), DefaultValue(Orientation.Horizontal), Localizable(true), SRDescription(SR.TrackBarOrientationDescr) ] public Orientation Orientation { get { return orientation; } set { //valid values are 0x0 to 0x1 if (!ClientUtils.IsEnumValid(value, (int)value, (int)Orientation.Horizontal, (int)Orientation.Vertical)) { throw new InvalidEnumArgumentException("value", (int)value, typeof(Orientation)); } if (orientation != value) { orientation = value; if (orientation == Orientation.Horizontal) { SetStyle(ControlStyles.FixedHeight, autoSize); SetStyle(ControlStyles.FixedWidth, false); Width = requestedDim; } else { SetStyle(ControlStyles.FixedHeight, false); SetStyle(ControlStyles.FixedWidth, autoSize); Height = requestedDim; } if (IsHandleCreated) { Rectangle r = Bounds; RecreateHandle(); SetBounds(r.X, r.Y, r.Height, r.Width, BoundsSpecified.All); AdjustSize(); } } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.Padding"]/*' /> /// <devdoc> /// <para> /// <para>[To be supplied.]</para> /// </para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public new Padding Padding { get { return base.Padding; } set { base.Padding = value;} } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] public new event EventHandler PaddingChanged { add { base.PaddingChanged += value; } remove { base.PaddingChanged -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.PreferredDimension"]/*' /> /// <devdoc> /// Little private routine that helps with auto-sizing. /// </devdoc> /// <internalonly/> private int PreferredDimension { get { int cyhscroll = UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CYHSCROLL); // this is our preferred size // return((cyhscroll * 8) / 3); } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.PreferredDimension"]/*' /> /// <devdoc> /// Redraw control, if the handle's created /// </devdoc> /// <internalonly/> private void RedrawControl() { if (IsHandleCreated) { //The '1' in the call to SendMessage below indicates that the //trackbar should be redrawn (see TBM_SETRANGEMAX in MSDN) SendMessage(NativeMethods.TBM_SETRANGEMAX, 1, maximum); Invalidate(); } } /// <include file='doc\Trackbar.uex' path='docs/doc[@for="Trackbar.RightToLeftLayout"]/*' /> /// <devdoc> /// This is used for international applications where the language /// is written from RightToLeft. When this property is true, // and the RightToLeft property is true, mirroring will be turned on on the trackbar. /// </devdoc> [ SRCategory(SR.CatAppearance), Localizable(true), DefaultValue(false), SRDescription(SR.ControlRightToLeftLayoutDescr) ] public virtual bool RightToLeftLayout { get { return rightToLeftLayout; } set { if (value != rightToLeftLayout) { rightToLeftLayout = value; using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) { OnRightToLeftLayoutChanged(EventArgs.Empty); } } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.SmallChange"]/*' /> /// <devdoc> /// The number of ticks by which the TrackBar will change when an /// event considered a "small change" occurs. These are most commonly /// seen by using the arrow keys to move the TrackBar thumb around. /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(1), SRDescription(SR.TrackBarSmallChangeDescr) ] public int SmallChange { get { return smallChange; } set { if (value < 0) { throw new ArgumentOutOfRangeException("SmallChange", SR.GetString(SR.TrackBarSmallChangeError, value)); } if (smallChange != value) { smallChange = value; if (IsHandleCreated) { SendMessage(NativeMethods.TBM_SETLINESIZE, 0, value); } } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.Text"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)] public override string Text { get { return base.Text; } set { base.Text = value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.TextChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler TextChanged { add { base.TextChanged += value; } remove { base.TextChanged -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.TickStyle"]/*' /> /// <devdoc> /// Indicates how the TrackBar control will draw itself. This affects /// both where the ticks will be drawn in relation to the moveable thumb, /// and how the thumb itself will be drawn. values are taken from the /// TickStyle enumeration. /// </devdoc> [ SRCategory(SR.CatAppearance), DefaultValue(TickStyle.BottomRight), SRDescription(SR.TrackBarTickStyleDescr) ] public TickStyle TickStyle { get { return tickStyle; } set { // Confirm that value is a valid enum //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)TickStyle.None, (int)TickStyle.Both)) { throw new InvalidEnumArgumentException("value", (int)value, typeof(TickStyle)); } if (tickStyle != value) { tickStyle = value; RecreateHandle(); } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.TickFrequency"]/*' /> /// <devdoc> /// Indicates just how many ticks will be drawn. For a TrackBar with a /// range of 0..100, it might be impractical to draw all 100 ticks for a /// very small control. Passing in a value of 5 here would only draw /// 20 ticks -- i.e. Each tick would represent 5 units in the TrackBars /// range of values. /// </devdoc> [ SRCategory(SR.CatAppearance), DefaultValue(1), SRDescription(SR.TrackBarTickFrequencyDescr) ] public int TickFrequency { get { return tickFrequency; } set { // SEC. if (tickFrequency != value) { tickFrequency = value; if (IsHandleCreated) { SendMessage(NativeMethods.TBM_SETTICFREQ, value, 0); Invalidate(); } } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.Value"]/*' /> /// <devdoc> /// The current location of the TrackBar thumb. This value must /// be between the lower and upper limits of the TrackBar range, of course. /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(0), Bindable(true), SRDescription(SR.TrackBarValueDescr) ] public int Value { get { GetTrackBarValue(); return value; } set { if (this.value != value) { if (!initializing && ((value < minimum) || (value > maximum))) throw new ArgumentOutOfRangeException("Value", SR.GetString(SR.InvalidBoundArgument, "Value", (value).ToString(CultureInfo.CurrentCulture), "'Minimum'", "'Maximum'")); this.value = value; SetTrackBarPosition(); OnValueChanged(EventArgs.Empty); } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.Click"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler Click { add { base.Click += value; } remove { base.Click -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.DoubleClick"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler DoubleClick { add { base.DoubleClick += value; } remove { base.DoubleClick -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.MouseClick"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event MouseEventHandler MouseClick { add { base.MouseClick += value; } remove { base.MouseClick -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.MouseDoubleClick"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event MouseEventHandler MouseDoubleClick { add { base.MouseDoubleClick += value; } remove { base.MouseDoubleClick -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.RightToLeftLayoutChanged"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnRightToLeftLayoutChangedDescr)] public event EventHandler RightToLeftLayoutChanged { add { Events.AddHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); } remove { Events.RemoveHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value); } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.Scroll"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [SRCategory(SR.CatBehavior), SRDescription(SR.TrackBarOnScrollDescr)] public event EventHandler Scroll { add { Events.AddHandler(EVENT_SCROLL, value); } remove { Events.RemoveHandler(EVENT_SCROLL, value); } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.OnPaint"]/*' /> /// <devdoc> /// TrackBar Onpaint. /// </devdoc> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event PaintEventHandler Paint { add { base.Paint += value; } remove { base.Paint -= value; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.ValueChanged"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [SRCategory(SR.CatAction), SRDescription(SR.valueChangedEventDescr)] public event EventHandler ValueChanged { add { Events.AddHandler(EVENT_VALUECHANGED, value); } remove { Events.RemoveHandler(EVENT_VALUECHANGED, value); } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.AdjustSize"]/*' /> /// <devdoc> /// Enforces autoSizing /// </devdoc> /// <internalonly/> private void AdjustSize() { if (IsHandleCreated) { int saveDim = requestedDim; try { if (orientation == Orientation.Horizontal) Height = autoSize ? PreferredDimension : saveDim; else Width = autoSize ? PreferredDimension : saveDim; } finally { requestedDim = saveDim; } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.BeginInit"]/*' /> /// <devdoc> /// Handles tasks required when the control is being initialized. /// </devdoc> /// <internalonly/> public void BeginInit() { initializing = true; } // Constrain the current value of the control to be within // the minimum and maximum. // private void ConstrainValue() { // Don't constrain the value while we're initializing the control if (initializing) { return; } Debug.Assert(minimum <= maximum, "Minimum should be <= Maximum"); // Keep the current value within the minimum and maximum if (Value < minimum) { Value = minimum; } if (Value > maximum) { Value = maximum; } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.CreateHandle"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> protected override void CreateHandle() { if (!RecreatingHandle) { IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate(); try { NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX(); icc.dwICC = NativeMethods.ICC_BAR_CLASSES; SafeNativeMethods.InitCommonControlsEx(icc); } finally { UnsafeNativeMethods.ThemingScope.Deactivate(userCookie); } } base.CreateHandle(); } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.EndInit"]/*' /> /// <devdoc> /// Called when initialization of the control is complete. /// </devdoc> /// <internalonly/> public void EndInit() { initializing = false; // Make sure the value is constrained by the minimum and maximum ConstrainValue(); } private void GetTrackBarValue() { if (IsHandleCreated) { value = unchecked( (int) (long)SendMessage(NativeMethods.TBM_GETPOS, 0, 0)); // See SetTrackBarValue() for a description of why we sometimes reflect the trackbar value // if (orientation == Orientation.Vertical) { // Reflect value value = Minimum + Maximum - value; } // Reflect for a RightToLeft horizontal trackbar // if (orientation == Orientation.Horizontal && RightToLeft == RightToLeft.Yes && !IsMirrored) { value = Minimum + Maximum - value; } } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.IsInputKey"]/*' /> /// <devdoc> /// Handling special input keys, such as pgup, pgdown, home, end, etc... /// </devdoc> protected override bool IsInputKey(Keys keyData) { if ((keyData & Keys.Alt) == Keys.Alt) return false; switch (keyData & Keys.KeyCode) { case Keys.PageUp: case Keys.PageDown: case Keys.Home: case Keys.End: return true; } return base.IsInputKey(keyData); } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.OnHandleCreated"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); SendMessage(NativeMethods.TBM_SETRANGEMIN, 0, minimum); SendMessage(NativeMethods.TBM_SETRANGEMAX, 0, maximum); SendMessage(NativeMethods.TBM_SETTICFREQ, tickFrequency, 0); SendMessage(NativeMethods.TBM_SETPAGESIZE, 0, largeChange); SendMessage(NativeMethods.TBM_SETLINESIZE, 0, smallChange); SetTrackBarPosition(); AdjustSize(); } /// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnRightToLeftLayoutChanged"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { if (GetAnyDisposingInHierarchy()) { return; } if (RightToLeft == RightToLeft.Yes) { RecreateHandle(); } EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler; if (eh != null) { eh(this, e); } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.OnScroll"]/*' /> /// <devdoc> /// Actually fires the "scroll" event. Inheriting classes should override /// this method in favor of actually adding an EventHandler for this /// event. Inheriting classes should not forget to call /// base.onScroll(e) /// </devdoc> protected virtual void OnScroll(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_SCROLL]; if (handler != null) handler(this,e); } /// <include file='doc\Trackbar.uex' path='docs/doc[@for="Trackbar.OnMouseWheel"]/*' /> /// <devdoc> /// <para>Raises the <see cref='System.Windows.Forms.Control.MouseWheel'/> event.</para> /// </devdoc> [EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnMouseWheel(MouseEventArgs e) { base.OnMouseWheel( e ); HandledMouseEventArgs hme = e as HandledMouseEventArgs; if (hme != null) { if (hme.Handled) { return; } hme.Handled = true; } if ((ModifierKeys & (Keys.Shift | Keys.Alt)) != 0 || MouseButtons != MouseButtons.None) { return; // Do not scroll when Shift or Alt key is down, or when a mouse button is down. } int wheelScrollLines = SystemInformation.MouseWheelScrollLines; if (wheelScrollLines == 0) { return; // Do not scroll when the user system setting is 0 lines per notch } Debug.Assert(this.cumulativeWheelData > -NativeMethods.WHEEL_DELTA, "cumulativeWheelData is too small"); Debug.Assert(this.cumulativeWheelData < NativeMethods.WHEEL_DELTA, "cumulativeWheelData is too big"); this.cumulativeWheelData += e.Delta; float partialNotches; partialNotches = (float)this.cumulativeWheelData / (float)NativeMethods.WHEEL_DELTA; if (wheelScrollLines == -1) { wheelScrollLines = TickFrequency; } // Evaluate number of bands to scroll int scrollBands = (int)((float)wheelScrollLines * partialNotches); if (scrollBands != 0) { int absScrollBands; if (scrollBands > 0) { absScrollBands = scrollBands; Value = Math.Min(absScrollBands+Value, Maximum); this.cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } else { absScrollBands = -scrollBands; Value = Math.Max(Value-absScrollBands, Minimum); this.cumulativeWheelData -= (int)((float)scrollBands * ((float)NativeMethods.WHEEL_DELTA / (float)wheelScrollLines)); } } if (e.Delta != Value) { OnScroll(EventArgs.Empty); OnValueChanged(EventArgs.Empty); } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.OnValueChanged"]/*' /> /// <devdoc> /// Actually fires the "valueChanged" event. /// </devdoc> /// <internalonly/> protected virtual void OnValueChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_VALUECHANGED]; if (handler != null) handler(this,e); } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.OnBackColorChanged"]/*' /> /// <devdoc> /// This method is called by the control when any property changes. Inheriting /// controls can overide this method to get property change notification on /// basic properties. Inherting controls must call base.propertyChanged. /// </devdoc> protected override void OnBackColorChanged(EventArgs e) { base.OnBackColorChanged(e); RedrawControl(); } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.OnSystemColorsChanged"]/*' /> protected override void OnSystemColorsChanged (EventArgs e) { base.OnSystemColorsChanged (e); RedrawControl(); } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.SetBoundsCore"]/*' /> /// <devdoc> /// Overrides Control.setBoundsCore to enforce autoSize. /// </devdoc> protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { //SetBoundsCore .. sets the height for a control in designer .. we should obey the requested //height is Autosize is false.. //if (IsHandleCreated) { requestedDim = (orientation == Orientation.Horizontal) ? height : width; if (autoSize) { if (orientation == Orientation.Horizontal) { if ((specified & BoundsSpecified.Height) != BoundsSpecified.None) height = PreferredDimension; } else { if ((specified & BoundsSpecified.Width) != BoundsSpecified.None) width = PreferredDimension; } } //} base.SetBoundsCore(x, y, width, height, specified); } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.SetRange"]/*' /> /// <devdoc> /// Lets you set the the entire range for the TrackBar control at once. /// The values passed are both the lower and upper limits to the range /// with which the control will work. /// </devdoc> public void SetRange(int minValue, int maxValue) { if (minimum != minValue || maximum != maxValue) { // The Minimum and Maximum properties contain the logic for // ensuring that minValue <= maxValue. It is possible, however, // that this function will be called somewhere other than from // these two properties, so we'll check that here anyway. // if (minValue > maxValue) { // We'll just adjust maxValue to match minValue maxValue = minValue; } minimum = minValue; maximum = maxValue; if (IsHandleCreated) { SendMessage(NativeMethods.TBM_SETRANGEMIN, 0, minimum); // We must repaint the trackbar after changing // the range. The '1' in the call to // SendMessage below indicates that the trackbar // should be redrawn (see TBM_SETRANGEMAX in MSDN) SendMessage(NativeMethods.TBM_SETRANGEMAX, 1, maximum); Invalidate(); } // When we change the range, the comctl32 trackbar's internal position can change // (because of the reflection that occurs with vertical trackbars) // so we make sure to explicitly set the trackbar position. // if (value < minimum) { value = minimum; } if (value > maximum) { value = maximum; } SetTrackBarPosition(); } } private void SetTrackBarPosition() { if (IsHandleCreated) { // There are two situations where we want to reflect the track bar position: // // 1. For a vertical trackbar, it seems to make more sense for the trackbar to increase in value // as the slider moves up the trackbar (this is opposite what the underlying winctl control does) // // 2. For a RightToLeft horizontal trackbar, we want to reflect the position. // int reflectedValue = value; // 1. Reflect for a vertical trackbar // if (orientation == Orientation.Vertical) { reflectedValue = Minimum + Maximum - value; } // 2. Reflect for a RightToLeft horizontal trackbar // if (orientation == Orientation.Horizontal && RightToLeft == RightToLeft.Yes && !IsMirrored) { reflectedValue = Minimum + Maximum - value; } SendMessage(NativeMethods.TBM_SETPOS, 1, reflectedValue); } } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.ToString"]/*' /> /// <devdoc> /// Returns a string representation for this control. /// </devdoc> /// <internalonly/> public override string ToString() { string s = base.ToString(); return s + ", Minimum: " + Minimum.ToString(CultureInfo.CurrentCulture) + ", Maximum: " + Maximum.ToString(CultureInfo.CurrentCulture) + ", Value: " + Value.ToString(CultureInfo.CurrentCulture); } /// <include file='doc\TrackBar.uex' path='docs/doc[@for="TrackBar.WndProc"]/*' /> /// <devdoc> /// The button's window procedure. Inheriting classes can override this /// to add extra functionality, but should not forget to call /// base.wndProc(m); to ensure the button continues to function properly. /// </devdoc> /// <internalonly/> [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { switch (m.Msg) { case NativeMethods.WM_REFLECT+NativeMethods.WM_HSCROLL: case NativeMethods.WM_REFLECT+NativeMethods.WM_VSCROLL: switch (NativeMethods.Util.LOWORD(m.WParam)) { case NativeMethods.TB_LINEUP: case NativeMethods.TB_LINEDOWN: case NativeMethods.TB_PAGEUP: case NativeMethods.TB_PAGEDOWN: //case NativeMethods.TB_THUMBPOSITION: case NativeMethods.TB_THUMBTRACK: case NativeMethods.TB_TOP: case NativeMethods.TB_BOTTOM: case NativeMethods.TB_ENDTRACK: if (value != Value) { OnScroll(EventArgs.Empty); OnValueChanged(EventArgs.Empty); } break; } break; default: base.WndProc(ref m); break; } } } }
// 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.IO.Tests { public class DirectoryInfo_CreateSubDirectory : FileSystemTest { #region UniversalTests [Fact] public void NullAsPath_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(null)); } [Fact] public void EmptyAsPath_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(string.Empty)); } [Fact] public void PathAlreadyExistsAsFile() { string path = GetTestFileName(); File.Create(Path.Combine(TestDirectory, path)).Dispose(); Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path)); Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.AddTrailingSlashIfNeeded(path))); Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.RemoveTrailingSlash(path))); } [Theory] [InlineData(FileAttributes.Hidden)] [InlineData(FileAttributes.ReadOnly)] [InlineData(FileAttributes.Normal)] public void PathAlreadyExistsAsDirectory(FileAttributes attributes) { string path = GetTestFileName(); DirectoryInfo testDir = Directory.CreateDirectory(Path.Combine(TestDirectory, path)); FileAttributes original = testDir.Attributes; try { testDir.Attributes = attributes; Assert.Equal(testDir.FullName, new DirectoryInfo(TestDirectory).CreateSubdirectory(path).FullName); } finally { testDir.Attributes = original; } } [Fact] public void DotIsCurrentDirectory() { string path = GetTestFileName(); DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".")); Assert.Equal(IOServices.RemoveTrailingSlash(Path.Combine(TestDirectory, path)), result.FullName); result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(Path.Combine(TestDirectory, path)), result.FullName); } [Fact] public void Conflicting_Parent_Directory() { string path = Path.Combine(TestDirectory, GetTestFileName(), "c"); Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path)); } [Fact] public void DotDotIsParentDirectory() { DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..")); Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName); result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName); } [Fact] public void SubDirectoryIsParentDirectory_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(TestDirectory, ".."))); Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory + "/path").CreateSubdirectory("../../path2")); } [Fact] public void ValidPathWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = IOServices.AddTrailingSlashIfNeeded(component); DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path); Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void ValidPathWithoutTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = component; DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path); Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void ValidPathWithMultipleSubdirectories() { string dirName = Path.Combine(GetTestFileName(), "Test", "Test", "Test"); DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName); Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName)); } [Fact] public void AllowedSymbols() { string dirName = Path.GetRandomFileName() + "!@#$%^&"; DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName); Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName)); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Control whitespace in path throws ArgumentException public void WindowsControlWhiteSpace() { // CreateSubdirectory will throw when passed a path with control whitespace e.g. "\t" var components = IOInputs.GetControlWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(GetTestFileName()); Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component)); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Simple whitespace is trimmed in path public void WindowsSimpleWhiteSpace() { // CreateSubdirectory trims all simple whitespace, returning us the parent directory // that called CreateSubdirectory var components = IOInputs.GetSimpleWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(GetTestFileName()); DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(component); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(TestDirectory, IOServices.RemoveTrailingSlash(result.FullName)); }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace as path allowed public void UnixWhiteSpaceAsPath_Allowed() { var paths = IOInputs.GetWhiteSpace(); Assert.All(paths, (path) => { new DirectoryInfo(TestDirectory).CreateSubdirectory(path); Assert.True(Directory.Exists(Path.Combine(TestDirectory, path))); }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Trailing whitespace in path treated as significant public void UnixNonSignificantTrailingWhiteSpace() { // Unix treats trailing/prename whitespace as significant and a part of the name. DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(testDir.Name) + component; DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path); Assert.True(Directory.Exists(result.FullName)); Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); }); } [ConditionalFact(nameof(UsingNewNormalization))] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)] [PlatformSpecific(TestPlatforms.Windows)] // Extended windows path public void ExtendedPathSubdirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); Assert.True(testDir.Exists); DirectoryInfo subDir = testDir.CreateSubdirectory("Foo"); Assert.True(subDir.Exists); Assert.StartsWith(IOInputs.ExtendedPrefix, subDir.FullName); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // UNC shares public void UNCPathWithOnlySlashes() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<ArgumentException>(() => testDir.CreateSubdirectory("//")); } #endregion } }
/* Copyright (c) 2019 Denis Zykov, GameDevWare.com This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. This source code is distributed via Unity Asset Store, to use it in your project you should accept Terms of Service and EULA https://unity3d.com/ru/legal/as_terms */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; // ReSharper disable once CheckNamespace namespace GameDevWare.Serialization.MessagePack { public class MsgPackReader : IJsonReader { public const int DEFAULT_BUFFER_SIZE = 1024 * 8; private static readonly object TrueObject = true; private static readonly object FalseObject = false; internal class MsgPackValueInfo : IValueInfo { private readonly MsgPackReader reader; private object value; internal MsgPackValueInfo(MsgPackReader reader) { if (reader == null) throw new ArgumentNullException("reader"); this.reader = reader; } public JsonToken Token { get; private set; } public bool HasValue { get; private set; } public object Raw { get { return this.value; } set { this.value = value; this.HasValue = true; } } public Type Type { get { if (this.HasValue && this.value != null) return this.value.GetType(); else { switch (this.Token) { case JsonToken.BeginArray: return typeof(List<object>); case JsonToken.Number: return typeof(double); case JsonToken.Member: case JsonToken.StringLiteral: return typeof(string); case JsonToken.DateTime: return typeof(DateTime); case JsonToken.Boolean: return typeof(bool); } return typeof(object); } } } public int LineNumber { get { return 0; } } public int ColumnNumber { get; private set; } public bool AsBoolean { get { return Convert.ToBoolean(this.Raw, this.reader.Context.Format); } } public byte AsByte { get { return Convert.ToByte(this.Raw, this.reader.Context.Format); } } public short AsInt16 { get { return Convert.ToInt16(this.Raw, this.reader.Context.Format); } } public int AsInt32 { get { return Convert.ToInt32(this.Raw, this.reader.Context.Format); } } public long AsInt64 { get { return Convert.ToInt64(this.Raw, this.reader.Context.Format); } } public sbyte AsSByte { get { return Convert.ToSByte(this.Raw, this.reader.Context.Format); } } public ushort AsUInt16 { get { return Convert.ToUInt16(this.Raw, this.reader.Context.Format); } } public uint AsUInt32 { get { return Convert.ToUInt32(this.Raw, this.reader.Context.Format); } } public ulong AsUInt64 { get { return Convert.ToUInt64(this.Raw, this.reader.Context.Format); } } public float AsSingle { get { return Convert.ToSingle(this.Raw, this.reader.Context.Format); } } public double AsDouble { get { return Convert.ToDouble(this.Raw, this.reader.Context.Format); } } public decimal AsDecimal { get { return Convert.ToDecimal(this.Raw, this.reader.Context.Format); } } public DateTime AsDateTime { get { if (this.Raw is DateTime) return (DateTime)this.Raw; else return DateTime.ParseExact(this.AsString, this.reader.Context.DateTimeFormats, this.reader.Context.Format, DateTimeStyles.AssumeUniversal); } } public string AsString { get { var raw = this.Raw; if (raw is string) return (string)raw; else if (raw is byte[]) return Convert.ToBase64String((byte[])raw); else return Convert.ToString(raw, this.reader.Context.Format); } } public void Reset() { this.value = null; this.HasValue = false; this.Token = JsonToken.None; this.ColumnNumber = 0; } public void SetValue(object rawValue, JsonToken token, int position) { this.HasValue = token == JsonToken.Boolean || token == JsonToken.DateTime || token == JsonToken.Member || token == JsonToken.Null || token == JsonToken.Number || token == JsonToken.StringLiteral; this.value = rawValue; this.Token = token; this.ColumnNumber = position; } public override string ToString() { if (this.HasValue) return Convert.ToString(this.value); else return "<no value>"; } } internal struct ClosingToken { public JsonToken Token; public long Counter; } private readonly Stream inputStream; private readonly byte[] buffer; private readonly EndianBitConverter bitConverter; private readonly Stack<ClosingToken> closingTokens; private int bufferOffset; private int bufferRead; private int bufferAvailable; private bool isEndOfStream; private int totalBytesRead; public SerializationContext Context { get; private set; } JsonToken IJsonReader.Token { get { if (this.Value.Token == JsonToken.None) this.NextToken(); if (this.isEndOfStream) return JsonToken.EndOfStream; return this.Value.Token; } } object IJsonReader.RawValue { get { if (this.Value.Token == JsonToken.None) this.NextToken(); return this.Value.Raw; } } IValueInfo IJsonReader.Value { get { if (this.Value.Token == JsonToken.None) this.NextToken(); return this.Value; } } internal MsgPackValueInfo Value { get; private set; } public MsgPackReader(Stream stream, SerializationContext context, Endianness endianness = Endianness.BigEndian, byte[] buffer = null) { if (stream == null) throw new ArgumentNullException("stream"); if (context == null) throw new ArgumentNullException("context"); if (!stream.CanRead) throw JsonSerializationException.StreamIsNotReadable(); if (buffer != null && buffer.Length < 1024) throw new ArgumentOutOfRangeException("buffer", "Buffer should be at least 1024 bytes long."); this.Context = context; this.inputStream = stream; this.buffer = buffer ?? new byte[DEFAULT_BUFFER_SIZE]; this.bufferOffset = 0; this.bufferRead = 0; this.bufferAvailable = 0; this.bitConverter = endianness == Endianness.BigEndian ? EndianBitConverter.Big : (EndianBitConverter)EndianBitConverter.Little; this.closingTokens = new Stack<ClosingToken>(); this.Value = new MsgPackValueInfo(this); } public bool NextToken() { this.Value.Reset(); if (this.closingTokens.Count > 0 && this.closingTokens.Peek().Counter == 0) { var closingToken = this.closingTokens.Pop(); this.Value.SetValue(null, closingToken.Token, this.totalBytesRead); this.DecrementClosingTokenCounter(); return true; } if (!this.ReadToBuffer(1, throwOnEos: false)) { this.isEndOfStream = true; this.Value.SetValue(null, JsonToken.EndOfStream, this.totalBytesRead); return false; } var pos = this.totalBytesRead; var formatValue = this.buffer[this.bufferOffset]; if (formatValue >= (byte)MsgPackType.FixArrayStart && formatValue <= (byte)MsgPackType.FixArrayEnd) { var arrayCount = formatValue - (byte)MsgPackType.FixArrayStart; this.closingTokens.Push(new ClosingToken { Token = JsonToken.EndOfArray, Counter = arrayCount + 1 }); this.Value.SetValue(null, JsonToken.BeginArray, pos); } else if (formatValue >= (byte)MsgPackType.FixStrStart && formatValue <= (byte)MsgPackType.FixStrEnd) { var strCount = formatValue - (byte)MsgPackType.FixStrStart; var strBytes = this.ReadBytes(strCount); var strValue = this.Context.Encoding.GetString(strBytes.Array, strBytes.Offset, strBytes.Count); var strTokenType = JsonToken.StringLiteral; if (this.closingTokens.Count > 0) { var closingToken = this.closingTokens.Peek(); if (closingToken.Token == JsonToken.EndOfObject && closingToken.Counter > 0 && closingToken.Counter % 2 == 0) strTokenType = JsonToken.Member; } this.Value.SetValue(strValue, strTokenType, pos); } else if (formatValue >= (byte)MsgPackType.FixMapStart && formatValue <= (byte)MsgPackType.FixMapEnd) { var mapCount = formatValue - (byte)MsgPackType.FixMapStart; this.closingTokens.Push(new ClosingToken { Token = JsonToken.EndOfObject, Counter = mapCount * 2 + 1 }); this.Value.SetValue(null, JsonToken.BeginObject, pos); } else if (formatValue >= (byte)MsgPackType.NegativeFixIntStart) { var value = unchecked((sbyte)formatValue); this.Value.SetValue(value, JsonToken.Number, pos); } else if (formatValue <= (byte)MsgPackType.PositiveFixIntEnd) { var value = unchecked((byte)formatValue); this.Value.SetValue(value, JsonToken.Number, pos); } else { switch ((MsgPackType)formatValue) { case MsgPackType.Nil: this.Value.SetValue(null, JsonToken.Null, pos); break; case MsgPackType.Array16: case MsgPackType.Array32: var arrayCount = 0L; if (formatValue == (int)MsgPackType.Array16) { this.ReadToBuffer(2, throwOnEos: true); arrayCount = this.bitConverter.ToUInt16(this.buffer, this.bufferOffset); } else if (formatValue == (int)MsgPackType.Array32) { this.ReadToBuffer(4, throwOnEos: true); arrayCount = this.bitConverter.ToUInt32(this.buffer, this.bufferOffset); } this.closingTokens.Push(new ClosingToken { Token = JsonToken.EndOfArray, Counter = arrayCount + 1 }); this.Value.SetValue(null, JsonToken.BeginArray, pos); break; case MsgPackType.Map16: case MsgPackType.Map32: var mapCount = 0L; if (formatValue == (int)MsgPackType.Map16) { this.ReadToBuffer(2, throwOnEos: true); mapCount = this.bitConverter.ToUInt16(this.buffer, this.bufferOffset); } else if (formatValue == (int)MsgPackType.Map32) { this.ReadToBuffer(4, throwOnEos: true); mapCount = this.bitConverter.ToUInt32(this.buffer, this.bufferOffset); } this.closingTokens.Push(new ClosingToken { Token = JsonToken.EndOfObject, Counter = mapCount * 2 + 1 }); this.Value.SetValue(null, JsonToken.BeginObject, pos); break; case MsgPackType.Str16: case MsgPackType.Str32: case MsgPackType.Str8: var strBytesCount = 0L; if (formatValue == (int)MsgPackType.Str8) { this.ReadToBuffer(1, throwOnEos: true); strBytesCount = this.buffer[this.bufferOffset]; } else if (formatValue == (int)MsgPackType.Str16) { this.ReadToBuffer(2, throwOnEos: true); strBytesCount = this.bitConverter.ToUInt16(this.buffer, this.bufferOffset); } else if (formatValue == (int)MsgPackType.Str32) { this.ReadToBuffer(4, throwOnEos: true); strBytesCount = this.bitConverter.ToUInt32(this.buffer, this.bufferOffset); } var strTokenType = JsonToken.StringLiteral; if (this.closingTokens.Count > 0) { var closingToken = this.closingTokens.Peek(); if (closingToken.Token == JsonToken.EndOfObject && closingToken.Counter > 0 && closingToken.Counter % 2 == 0) strTokenType = JsonToken.Member; } var strBytes = this.ReadBytes(strBytesCount); var strValue = this.Context.Encoding.GetString(strBytes.Array, strBytes.Offset, strBytes.Count); this.Value.SetValue(strValue, strTokenType, pos); break; case MsgPackType.Bin32: case MsgPackType.Bin16: case MsgPackType.Bin8: var bytesCount = 0L; if (formatValue == (int)MsgPackType.Bin8) { this.ReadToBuffer(1, throwOnEos: true); bytesCount = this.buffer[this.bufferOffset]; } else if (formatValue == (int)MsgPackType.Bin16) { this.ReadToBuffer(2, throwOnEos: true); bytesCount = this.bitConverter.ToUInt16(this.buffer, this.bufferOffset); } else if (formatValue == (int)MsgPackType.Bin32) { this.ReadToBuffer(4, throwOnEos: true); bytesCount = this.bitConverter.ToUInt32(this.buffer, this.bufferOffset); } var bytes = this.ReadBytes(bytesCount, forceNewBuffer: true); this.Value.SetValue(bytes.Array, JsonToken.StringLiteral, pos); break; case MsgPackType.FixExt1: case MsgPackType.FixExt16: case MsgPackType.FixExt2: case MsgPackType.FixExt4: case MsgPackType.FixExt8: case MsgPackType.Ext32: case MsgPackType.Ext16: case MsgPackType.Ext8: var dataCount = 0L; if (formatValue == (int)MsgPackType.FixExt1) dataCount = 1; else if (formatValue == (int)MsgPackType.FixExt2) dataCount = 2; else if (formatValue == (int)MsgPackType.FixExt4) dataCount = 4; else if (formatValue == (int)MsgPackType.FixExt8) dataCount = 8; else if (formatValue == (int)MsgPackType.FixExt16) dataCount = 16; if (formatValue == (int)MsgPackType.Ext8) { this.ReadToBuffer(1, throwOnEos: true); dataCount = this.buffer[this.bufferOffset]; } else if (formatValue == (int)MsgPackType.Ext16) { this.ReadToBuffer(2, throwOnEos: true); dataCount = this.bitConverter.ToUInt16(this.buffer, this.bufferOffset); } else if (formatValue == (int)MsgPackType.Ext32) { this.ReadToBuffer(4, throwOnEos: true); dataCount = this.bitConverter.ToUInt32(this.buffer, this.bufferOffset); } this.ReadToBuffer(1, true); var extensionType = unchecked((sbyte)this.buffer[this.bufferOffset]); var data = this.ReadBytes(dataCount); this.Value.SetValue(this.ReadExtensionType(extensionType, data), JsonToken.StringLiteral, pos); break; case MsgPackType.False: this.Value.SetValue(FalseObject, JsonToken.Boolean, pos); break; case MsgPackType.True: this.Value.SetValue(TrueObject, JsonToken.Boolean, pos); break; case MsgPackType.Float32: this.ReadToBuffer(4, throwOnEos: true); this.Value.SetValue(this.bitConverter.ToSingle(this.buffer, this.bufferOffset), JsonToken.Number, pos); break; case MsgPackType.Float64: this.ReadToBuffer(8, throwOnEos: true); this.Value.SetValue(this.bitConverter.ToDouble(this.buffer, this.bufferOffset), JsonToken.Number, pos); break; case MsgPackType.Int8: this.ReadToBuffer(1, throwOnEos: true); this.Value.SetValue(unchecked((sbyte)this.buffer[this.bufferOffset]), JsonToken.Number, pos); break; case MsgPackType.Int16: this.ReadToBuffer(2, throwOnEos: true); this.Value.SetValue(this.bitConverter.ToInt16(this.buffer, this.bufferOffset), JsonToken.Number, pos); break; case MsgPackType.Int32: this.ReadToBuffer(4, throwOnEos: true); this.Value.SetValue(this.bitConverter.ToInt32(this.buffer, this.bufferOffset), JsonToken.Number, pos); break; case MsgPackType.Int64: this.ReadToBuffer(8, throwOnEos: true); this.Value.SetValue(this.bitConverter.ToInt64(this.buffer, this.bufferOffset), JsonToken.Number, pos); break; case MsgPackType.UInt8: this.ReadToBuffer(1, throwOnEos: true); this.Value.SetValue(this.buffer[this.bufferOffset], JsonToken.Number, pos); break; case MsgPackType.UInt16: this.ReadToBuffer(2, throwOnEos: true); this.Value.SetValue(this.bitConverter.ToUInt16(this.buffer, this.bufferOffset), JsonToken.Number, pos); break; case MsgPackType.UInt32: this.ReadToBuffer(4, throwOnEos: true); this.Value.SetValue(this.bitConverter.ToUInt32(this.buffer, this.bufferOffset), JsonToken.Number, pos); break; case MsgPackType.UInt64: this.ReadToBuffer(8, throwOnEos: true); this.Value.SetValue(this.bitConverter.ToUInt64(this.buffer, this.bufferOffset), JsonToken.Number, pos); break; case MsgPackType.PositiveFixIntStart: case MsgPackType.PositiveFixIntEnd: case MsgPackType.FixMapStart: case MsgPackType.FixMapEnd: case MsgPackType.FixArrayStart: case MsgPackType.FixArrayEnd: case MsgPackType.FixStrStart: case MsgPackType.FixStrEnd: case MsgPackType.Unused: case MsgPackType.NegativeFixIntStart: case MsgPackType.NegativeFixIntEnd: default: throw new UnknownMsgPackFormatException(formatValue); } } this.DecrementClosingTokenCounter(); return true; } public void Reset() { Array.Clear(this.buffer, 0, this.buffer.Length); this.bufferOffset = 0; this.bufferAvailable = 0; this.bufferRead = 0; this.totalBytesRead = 0; this.Value.Reset(); } public bool IsEndOfStream() { return this.isEndOfStream; } private bool ReadToBuffer(int bytesRequired, bool throwOnEos) { this.bufferAvailable -= this.bufferRead; this.bufferOffset += this.bufferRead; this.bufferRead = 0; if (this.bufferAvailable < bytesRequired) { if (this.bufferAvailable > 0) Buffer.BlockCopy(this.buffer, this.bufferOffset, this.buffer, 0, this.bufferAvailable); this.bufferOffset = 0; while (this.bufferAvailable < bytesRequired) { var read = this.inputStream.Read(this.buffer, this.bufferAvailable, this.buffer.Length - this.bufferAvailable); this.bufferAvailable += read; if (read != 0 || this.bufferAvailable >= bytesRequired) continue; if (throwOnEos) throw JsonSerializationException.UnexpectedEndOfStream(this); else return false; } } this.bufferRead = bytesRequired; this.totalBytesRead += bytesRequired; return true; } private ArraySegment<byte> ReadBytes(long bytesRequired, bool forceNewBuffer = false) { if (bytesRequired > int.MaxValue) throw new ArgumentOutOfRangeException("bytesRequired"); this.bufferAvailable -= this.bufferRead; this.bufferOffset += this.bufferRead; this.bufferRead = 0; if (this.bufferAvailable >= bytesRequired && !forceNewBuffer) { var bytes = new ArraySegment<byte>(this.buffer, this.bufferOffset, (int)bytesRequired); this.bufferAvailable -= (int)bytesRequired; this.bufferOffset += (int)bytesRequired; this.totalBytesRead += (int)bytesRequired; return bytes; } else { var bytes = new byte[bytesRequired]; var bytesOffset = 0; if (this.bufferAvailable > 0 && bytesOffset < bytes.Length) { var bytesToCopy = Math.Min(bytes.Length - bytesOffset, this.bufferAvailable); Buffer.BlockCopy(this.buffer, this.bufferOffset, bytes, bytesOffset, bytesToCopy); bytesOffset += bytesToCopy; this.bufferOffset += bytesToCopy; this.bufferAvailable -= bytesToCopy; this.totalBytesRead += bytesToCopy; } if (this.bufferAvailable == 0) this.bufferOffset = 0; while (bytesOffset < bytes.Length) { var read = this.inputStream.Read(bytes, bytesOffset, bytes.Length - bytesOffset); bytesOffset += read; this.totalBytesRead += read; if (read == 0 && bytesOffset < bytes.Length) throw JsonSerializationException.UnexpectedEndOfStream(this); } return new ArraySegment<byte>(bytes, 0, bytes.Length); } } private object ReadExtensionType(sbyte type, ArraySegment<byte> data) { var value = default(object); if (this.Context.ExtensionTypeHandler.TryRead(type, data, out value)) { return value; } else { if (ReferenceEquals(data.Array, this.buffer)) data = new ArraySegment<byte>((byte[])data.Array.Clone(), data.Offset, data.Count); return new MessagePackExtensionType(type, data); } } private void DecrementClosingTokenCounter() { if (this.closingTokens.Count > 0) { var closingToken = this.closingTokens.Pop(); closingToken.Counter--; this.closingTokens.Push(closingToken); } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is DotSpatial // // The Initial Developer of this Original Code is Ted Dunsford. Created in February, 2008. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.IO; using DotSpatial.NTSExtension; using GeoAPI.Geometries; namespace DotSpatial.Data { /// <summary> /// The header for the .shp file and the .shx file that support shapefiles /// </summary> public class ShapefileHeader { #region Private Variables // Always 9994 if it is a shapefile private int _fileCode; // The length of the shp file in bytes private int _fileLength; private string _fileName; private double _mMax; private double _mMin; // The version, which should be 1000 // Specifies line, polygon, point etc. private ShapeType _shapeType; private int _shxLength; private int _version; // Extent Values for the entire shapefile private double _xMax; private double _xMin; private double _yMax; private double _yMin; private double _zMax; private double _zMin; #endregion #region Constructors /// <summary> /// Creates a new, blank ShapeHeader /// </summary> public ShapefileHeader() { Clear(); } /// <summary> /// Opens the specified fileName directly /// </summary> /// <param name="inFilename">The string fileName to open as a header.</param> public ShapefileHeader(string inFilename) { Open(inFilename); } #endregion #region Methods /// <summary> /// Resets all the extent values to 0 /// </summary> public void Clear() { _version = 1000; _fileCode = 9994; _xMin = 0.0; _xMax = 0.0; _yMin = 0.0; _yMax = 0.0; _zMin = 0.0; _zMax = 0.0; _mMin = 0.0; _mMax = 0.0; } /// <summary> /// Parses the first 100 bytes of a shapefile into the important values /// </summary> /// <param name="inFilename">The fileName to read</param> public void Open(string inFilename) { _fileName = inFilename; // Position Field Value Type ByteOrder // -------------------------------------------------------------- // Byte 0 File Code 9994 Integer Big // Byte 4 Unused 0 Integer Big // Byte 8 Unused 0 Integer Big // Byte 12 Unused 0 Integer Big // Byte 16 Unused 0 Integer Big // Byte 20 Unused 0 Integer Big // Byte 24 File Length File Length Integer Big // Byte 28 Version 1000 Integer Little // Byte 32 Shape Type Shape Type Integer Little // Byte 36 Bounding Box Xmin Double Little // Byte 44 Bounding Box Ymin Double Little // Byte 52 Bounding Box Xmax Double Little // Byte 60 Bounding Box Ymax Double Little // Byte 68 Bounding Box Zmin Double Little // Byte 76 Bounding Box Zmax Double Little // Byte 84 Bounding Box Mmin Double Little // Byte 92 Bounding Box Mmax Double Little // This may throw an IOException if the file is already in use. BufferedBinaryReader bbReader = new BufferedBinaryReader(inFilename); bbReader.FillBuffer(100); // we only need to read 100 bytes from the header. bbReader.Close(); // Close the internal readers connected to the file, but don't close the file itself. // Reading BigEndian simply requires us to reverse the byte order. _fileCode = bbReader.ReadInt32(false); // Skip the next 20 bytes because they are unused bbReader.Seek(20, SeekOrigin.Current); // Read the file length in reverse sequence _fileLength = bbReader.ReadInt32(false); // From this point on, all the header values are in little Endean // Read the version _version = bbReader.ReadInt32(); // Read in the shape type that should be the shape type for the whole shapefile _shapeType = (ShapeType)bbReader.ReadInt32(); // Get the extents, each of which are double values. _xMin = bbReader.ReadDouble(); _yMin = bbReader.ReadDouble(); _xMax = bbReader.ReadDouble(); _yMax = bbReader.ReadDouble(); _zMin = bbReader.ReadDouble(); _zMax = bbReader.ReadDouble(); _mMin = bbReader.ReadDouble(); _mMax = bbReader.ReadDouble(); bbReader.Dispose(); string shxFile = Path.ChangeExtension(Filename, ".shx"); FileInfo fi = new FileInfo(shxFile); if (fi.Exists) { _shxLength = Convert.ToInt32(fi.Length / 2); //length is in 16 bit words. } } /// <summary> /// Saves changes to the .shp file will also automatically update the .shx file. /// </summary> public void Save() { SaveAs(_fileName); } /// <summary> /// Saves changes to the .shp file and will also automatically create the header for the .shx file. /// This will no longer automatically delete an existing shapefile. /// </summary> /// <param name="outFilename">The string fileName to create.</param> public void SaveAs(string outFilename) { _fileName = outFilename; Write(_fileName, _fileLength); Write(ShxFilename, _shxLength); } /// <summary> /// Writes the current content to the specified file. /// </summary> /// <param name="destFilename">The string fileName to write to</param> /// <param name="destFileLength">The only difference between the shp header and the /// shx header is the file length parameter.</param> private void Write(string destFilename, int destFileLength) { string dir = Path.GetDirectoryName(Path.GetFullPath(Filename)); if (dir != null) if (!Directory.Exists(dir)) { //if (MessageBox.Show("Directory " + dir + " does not exist. Do you want to create it?", // "Create Directory?", MessageBoxButtons.YesNo) != DialogResult.OK) // return; Directory.CreateDirectory(dir); } //if (File.Exists(destFilename)) File.Delete(destFilename); FileStream fs = new FileStream(destFilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); fs.WriteBe(_fileCode); // Byte 0 File Code 9994 Integer Big byte[] bt = new byte[20]; fs.Write(bt, 0, 20); // Bytes 4 - 20 are unused fs.WriteBe(destFileLength); // Byte 24 File Length File Length Integer Big fs.WriteLe(_version); // Byte 28 Version 1000 Integer Little fs.WriteLe((int)_shapeType); // Byte 32 Shape Type Shape Type Integer Little fs.WriteLe(_xMin); // Byte 36 Bounding Box Xmin Double Little fs.WriteLe(_yMin); // Byte 44 Bounding Box Ymin Double Little fs.WriteLe(_xMax); // Byte 52 Bounding Box Xmax Double Little fs.WriteLe(_yMax); // Byte 60 Bounding Box Ymax Double Little fs.WriteLe(_zMin); // Byte 68 Bounding Box Zmin Double Little fs.WriteLe(_zMax); // Byte 76 Bounding Box Zmax Double Little fs.WriteLe(_mMin); // Byte 84 Bounding Box Mmin Double Little fs.WriteLe(_mMax); // Byte 92 Bounding Box Mmax Double Little // ------------ WRITE TO SHP FILE ------------------------- fs.Close(); } #endregion /// <summary> /// Gets or sets the integer file code that should always be 9994. /// </summary> public int FileCode { get { return _fileCode; } set { _fileCode = value; } } /// <summary> /// Gets or sets the integer file length in bytes /// </summary> public int FileLength { get { return _fileLength; } set { _fileLength = value; } } /// <summary> /// Gets or sets the string fileName to use for this header /// </summary> public string Filename { get { return _fileName; } set { _fileName = value; } } /// <summary> /// Gets or sets the DotSpatial.Data.Shapefiles.ShapeType enumeration specifying /// whether the shapes are points, lines, polygons etc. /// </summary> public ShapeType ShapeType { get { return _shapeType; } set { _shapeType = value; } } /// <summary> /// Changes the extension of the fileName to .shx instead of .shp /// </summary> public string ShxFilename { get { return Path.ChangeExtension(_fileName, ".shx"); } } /// <summary> /// Gets or sets the version, which should be 1000 /// </summary> public int Version { get { return _version; } set { _version = value; } } /// <summary> /// The minimum X coordinate for the values in the shapefile /// </summary> public double Xmin { get { return _xMin; } set { _xMin = value; } } /// <summary> /// The maximum X coordinate for the shapes in the shapefile /// </summary> public double Xmax { get { return _xMax; } set { _xMax = value; } } /// <summary> /// The minimum Y coordinate for the values in the shapefile /// </summary> public double Ymin { get { return _yMin; } set { _yMin = value; } } /// <summary> /// The maximum Y coordinate for the shapes in the shapefile /// </summary> public double Ymax { get { return _yMax; } set { _yMax = value; } } /// <summary> /// The minimum Z coordinate for the values in the shapefile /// </summary> public double Zmin { get { return _zMin; } set { _zMin = value; } } /// <summary> /// The maximum Z coordinate for the shapes in the shapefile /// </summary> public double Zmax { get { return _zMax; } set { _zMax = value; } } /// <summary> /// The minimum M coordinate for the values in the shapefile /// </summary> public double Mmin { get { return _mMin; } set { _mMin = value; } } /// <summary> /// The maximum M coordinate for the shapes in the shapefile /// </summary> public double Mmax { get { return _mMax; } set { _mMax = value; } } /// <summary> /// Gets or sets the length of the shx file in 16 bit words. /// </summary> public int ShxLength { get { return _shxLength; } set { _shxLength = value; } } /// <summary> /// Generates a new envelope based on the extents of this shapefile. /// </summary> /// <returns>An Envelope</returns> public Envelope ToEnvelope() { Envelope env = new Envelope(_xMin, _xMax, _yMin, _yMax); env.InitM(_mMin, _mMax); env.InitZ(_zMin, _zMax); return env; } /// <summary> /// Generates a new extent from the shape header. This will infer the whether the ExtentMZ, ExtentM /// or Extent class is the best implementation. Casting is required to access the higher /// values from the Extent return type. /// </summary> /// <returns>Extent, which can be Extent, ExtentM, or ExtentMZ</returns> public Extent ToExtent() { if (ShapeType == ShapeType.MultiPointZ || ShapeType == ShapeType.PointZ || ShapeType == ShapeType.PolygonZ || ShapeType == ShapeType.PolyLineZ) { return new ExtentMZ(_xMin, _yMin, _mMin, _zMin, _xMax, _yMax, _mMax, _zMax); } if (ShapeType == ShapeType.MultiPointM || ShapeType == ShapeType.PointM || ShapeType == ShapeType.PolygonM || ShapeType == ShapeType.PolyLineM) { return new ExtentM(_xMin, _yMin, _mMin, _xMax, _yMax, _mMax); } Extent ext = new Extent(_xMin, _yMin, _xMax, _yMax); return ext; } /// <summary> /// The shape type is assumed to be fixed, and will control how the input extent is treated as far /// as M and Z values, rather than updating the shape type based on the extent. /// </summary> public void SetExtent(IExtent extent) { IExtentZ zExt = extent as ExtentMZ; IExtentM mExt = extent as ExtentM; if ((ShapeType == ShapeType.MultiPointZ || ShapeType == ShapeType.PointZ || ShapeType == ShapeType.PolygonZ || ShapeType == ShapeType.PolyLineZ)) { if (zExt == null || extent.HasZ == false) { _zMin = double.MaxValue; _zMax = double.MinValue; } else { _zMin = zExt.MinZ; _zMax = zExt.MaxZ; } } if (ShapeType == ShapeType.MultiPointM || ShapeType == ShapeType.PointM || ShapeType == ShapeType.PolygonM || ShapeType == ShapeType.PolyLineM) { if (mExt == null || extent.HasM == false) { _mMin = double.MaxValue; _mMax = double.MinValue; } else { _mMin = mExt.MinM; _mMax = mExt.MaxM; } } _xMin = extent.MinX; _xMax = extent.MaxX; _yMin = extent.MinY; _yMax = extent.MaxY; } } }
////////////////////////////////////////////////////////////////////////////////////////////////// // // file: Particles_simulation.cs // // Author Sergey Solokhin (Neill3d) // // Main GPU Particles compute shader // // GitHub page - https://github.com/Neill3d/MoPlugs // Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE // /////////////////////////////////////////////////////////////////////////////////////////////////// #version 430 layout (local_size_x = 1024, local_size_y = 1) in; uniform int gNumParticles; uniform float DeltaTimeSecs; uniform float gTime; uniform mat4 gTM; // emitter transform uniform vec4 gDynamic; uniform vec4 gTurbulence; uniform vec4 gGravity; // in w - use gravity force uniform vec4 gFloor; // in x - floor friction, in y - level, in w - use floor level uniform int gNumForces; uniform int gNumCollisions; uniform int gUseSizeAttenuation; uniform int gUseColorAttenuation; uniform int gUpdatePosition; uniform int gEmitterPointCount; #define PARTICLE_TYPE_LAUNCHER 0.0f #define PARTICLE_TYPE_SHELL 1.0f #define PARTICLE_TYPE_SECONDARY_SHELL 2.0f #define USE_FLOOR gFloor.w #define FLOOR_FRICTION gFloor.y #define FLOOR_LEVEL gFloor.z #define MASS gDynamic.x #define DAMPING gDynamic.y #define CONSTRAINT_MAGN gDynamic.z #define USE_GRAVITY gGravity.w #define GRAVITY gGravity.xyz #define USE_TURBULENCE gTurbulence.w #define NOISE_FREQ gTurbulence.x #define NOISE_SPEED gTurbulence.y #define NOISE_AMP gTurbulence.z #define USE_FORCES gNumForces > 0 #define USE_COLLISIONS gNumCollisions > 0 #define EMITTER_TYPE gFlags.z #define EMITTER_TYPE_VERTICES 0.0 #define EMITTER_TYPE_VOLUME 1.0 #define FORCE_WIND 1.0 #define FORCE_GRAVITY 2.0 #define FORCE_MOTOR 3.0 #define FORCE_VORTEX 4.0 #define COLLISION_SPHERE 1.0 #define COLLISION_TERRIAN 4.0 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TYPES AND DATA BUFFERS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct TParticle { vec4 Pos; // in w hold lifetime from 0.0 to 1.0 (normalized) vec4 Vel; // in w - individual birth randomF // color packed in x. inherit color from the emitter surface, custom color simulation vec4 Color; // in y - total lifetime, z - AgeMillis, w - Index vec4 Rot; // vec4 RotVel; // }; struct TCollision { vec4 position; // use w as collision type vec4 velocity; // .w - maxscale dimention vec4 terrainScale; // .w - softness vec4 terrainSize; // texture dimentions float radius; float friction; uvec2 terrainAddress; mat4 tm; mat4 invtm; }; struct TForce { vec4 position; vec4 direction; // use w as a force type float magnitude; float radius; float noiseFreq; float noiseSpeed; vec4 turbulence; // w - use turbulence or not, x-amplitude, y-frequency vec4 wind1; // special wind pre-calculated force vec4 wind2; }; // emitter surface struct TTriangle { vec4 p[3]; vec4 n; vec2 uv[3]; vec2 temp; // to align type }; layout (std430, binding = 0) buffer ParticleBuffer { TParticle particles[]; } particleBuffer; layout (std430, binding = 1) readonly buffer ForcesBuffer { TForce forces[]; } forceBuffer; layout (std430, binding = 2) readonly buffer CollisionBuffer { TCollision collisions[]; } collisionBuffer; layout (std430, binding = 3) readonly buffer MeshBuffer { TTriangle mesh[]; } meshBuffer; // terrain depth layout(binding=0) uniform sampler2D TerrainSampler; // particle size attenuation layout(binding=5) uniform sampler1D SizeSampler; const vec2 randN1 = vec2(0.14, -0.07); const vec2 randN2 = vec2(0.77, 1.01); const vec2 randN3 = vec2(-0.38, 0.15); const float PiPi = 6.2831853; const float PI = 3.14159265; const float PI_2 = 1.57079632; const float PI_4 = 0.785398163; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // HELPER FUNCTIONS /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// highp float rand(vec2 co) { highp float a = 12.9898; highp float b = 78.233; highp float c = 43758.5453; highp float dt= dot(co.xy ,vec2(a,b)); highp float sn= mod(dt,3.14); return fract(sin(sn) * c); } mat3 rotationMatrix(vec3 axisIn, float angle) { vec3 axis = normalize(axisIn); float s = sin(angle); float c = cos(angle); float oc = 1.0 - c; return mat3(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c); } vec4 quat_mul(vec4 q0, vec4 q1) { vec4 d; d.x = q0.w * q1.x + q0.x * q1.w + q0.y * q1.z - q0.z * q1.y; d.y = q0.w * q1.y - q0.x * q1.z + q0.y * q1.w + q0.z * q1.x; d.z = q0.w * q1.z + q0.x * q1.y - q0.y * q1.x + q0.z * q1.w; d.w = q0.w * q1.w - q0.x * q1.x - q0.y * q1.y - q0.z * q1.z; return d; } uint get_invocation() { //uint work_group = gl_WorkGroupID.x * gl_NumWorkGroups.y * gl_NumWorkGroups.z + gl_WorkGroupID.y * gl_NumWorkGroups.z + gl_WorkGroupID.z; //return work_group * gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z + gl_LocalInvocationIndex; // uint work_group = gl_WorkGroupID.y * gl_NumWorkGroups.x * gl_WorkGroupSize.x + gl_WorkGroupID.x * gl_WorkGroupSize.x + gl_LocalInvocationIndex; uint work_group = gl_GlobalInvocationID.y * (gl_NumWorkGroups.x * gl_WorkGroupSize.x) + gl_GlobalInvocationID.x; return work_group; } // // Description : Array and textureless GLSL 2D/3D/4D simplex // noise functions. // Author : Ian McEwan, Ashima Arts. // Maintainer : ijm // Lastmod : 20110822 (ijm) // License : Copyright (C) 2011 Ashima Arts. All rights reserved. // Distributed under the MIT License. See LICENSE file. // https://github.com/ashima/webgl-noise // vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } vec4 permute(vec4 x) { return mod289(((x*34.0)+1.0)*x); } vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; } float snoise(vec3 v) { const vec2 C = vec2(1.0/6.0, 1.0/3.0) ; const vec4 D = vec4(0.0, 0.5, 1.0, 2.0); // First corner vec3 i = floor(v + dot(v, C.yyy) ); vec3 x0 = v - i + dot(i, C.xxx) ; // Other corners vec3 g = step(x0.yzx, x0.xyz); vec3 l = 1.0 - g; vec3 i1 = min( g.xyz, l.zxy ); vec3 i2 = max( g.xyz, l.zxy ); // x0 = x0 - 0.0 + 0.0 * C.xxx; // x1 = x0 - i1 + 1.0 * C.xxx; // x2 = x0 - i2 + 2.0 * C.xxx; // x3 = x0 - 1.0 + 3.0 * C.xxx; vec3 x1 = x0 - i1 + C.xxx; vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y // Permutations i = mod289(i); vec4 p = permute( permute( permute( i.z + vec4(0.0, i1.z, i2.z, 1.0 )) + i.y + vec4(0.0, i1.y, i2.y, 1.0 )) + i.x + vec4(0.0, i1.x, i2.x, 1.0 )); // Gradients: 7x7 points over a square, mapped onto an octahedron. // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) float n_ = 0.142857142857; // 1.0/7.0 vec3 ns = n_ * D.wyz - D.xzx; vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7) vec4 x_ = floor(j * ns.z); vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N) vec4 x = x_ *ns.x + ns.yyyy; vec4 y = y_ *ns.x + ns.yyyy; vec4 h = 1.0 - abs(x) - abs(y); vec4 b0 = vec4( x.xy, y.xy ); vec4 b1 = vec4( x.zw, y.zw ); //vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0; //vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0; vec4 s0 = floor(b0)*2.0 + 1.0; vec4 s1 = floor(b1)*2.0 + 1.0; vec4 sh = -step(h, vec4(0.0)); vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ; vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ; vec3 p0 = vec3(a0.xy,h.x); vec3 p1 = vec3(a0.zw,h.y); vec3 p2 = vec3(a1.xy,h.z); vec3 p3 = vec3(a1.zw,h.w); //Normalise gradients vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3))); p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w; // Mix final noise value vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0); m = m * m; return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3) ) ); } ////////////////////////////////////////////////////////////////////// // // out float r, out float theta, out float phi void ConvertUnitVectorToSpherical(const vec4 v, out vec3 sv) { sv.x = sqrt(v.x*v.x + v.y*v.y + v.z*v.z); // r sv.y = atan( v.y, v.x ); // theta sv.z = atan( sqrt(v.x*v.x+v.y*v.y), v.z ); // phi } // const float r, const float theta, const float phi void ConvertSphericalToUnitVector(vec3 sv, out vec4 v) { v.x = sv.x * cos(sv.y) * sin(sv.z); v.y = sv.x * sin(sv.y) * sin(sv.z); v.z = sv.x * cos(sv.z); v.w = 1.0; } void GetRandomDir(in vec4 inDir, in vec2 dirRnd, out vec4 dir) { //float r, theta, phi; vec3 sv; ConvertUnitVectorToSpherical(inDir, sv); sv.y += dirRnd.x * PI; sv.z += dirRnd.y * PiPi; ConvertSphericalToUnitVector(sv, dir); } void GetRandomDir(in vec3 inDir, in vec2 dirRnd, out vec3 dir) { //float r, theta, phi; vec3 sv; ConvertUnitVectorToSpherical(vec4(inDir, 1.0), sv); sv.y += dirRnd.x * PI; sv.z += dirRnd.y * PiPi; vec4 result; ConvertSphericalToUnitVector(sv, result); dir = result.xyz; } vec4 Color_UnPack (float x) { float a,b,c,d; a = floor(x*255.0/64.0)*64.0/255.0; x -= a; b = floor(x*255.0/16.0)*16.0/255.0; x -= b; b *= 4.0; c = floor(x*255.0/4.0)*4.0/255.0; x -= c; c *= 16.0; d = x*255.0 * 64.0 / 255.0; // scan be simplified to just x*64.0 return vec4(a,b,c,d); } float Color_Pack (vec4 colour) { float x = 1.0/255.0 * (floor(colour.x*255.0/64.0)*64.0 + floor(colour.y*255.0/64.0)*16.0 + floor(colour.z*255.0/64.0)*4.0 + floor(colour.a*255.0/64.0)); return x; } void GetEmitPos(in vec2 randN, out vec4 pos, out int vertIndex, out vec3 bary) { float rnd = rand(randN) * gEmitterPointCount; int triIndex = int(rnd); // barycentric coords float rnd1 = rand(randN+randN1); float rnd2 = rand(randN+randN2); bary.x = 1.0 - sqrt(rnd1); bary.y = sqrt(rnd1) * (1.0 - rnd2); bary.z = sqrt(rnd1) * rnd2; TTriangle tri = meshBuffer.mesh[triIndex]; vec4 p0 = tri.p[0]; vec4 p1 = tri.p[1]; vec4 p2 = tri.p[2]; p0 *= bary.x; p1 *= bary.y; p2 *= bary.z; vec4 P = p0 + p1 + p2; vertIndex = triIndex * 3; pos = gTM * vec4(P.xyz, 1.0); //pos = vec4(P.xyz, 1.0); // TODO: extrusion dist is not used ! } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CONSTRAINT AND COLLIDE ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SphereCollide(TCollision data, in float size, in vec3 x, inout vec3 vel) { vec3 delta = x - data.position.xyz; float dist = length(delta); float radius = data.radius * data.velocity.w; // + size; if (dist < radius) { vec4 untransformed = data.invtm * vec4(x, 1.0); dist = length(untransformed.xyz); radius = data.radius; // + size / data.velocity.w; if (dist < radius) { vec3 newvel = vel * clamp(dist / radius, 0.0, 1.0) * data.friction; newvel = reflect(newvel, normalize(untransformed.xyz)); vel = mix(newvel, vel, data.terrainScale.w); vel += (1.0 - data.terrainScale.w) * data.velocity.xyz; } } } // constrain particle to be outside volume of a sphere void SphereConstraint(TCollision data, in float size, inout vec3 x) { vec3 delta = x - data.position.xyz; float dist = length(delta); float radius = data.radius * data.velocity.w; // + size; if (dist < radius) { vec4 untransformed = data.invtm * vec4(x, 1.0); dist = length(untransformed.xyz); radius = data.radius; // + size / data.velocity.w; if (dist < radius) { vec3 newx = radius * normalize(untransformed.xyz); untransformed = data.tm * vec4(newx, 1.0); x = mix(untransformed.xyz, x, data.terrainScale.w); } } } // constrain particle to heightfield stored in texture void TerrainConstraint(TCollision data, inout vec3 pos) { vec3 scale = data.terrainScale.xyz; vec3 offset = data.position.xyz; if (pos.x < offset.x || pos.x > offset.x+scale.x || pos.z < offset.z || pos.z > offset.z+scale.z || pos.y < offset.y || pos.y > data.terrainSize.z ) { return; } vec2 uv = (pos.xz - offset.xz) / scale.xz; float h = texture(TerrainSampler, uv).x; if (pos.y < h) { pos.y = h; } } // constrain particle to be above floor void FloorConstraint(inout vec3 x, float level) { if (x.y < level) { x.y = level; } } void FloorCollide(inout vec3 x, inout vec3 vel, const float rndF, float level, float friction, const float dt) { if (x.y < level) { // x.y = level; // force.y += -vel.y*friction; vel.xyz = friction * vel.xyz; vel.xyz = reflect( vel.xyz, vec3(0.0, 1.0, 0.0) ); //vel.y += -vel.y*friction * rand(vec2(rndF, 0.123)) * dt; //vel.x += rand(vec2(rndF, -0.123)) * friction * dt; //vel.z += rand(vec2(rndF, -0.543)) * friction * dt; } } void TerrainCollide(TCollision data, vec3 pos, const float rndF, inout vec3 vel) { vec3 offset = data.position.xyz; vec3 scale = data.terrainScale.xyz; // should be predefined in shader if (pos.x < offset.x || pos.x > offset.x+scale.x || pos.z < offset.z || pos.z > offset.z+scale.z || pos.y < offset.y || pos.y > data.terrainSize.z ) { return; } vec2 texelSize = vec2( 1.0 / data.terrainSize.x, 1.0 / data.terrainSize.y ); vec2 uv = (pos.xz - offset.xz) / scale.xz; float h0 = texture(TerrainSampler, uv).x; if (pos.y < h0) { // calculate normal (could precalc this) float h1 = texture(TerrainSampler, uv + texelSize*vec2(1.0, 0.0) ).r; float h2 = texture(TerrainSampler, uv + texelSize*vec2(0.0, 1.0) ).r; vec3 N = cross( vec3(scale.x*texelSize.x, h1-h0, 0.0), vec3(0.0, h2-h0, scale.z*texelSize.y) ); //vec3 N = cross( vec3(scale.x*texelSize.x, (h1-h0)*scale.y, 0), vec3(0, (h2-h0)*scale.y, scale.z*texelSize.y) ); N = normalize(N); //GetRandomDir(N, vec2(0.1*rand(vec2(rndF, 0.11)), 0.2*rand(vec2(rndF, -0.05))), N); vel = reflect(vel, N); vel *= data.friction; vec3 newvel = vel * data.friction; newvel = reflect(newvel, N); vel = mix(newvel, vel, data.terrainScale.w); } } //////////////////////////////////////////////////////////////////////// // FORCES //////////////////////////////////////////////////////////////////////// void ApplyWindForce2(TForce data, in float time, in vec3 pos_next, inout vec3 force, inout vec3 vel, float dt) { // combining four winds. float a = snoise( vec3(data.noiseSpeed * time) + data.noiseFreq * pos_next ); vec3 w = a*data.direction.xyz + (1.0f-a)*data.turbulence.xyz + a*data.wind1.xyz + (1.0f-a)*data.wind2.xyz; vec3 lforce = data.magnitude * normalize(w); float r = data.radius; if (r > 0.0f) { vec3 lpos = data.position.xyz; float len = length(lpos - pos_next); len = clamp(len, 0.0, r); len = 1.0f - len / r; lforce *= len; } vel += lforce*dt*dt; } void ApplyDragForce(TForce data, in float time, in vec3 pos_next, inout vec3 force, inout vec3 vel) { // here direction is a drag velocity vec3 lforce = data.magnitude * data.direction.xyz; float r = data.radius; if (r > 0.0) { vec3 lpos = data.position.xyz; float len = length(lpos - pos_next); if (len <= r) { len = 1.0 - len / (r + 0.001); force += lforce * len; //force += lforce * (1.0 / (len*len + 0.001) ); } } else { force += lforce; } } void ApplyDragForce2(TForce data, in float time, in vec3 pos_next, inout vec3 force, inout vec3 vel) { // here direction is a drag velocity vec3 lforce = data.magnitude * data.direction.xyz; lforce = data.magnitude * normalize(pos_next - data.position.xyz); lforce.x = 0.0; lforce.z = 0.0; float r = data.radius; if (r > 0.0) { vec3 lpos = data.position.xyz; float len = length(lpos - pos_next); if (len <= r) { len = 1.0 - len / (r + 0.001); force += lforce * len; //force += lforce * (1.0 / (len*len + 0.001) ); } } else { force += lforce; } } // Thanks for paper - Particle Systems Using 3D Vector Fields with OpenGL Compute Shaders. Johan Anderdahl Alice Darner void ApplyGravityForce(TForce data, in float time, in vec3 pos_next, inout vec3 force, inout vec3 vel) { vec3 center = data.position.xyz; float power = data.magnitude; vec3 dir = center - pos_next; float range = data.radius; if (range > 0.0) { float distance = length(dir); float percent = ((range-distance) / range); percent = clamp(percent, 0.0, 1.0); dir = normalize(dir); force += dir * percent * power; } else { force += dir * power; } } void ApplyMotorForce(TForce data, in float time, in vec3 pos_next, inout vec3 force, inout vec3 vel) { vec3 lpos = data.position.xyz; mat3 mat = rotationMatrix( data.direction.xyz, data.direction.w * 3.14 / 180.0 ); vec3 v = pos_next - lpos; // TODO: we can make a force to move to/from the center of motor vec3 tmpPos = pos_next - lpos; vec3 point = (dot(tmpPos, data.direction.xyz)/dot(data.direction.xyz, data.direction.xyz) * data.direction.xyz); vec3 pointVec = tmpPos - point; vec3 direction = lpos - pos_next; float distance = length(direction); direction /= distance; //vel += direction * max(0.01, (1.0 / (distance*distance))); // * data.magnitude; vec3 v2 = v * mat; //v += lpos; vec3 lforce = vec3(0.0); // 0.1 * data.magnitude * (v - pos_next); vec3 spinVec = cross(direction, pointVec); //lforce = spinVec * data.magnitude; lforce += (v2 - v + direction) * max(0.01, (1.0 / (distance*distance))) * data.magnitude * 10.0; //vec3 lforce = data.magnitude * data.direction.xyz; float r = data.radius; if (r > 0.0) { float len = length(lpos - pos_next); if (len <= r) { len = 1.0 - len / (r + 0.001); vel = lforce * len; //force += lforce * (1.0 / (len*len + 0.001) ); } } else { vel = lforce; } } void ApplyVortex(TForce data, in float time, in vec3 particlePos, inout vec3 force, inout vec3 vel) { float height = data.radius; float range = data.radius; float curve = 1.0; float downPower = 1.0; vec3 center = data.position.xyz; vec3 direction = data.direction.xyz; vec3 tmpPos = particlePos - center; vec3 point = (dot(tmpPos, data.direction.xyz)/dot(data.direction.xyz, data.direction.xyz) * data.direction.xyz); // if the particle we are testing against is above the vortex it shouldn't affect that particle bool cut = bool(clamp(dot(point, direction), 0.0, 1.0)); // TODO: we can make a force to move to/from the center of motor vec3 pointVec = tmpPos - point; vec3 pullVec = pointVec; float vort = length(point); float percentVort = ((height - vort)/height); range *= clamp(pow(percentVort, curve), 0.0, 1.0); float dist = length(pointVec); float downDist = length(point); float downPercent = ((height - downDist)/height); float rangePercent = ((range - dist)/range); rangePercent = clamp(rangePercent, 0.0, 1.0); downPercent = clamp(downPercent, 0.0, 1.0); vec3 spinVec = cross(direction, pointVec); vec3 downVec = normalize(direction); normalize(spinVec); normalize(pullVec); force += (spinVec * data.direction.w - pullVec * data.magnitude + downVec * downPower) * rangePercent * float(cut); /* float r = data.radius; if (r > 0.0) { float len = length(center - particlePos); if (len <= r) { len = 1.0 - len / (r + 0.001); force = lforce * len; //force += lforce * (1.0 / (len*len + 0.001) ); } } else { force = lforce; } */ } void ApplyConstraint(in float time, in float randomF, inout vec3 force, inout vec3 vel, inout vec3 pos) { vec4 dst; int vertIndex = 0; vec3 baryCoords; GetEmitPos(vec2(randomF, 0.487), dst, vertIndex, baryCoords); //vec4 dst = gTM * vec4(particleHold, 1.0); vec3 direction = pos - dst.xyz; float distance = length(direction); if (distance != 0.0) { pos = mix(pos, dst.xyz, clamp(CONSTRAINT_MAGN * time, 0.0, 1.0)) ; direction /= distance; vel *= 1.0 - CONSTRAINT_MAGN; // * max(1.0, (1.0 / (distance*distance))); // * data.magnitude; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MAIN ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void main() { // particle id in the array uint flattened_id = get_invocation(); // ?! skip unused part of the array if (flattened_id >= gNumParticles) return; // Read position and velocity vec4 pos = particleBuffer.particles[flattened_id].Pos; vec4 packedColor = particleBuffer.particles[flattened_id].Color; vec4 vel = particleBuffer.particles[flattened_id].Vel; vec4 rot = particleBuffer.particles[flattened_id].Rot; vec4 rotVel = particleBuffer.particles[flattened_id].RotVel; float lifetime = packedColor.y; if (lifetime == 0.0) return; float Age = packedColor.z + DeltaTimeSecs; packedColor.z = Age; // launcher has a negative size and negative lifetime value if (pos.w < 0.0 || lifetime < 0.0) // PARTICLE_TYPE_LAUNCHER { particleBuffer.particles[flattened_id].Color = packedColor; return; } else if (Age >= lifetime) { // dead particle, don't process it packedColor.y = 0.0; particleBuffer.particles[flattened_id].Color = packedColor; return; } // animate size if (gUseSizeAttenuation > 0) { float normLife = Age / lifetime; pos.w = texture( SizeSampler, normLife ).r; //pos.w = normLife * 10.0; } float randomF = gTime + float(flattened_id); // predicted position next timestep vec3 pos_next = pos.xyz + vel.xyz * DeltaTimeSecs; // accumulate rotation by angular velocity vec4 Qupdate = vec4(rotVel.xyz * 0.5 * DeltaTimeSecs, 0.0); rot += quat_mul(Qupdate, rot); // update velocity - gravity force vec3 force = GRAVITY * USE_GRAVITY; // in w - use gravity flag if (USE_FORCES) { for (int i=0; i<gNumForces; ++i) { float type = forceBuffer.forces[i].position.w; if (type == FORCE_WIND) ApplyWindForce2(forceBuffer.forces[i], gTime * 0.01, pos_next, force, vel.xyz, DeltaTimeSecs); else if (type == FORCE_GRAVITY) ApplyGravityForce(forceBuffer.forces[i], gTime * 0.01, pos_next, force, vel.xyz); else if (type == FORCE_MOTOR) ApplyMotorForce(forceBuffer.forces[i], gTime * 0.01, pos_next, force, vel.xyz); else if (type == FORCE_VORTEX) ApplyVortex(forceBuffer.forces[i], gTime * 0.01, pos_next, force, vel.xyz); } } if (USE_FLOOR > 0.0) FloorCollide(pos_next, vel.xyz, randomF, FLOOR_LEVEL, FLOOR_FRICTION, DeltaTimeSecs); // // Process all collisions // if (USE_COLLISIONS) { for(int i=0; i<gNumCollisions; ++i) { float coltype = collisionBuffer.collisions[i].position.w; if ( COLLISION_SPHERE == coltype ) { SphereCollide(collisionBuffer.collisions[i], pos.w, pos_next, vel.xyz); // collisions_inuse[i]); } else if ( COLLISION_TERRIAN == coltype ) { TerrainCollide(collisionBuffer.collisions[i], pos_next, randomF, vel.xyz); } } } float inv_mass = 1.0 / MASS; float damping = DAMPING; vel.xyz += force * inv_mass * DeltaTimeSecs; // F = ma damping = 1.0 - (1.0 - damping) * DeltaTimeSecs; vel.xyz *= damping; //vel.xyz += force; // turbulence behaviour if (USE_TURBULENCE > 0.0) { float f2 = cos(gTime) - 2.2; float f3 = sin(gTime) + 0.5; vec3 noiseVel = vec3( snoise(pos.xyz*NOISE_FREQ + gTime*NOISE_SPEED), snoise(pos.xyz*NOISE_FREQ + gTime*NOISE_SPEED+f2), snoise(pos.xyz*NOISE_FREQ + gTime*NOISE_SPEED+f3) ); vel.xyz += noiseVel * NOISE_AMP; } // update position // // new position = old position + velocity * deltaTime if (gUpdatePosition > 0) { //pos.xyz += vel.xyz * DeltaTimeSecs; pos.xyz = pos_next; if (CONSTRAINT_MAGN > 0.0) { ApplyConstraint(gTime * 0.01, vel.w, force, vel.xyz, pos.xyz); } if (USE_COLLISIONS) { for(int i=0; i<gNumCollisions; ++i) { //if ( inuse < 1.0 ) // collisions_inuse[i] < 1.0 ) // continue; float coltype = collisionBuffer.collisions[i].position.w; if ( COLLISION_SPHERE == coltype) { SphereConstraint(collisionBuffer.collisions[i], pos.w, pos.xyz); } else if ( COLLISION_TERRIAN == coltype ) { TerrainConstraint(collisionBuffer.collisions[i], pos.xyz); } } } if (USE_FLOOR > 0.0) FloorConstraint(pos.xyz, FLOOR_LEVEL); } // write back particleBuffer.particles[flattened_id].Pos = pos; // pos.w - particle size particleBuffer.particles[flattened_id].Vel = vel; particleBuffer.particles[flattened_id].Color = packedColor; // in y we store lifetime, in z - Age, in W - Index particleBuffer.particles[flattened_id].Rot = rot; /* // noise3 based color vec4 color = particleBuffer.particles[flattened_id].Color; float a = clamp(1.0 - snoise( 0.03 * pos.xyz + 0.01 * vel.xyz ), 0.0, 1.0); particleBuffer.particles[flattened_id].Color = vec4(a, a, a, color.w); */ }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.Swagger.Model { /// <summary> /// /// </summary> [DataContract] public partial class QuietHour : IEquatable<QuietHour> { public enum { [EnumMember(Value = "Sunday")] Sunday, [EnumMember(Value = "Monday")] Monday, [EnumMember(Value = "Tuesday")] Tuesday, [EnumMember(Value = "Wednesday")] Wednesday, [EnumMember(Value = "Thursday")] Thursday, [EnumMember(Value = "Friday")] Friday, [EnumMember(Value = "Saturday")] Saturday } /// <summary> /// Initializes a new instance of the <see cref="QuietHour" /> class. /// Initializes a new instance of the <see cref="QuietHour" />class. /// </summary> /// <param name="DayOfWeekList">DayOfWeekList.</param> /// <param name="StartHourLocal">StartHourLocal.</param> /// <param name="StartMinLocal">StartMinLocal.</param> /// <param name="DurationMin">DurationMin.</param> /// <param name="TimeZoneName">TimeZoneName.</param> public QuietHour(List<DayOfWeekListEnum?> DayOfWeekList = null, int? StartHourLocal = null, int? StartMinLocal = null, int? DurationMin = null, string TimeZoneName = null) { this.DayOfWeekList = DayOfWeekList; this.StartHourLocal = StartHourLocal; this.StartMinLocal = StartMinLocal; this.DurationMin = DurationMin; this.TimeZoneName = TimeZoneName; } /// <summary> /// Gets or Sets DayOfWeekList /// </summary> [DataMember(Name="DayOfWeekList", EmitDefaultValue=false)] public List<string> DayOfWeekList { get; set; } /// <summary> /// Gets or Sets StartHourLocal /// </summary> [DataMember(Name="StartHourLocal", EmitDefaultValue=false)] public int? StartHourLocal { get; set; } /// <summary> /// Gets or Sets StartMinLocal /// </summary> [DataMember(Name="StartMinLocal", EmitDefaultValue=false)] public int? StartMinLocal { get; set; } /// <summary> /// Gets or Sets DurationMin /// </summary> [DataMember(Name="DurationMin", EmitDefaultValue=false)] public int? DurationMin { get; set; } /// <summary> /// Gets or Sets TimeZoneName /// </summary> [DataMember(Name="TimeZoneName", EmitDefaultValue=false)] public string TimeZoneName { 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 QuietHour {\n"); sb.Append(" DayOfWeekList: ").Append(DayOfWeekList).Append("\n"); sb.Append(" StartHourLocal: ").Append(StartHourLocal).Append("\n"); sb.Append(" StartMinLocal: ").Append(StartMinLocal).Append("\n"); sb.Append(" DurationMin: ").Append(DurationMin).Append("\n"); sb.Append(" TimeZoneName: ").Append(TimeZoneName).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as QuietHour); } /// <summary> /// Returns true if QuietHour instances are equal /// </summary> /// <param name="other">Instance of QuietHour to be compared</param> /// <returns>Boolean</returns> public bool Equals(QuietHour other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.DayOfWeekList == other.DayOfWeekList || this.DayOfWeekList != null && this.DayOfWeekList.SequenceEqual(other.DayOfWeekList) ) && ( this.StartHourLocal == other.StartHourLocal || this.StartHourLocal != null && this.StartHourLocal.Equals(other.StartHourLocal) ) && ( this.StartMinLocal == other.StartMinLocal || this.StartMinLocal != null && this.StartMinLocal.Equals(other.StartMinLocal) ) && ( this.DurationMin == other.DurationMin || this.DurationMin != null && this.DurationMin.Equals(other.DurationMin) ) && ( this.TimeZoneName == other.TimeZoneName || this.TimeZoneName != null && this.TimeZoneName.Equals(other.TimeZoneName) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.DayOfWeekList != null) hash = hash * 59 + this.DayOfWeekList.GetHashCode(); if (this.StartHourLocal != null) hash = hash * 59 + this.StartHourLocal.GetHashCode(); if (this.StartMinLocal != null) hash = hash * 59 + this.StartMinLocal.GetHashCode(); if (this.DurationMin != null) hash = hash * 59 + this.DurationMin.GetHashCode(); if (this.TimeZoneName != null) hash = hash * 59 + this.TimeZoneName.GetHashCode(); return hash; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; [System.Serializable] public class ActionBarSlot { public Spell spell; public Item item; public KeyCode keycode; } public class ActionBars : MonoBehaviour { public GUISkin mySkin; //The GUISkin you want to use. public Texture2D cooldownTexture; //The texture for cooldown overlay. public Texture2D frame; //The frame around the icons and slots public Material cooldownMaterial; //The material for cooldown public int leftActionBarWidth; //The width of the left actionbar public int rightActionBarWidth; //The width of the right actionbar public int bottomActionBarWidth; //The width of the right actionbar public List<ActionBarSlot> leftActionbarSlots; //The list of the left actionbar slots public List<ActionBarSlot> rightActionbarSlots; //The list of the right actionbar slots public List<ActionBarSlot> bottomActionbarSlots; //The list of the bottom actionbar slots public bool left; //Is the left actionbar? public bool right; //Is the right actionbar? public bool bottom; //Is the bottom actionbar? [HideInInspector] public bool hoverActionBar; //Are we hovering over the actionbar? private SpellBook spellbook; //Reference to the spellbook private InventoryManager inventory; //Reference to the inventory private string hoverName; //The name of the hovered item private float slotSize; //The size of the slots private float slotBorder; //How much space is there between the slots private Rect leftActionbarsRect; //The size and position of the size where the left actionbars are drawn private Rect rightActionbarsRect; //The size and position of the size where the right actionbars are drawn private Rect bottomActionbarsRect; //The size and position of the size where the bottom actionbars are drawn private float screenWidth; //The value to hold the width of the screen private float screenHeigth; //The value to hold the height of the screen // Use this for initialization void Start () { //Find the spellbook and get spellbook script from it spellbook = GameObject.FindGameObjectWithTag("SpellBook").GetComponent<SpellBook>(); //Find the inventory and get inventory script from it inventory = GameObject.FindGameObjectWithTag("Inventory").GetComponent<InventoryManager>(); //Resize the GUI to fit the screen ResizeGUI(); } // Update is called once per frame void Update () { //If the height or the width of the screen changes - resize the gui if(Screen.width != screenWidth || Screen.height != screenHeigth) ResizeGUI(); //This part resizes the fontsize according to the size of the screen mySkin.box.fontSize = Mathf.Min(Screen.width, Screen.height) / 50; mySkin.label.fontSize = Mathf.Min(Screen.width, Screen.height) / 50; mySkin.textArea.fontSize = Mathf.Min(Screen.width, Screen.height) / 50; mySkin.GetStyle("Stacksize").fontSize = Mathf.Min(Screen.width, Screen.height) / 50; mySkin.GetStyle("RibbonLabel").fontSize = Mathf.Min(Screen.width, Screen.height) / 50; } void ResizeGUI() { //Calculate the size of the slots slotSize = Screen.width * 0.04f; //Calculate the size of the space between the slots slotBorder = slotSize * 0.075f; //Calculate the size and position of the left bars leftActionbarsRect = new Rect(slotBorder, Screen.height * 0.1f, Screen.width * 0.2f, Screen.height * 0.8f); //Calculate the size and position of the right bars rightActionbarsRect = new Rect(Screen.width - rightActionBarWidth * (slotSize + slotBorder), Screen.height * 0.1f, Screen.width * 0.2f, Screen.height * 0.8f); //Calculate the size and position of the bottom bars bottomActionbarsRect = new Rect(Screen.width * 0.5f - (bottomActionbarSlots.Count * (slotSize + slotBorder)) * 0.5f, Screen.height - (slotSize + slotBorder), Screen.width * 0.8f, (slotSize + slotBorder)); //Store the width of the screen screenWidth = Screen.width; //Store the height of the screen screenHeigth = Screen.height; } void OnGUI() { hoverActionBar = false; hoverName = ""; GUI.depth = 1; GUI.skin = mySkin; Event curEvent = Event.current; int j; int k; Spell spell = null; Item item = null; Rect actionBarRect = new Rect(0,0,0,0); int actionBarAmount = 0; int actionBarWidth = 0; List<ActionBarSlot> actionBarSlots = new List<ActionBarSlot>(); if(right){ actionBarRect = rightActionbarsRect; actionBarWidth = rightActionBarWidth; actionBarSlots = rightActionbarSlots; actionBarAmount = rightActionbarSlots.Count; } if(bottom) { actionBarRect = bottomActionbarsRect; actionBarWidth = bottomActionBarWidth; actionBarSlots = bottomActionbarSlots; actionBarAmount = bottomActionbarSlots.Count; } if(left) { actionBarRect = leftActionbarsRect; actionBarWidth = leftActionBarWidth; actionBarSlots = leftActionbarSlots; actionBarAmount = leftActionbarSlots.Count; } GUILayout.BeginArea(actionBarRect); for(int i = 0; i < actionBarAmount; i++) { j = i / actionBarWidth; k = i % actionBarWidth; //Calculate the size and position of the currentRect Rect currentRect = (new Rect(k * (slotSize + slotBorder), j * (slotSize + slotBorder), slotSize, slotSize)); //If we're hovering over a actionbar slot if(currentRect.Contains(curEvent.mousePosition)) { hoverActionBar = true; } //If the slots contains an item if(actionBarSlots[i].item) { //store the item of the slot item = actionBarSlots[i].item; //If the item has an icon then draw the icon as the slot if(item.icon) GUI.DrawTexture(currentRect, item.icon); //If the stacksize of the item is greater than zero //Draw a label saying the size of the stack if(actionBarSlots[i].item.stackSize > 0) GUI.Label(currentRect, actionBarSlots[i].item.stackSize.ToString(),"Stacksize"); } //Else if the actionbar contains a spell else if(actionBarSlots[i].spell) { //Store the spell of the slot spell = actionBarSlots[i].spell; //If the spell has an icon //Draw the icon as the slot if(spell.icon) GUI.DrawTexture(currentRect, spell.icon); } //If there's no item or spell in the slot else { //Just draw a simple box GUI.Box(currentRect, ""); } //Store the keycode of the slot as a string string keycodeString = actionBarSlots[i].keycode.ToString(); //If the keycode is 6 characters long then assume it's of type "Alpha + number" example: Alpha1 if(keycodeString.Length == 6) { //Remove the first 5 characters so that it only contains the number. keycodeString = keycodeString.Substring(5, 1); } //If keycode isn't "None" then draw a label containing the keycode if(keycodeString != "None") GUI.Label(currentRect, keycodeString); //If the mouse is hovering over the slot if(currentRect.Contains(curEvent.mousePosition)) { //If the slot contains a spell if(actionBarSlots[i].spell) //Set the hovername equal to the name of the spell hoverName = spell.spellName; //Else if the slot contains an item else if(actionBarSlots[i].item) //Set the hovername equal to the name of the spell hoverName = item.itemName; //If the player release the mouse over the slot if((curEvent.type == EventType.MouseUp)) { //If we're dragging a spell if(spellbook.draggedSpell) { //If there's allready a spell in the slot //Then replace the dragged spell with the one in the slot if(actionBarSlots[i].spell) { actionBarSlots[i].spell = spellbook.draggedSpell; spellbook.draggedSpell = spell; spellbook.dragging = true; } //Else if there's an item in the slot //Replace the item in the slot with the spell and set the item to be dragged else if(actionBarSlots[i].item) { actionBarSlots[i].spell = spellbook.draggedSpell; spellbook.draggedSpell = null; spellbook.dragging = false; inventory.draggedItem = item; inventory.dragging = true; if(actionBarSlots[i].item) actionBarSlots[i].item = null; else if(actionBarSlots[i].spell) actionBarSlots[i].spell = null; } //If there's nothing in the slot then just put the spell in the slot else { actionBarSlots[i].spell = spellbook.draggedSpell; spellbook.draggedSpell = null; spellbook.dragging = false; } } //Else if we're dragging an item else if(inventory.draggedItem) { //If we the slot contains either a spell or an item if(actionBarSlots[i].spell || actionBarSlots[i].item) { //If it's a spell then replace it with the dragged item if(actionBarSlots[i].spell) { actionBarSlots[i].item = inventory.draggedItem; inventory.draggedItem = null; inventory.items[inventory.dragOrigin] = inventory.draggedItem; spellbook.draggedSpell = spell; spellbook.dragging = true; actionBarSlots[i].spell = null; } //Else if there's an item in the slot replace it with the dragged item else { actionBarSlots[i].item = inventory.draggedItem; inventory.items[inventory.dragOrigin] = inventory.draggedItem; inventory.draggedItem = item; inventory.dragging = true; } } //If there's nothing in the slot then put the dragged item in the slot else { actionBarSlots[i].item = inventory.draggedItem; inventory.items[inventory.dragOrigin] = inventory.draggedItem; inventory.draggedItem = null; inventory.dragging = false; } } } //If the player presses the mouse on a slot and not pressing the shift key and the inventory or the spell is dragging something else if(curEvent.type == EventType.MouseDown && !curEvent.shift && !inventory.dragging && !spellbook.dragging) { //If there's a spell in the slot use the spell if(actionBarSlots[i].spell) { if(!actionBarSlots[i].spell.onCooldown) actionBarSlots[i].spell.Use(); } //If there's an item in the slot use the item else if(actionBarSlots[i].item) { if(!actionBarSlots[i].item.onCooldown) actionBarSlots[i].item.Use(); } } //If the player drags the mouse and is holding the shift key and we're not currently dragging anything and the player isn't releasing the mouse or pressing it down else if(curEvent.type == EventType.MouseDrag && curEvent.shift && (!spellbook.draggedSpell || !inventory.draggedItem) && (curEvent.type != EventType.MouseDown || curEvent.type != EventType.MouseUp)) { //If there's a spell in the slot //Set the spell in the slot to being dragged and remove it from the slot if(actionBarSlots[i].spell) { spellbook.dragging = true; spellbook.draggedSpell = actionBarSlots[i].spell; actionBarSlots[i].spell = null; } //If there's an item in the slot //Set the item in the slot to being dragged and remove it from the slot else if(actionBarSlots[i].item) { inventory.dragging = true; inventory.draggedItem = actionBarSlots[i].item; actionBarSlots[i].item = null; } } } //If there's a keycode set for the slot and player pressing the button if(curEvent.keyCode == actionBarSlots[i].keycode && curEvent.keyCode != KeyCode.None && curEvent.type == EventType.KeyDown) { //If there's a spell in the slot if(actionBarSlots[i].spell) { //If the spell is not on cooldown use the spell if(!actionBarSlots[i].spell.onCooldown) { actionBarSlots[i].spell.Use(); } } //Else if there's an item in the slot else if(actionBarSlots[i].item && actionBarSlots[i].item.itemType == EquipmentSlotType.consumable) { //If the item isn't on cooldown use the item if(!actionBarSlots[i].item.onCooldown) actionBarSlots[i].item.Use(); } } //If there's a spell in the slot and the spell is on cooldown if(actionBarSlots[i].spell && actionBarSlots[i].spell.onCooldown) { if(Event.current.type.Equals(EventType.Repaint)) { //Set the cutoff of the cooldown material to match the state of the cooldown cooldownMaterial.SetFloat("_Cutoff", actionBarSlots[i].spell.cooldownTimer / actionBarSlots[i].spell.cooldown); //Draw the cooldown texture over the spell Graphics.DrawTexture(currentRect, cooldownTexture, cooldownMaterial); } } //If there's an item in the slot and the item is on cooldown else if(actionBarSlots[i].item && actionBarSlots[i].item.onCooldown) { if(Event.current.type.Equals(EventType.Repaint)) { //Set the cutoff of the cooldown material to match the state of the cooldown cooldownMaterial.SetFloat("_Cutoff", actionBarSlots[i].item.cooldownTimer / actionBarSlots[i].item.cooldown); //Draw the cooldown texture over the item Graphics.DrawTexture(currentRect, cooldownTexture, cooldownMaterial); } } //Draw the frame over the slot GUI.DrawTexture(currentRect, frame); } GUILayout.EndArea(); //If there's something set as the hovername if(hoverName != "") //Draw a box containing the hovername GUI.Box(new Rect(curEvent.mousePosition.x - mySkin.box.CalcSize(new GUIContent(hoverName)).x * 0.5f, curEvent.mousePosition.y - mySkin.box.CalcSize(new GUIContent(hoverName)).y , mySkin.box.CalcSize(new GUIContent(hoverName)).x, mySkin.box.CalcSize(new GUIContent(hoverName)).y),hoverName, "textArea"); } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Management.Automation; using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Creates Azure Site Recovery Policy object in memory. /// </summary> [Cmdlet( VerbsCommon.New, "AzureRmRecoveryServicesAsrPolicy", DefaultParameterSetName = ASRParameterSets.HyperVToAzure, SupportsShouldProcess = true)] [Alias("New-ASRPolicy")] [OutputType(typeof(ASRJob))] public class NewAzureRmRecoveryServicesAsrPolicy : SiteRecoveryCmdletBase { /// <summary> /// Switch Paramter to create VMwareToAzure / InMageV2Azure policy. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.VMwareToAzure, Position = 0, Mandatory = true)] public SwitchParameter VMwareToAzure { get; set; } /// <summary> /// Switch Paramter to create VMwareToAzure / InMage policy. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.AzureToVMware, Position = 0, Mandatory = true)] public SwitchParameter AzureToVMware { get; set; } /// <summary> /// Switch Paramter to create VMwareToAzure / InMage policy. /// </summary> [Parameter(Position = 0, ParameterSetName = ASRParameterSets.HyperVToAzure, Mandatory = false)] public SwitchParameter HyperVToAzure { get; set; } /// <summary> /// Switch Paramter to create VMwareToAzure / InMage policy. /// </summary> [Parameter(Position = 0, ParameterSetName = ASRParameterSets.EnterpriseToEnterprise, Mandatory = false)] public SwitchParameter VmmToVmm { get; set; } /// <summary> /// Gets or sets Name of the Policy. /// </summary> [Parameter(Mandatory = true)] public string Name { get; set; } /// <summary> /// Gets or sets Replication Provider of the Policy. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.HyperVToAzure, Mandatory = true)] [ValidateNotNullOrEmpty] [ValidateSet( Constants.HyperVReplica2012R2, Constants.HyperVReplica2012, Constants.HyperVReplicaAzure)] public string ReplicationProvider { get; set; } /// <summary> /// Gets or sets a value for Replication Method of the Policy. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)] [ValidateNotNullOrEmpty] [ValidateSet( Constants.OnlineReplicationMethod, Constants.OfflineReplicationMethod)] public string ReplicationMethod { get; set; } /// <summary> /// Gets or sets Replication Frequency of the Policy in seconds. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise, Mandatory = true)] [Parameter( ParameterSetName = ASRParameterSets.HyperVToAzure, Mandatory = true)] [ValidateNotNullOrEmpty] [ValidateSet( Constants.Thirty, Constants.ThreeHundred, Constants.NineHundred)] public string ReplicationFrequencyInSeconds { get; set; } /// <summary> /// Gets or sets Recovery Points of the Policy. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)] [Parameter( ParameterSetName = ASRParameterSets.HyperVToAzure)] [ValidateNotNullOrEmpty] [DefaultValue(0)] [Alias("RecoveryPoints")] public int NumberOfRecoveryPointsToRetain { get; set; } [Parameter(ParameterSetName = ASRParameterSets.VMwareToAzure, Mandatory = true)] [Parameter(ParameterSetName = ASRParameterSets.AzureToVMware, Mandatory = true)] [ValidateNotNullOrEmpty] [DefaultValue(0)] public int RecoveryPointRetentionInHours { get; set; } /// <summary> /// Gets or sets Application Consistent Snapshot Frequency of the Policy in hours. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [DefaultValue(0)] public int ApplicationConsistentSnapshotFrequencyInHours { get; set; } /// <summary> /// Gets or sets a value indicating whether Compression needs to be Enabled on the Policy. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)] [DefaultValue(Constants.Disable)] [ValidateSet( Constants.Enable, Constants.Disable)] public string Compression { get; set; } /// <summary> /// Gets or sets the Replication Port of the Policy. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise, Mandatory = true)] [ValidateNotNullOrEmpty] public ushort ReplicationPort { get; set; } /// <summary> /// Gets or sets the Replication Port of the Policy. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)] [ValidateNotNullOrEmpty] [ValidateSet( Constants.AuthenticationTypeCertificate, Constants.AuthenticationTypeKerberos)] public string Authentication { get; set; } /// <summary> /// Gets or sets Replication Start time of the Policy. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)] [Parameter( ParameterSetName = ASRParameterSets.HyperVToAzure)] [ValidateNotNullOrEmpty] public TimeSpan? ReplicationStartTime { get; set; } /// <summary> /// Gets or sets a value indicating whether Replica should be Deleted on /// disabling protection of a protection entity protected by the Policy. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.EnterpriseToEnterprise)] [DefaultValue(Constants.NotRequired)] [ValidateSet( Constants.Required, Constants.NotRequired)] public string ReplicaDeletion { get; set; } /// <summary> /// Gets or sets Recovery Azure Storage Account Name of the Policy for E2A scenarios. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.HyperVToAzure)] [ValidateNotNullOrEmpty] public string RecoveryAzureStorageAccountId { get; set; } /// <summary> /// Gets or sets Encrypt parameter. On passing, data will be encrypted. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.HyperVToAzure)] [DefaultValue(Constants.Disable)] [ValidateSet( Constants.Enable, Constants.Disable)] public string Encryption { get; set; } /// <summary> /// Gets or sets Multi VM sync status parameter. /// </summary> [Parameter( DontShow = true, ParameterSetName = ASRParameterSets.VMwareToAzure)] [Parameter( DontShow = true, ParameterSetName = ASRParameterSets.AzureToVMware)] [ValidateNotNullOrEmpty] [DefaultValue(Constants.Enable)] [ValidateSet(Constants.Enable,Constants.Disable)] public string MultiVmSyncStatus { get; set; } /// <summary> /// Gets or sets RPO warning threshold in minutes. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.VMwareToAzure, Mandatory = true)] [Parameter(ParameterSetName = ASRParameterSets.AzureToVMware, Mandatory = true)] public int RPOWarningThresholdInMinutes { get; set; } /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); if (this.ShouldProcess( this.Name, VerbsCommon.New)) { switch (this.ParameterSetName) { case ASRParameterSets.EnterpriseToEnterprise: this.EnterpriseToEnterprisePolicyObject(); break; case ASRParameterSets.HyperVToAzure: this.HyperVToAzurePolicyObject(); break; case ASRParameterSets.VMwareToAzure: case ASRParameterSets.AzureToVMware: this.ReplicationProvider = (this.ParameterSetName == ASRParameterSets.VMwareToAzure) ? Constants.InMageAzureV2 : Constants.InMage; this.V2AandV2VPolicyObject(); break; } } } /// <summary> /// Creates an E2A Policy Object /// </summary> private void HyperVToAzurePolicyObject() { if (string.Compare( this.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase) != 0) { throw new InvalidOperationException( string.Format( Resources.IncorrectReplicationProvider, this.ReplicationProvider)); } PSRecoveryServicesClient.ValidateReplicationStartTime(this.ReplicationStartTime); var replicationFrequencyInSeconds = PSRecoveryServicesClient.ConvertReplicationFrequencyToUshort( this.ReplicationFrequencyInSeconds); var hyperVReplicaAzurePolicyInput = new HyperVReplicaAzurePolicyInput { ApplicationConsistentSnapshotFrequencyInHours = this.ApplicationConsistentSnapshotFrequencyInHours, Encryption = this.MyInvocation.BoundParameters.ContainsKey( Utilities.GetMemberName(() => this.Encryption)) ? this.Encryption : Constants.Disable, OnlineReplicationStartTime = this.ReplicationStartTime == null ? null : this.ReplicationStartTime.ToString(), RecoveryPointHistoryDuration = this.NumberOfRecoveryPointsToRetain, ReplicationInterval = replicationFrequencyInSeconds }; hyperVReplicaAzurePolicyInput.StorageAccounts = new List<string>(); if (this.RecoveryAzureStorageAccountId != null) { var storageAccount = this.RecoveryAzureStorageAccountId; hyperVReplicaAzurePolicyInput.StorageAccounts.Add(storageAccount); } var createPolicyInputProperties = new CreatePolicyInputProperties { ProviderSpecificInput = hyperVReplicaAzurePolicyInput }; var createPolicyInput = new CreatePolicyInput { Properties = createPolicyInputProperties }; var response = this.RecoveryServicesClient.CreatePolicy( this.Name, createPolicyInput); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } /// <summary> /// Creates an E2E Policy object /// </summary> private void EnterpriseToEnterprisePolicyObject() { if ((string.Compare( this.ReplicationProvider, Constants.HyperVReplica2012, StringComparison.OrdinalIgnoreCase) != 0) && (string.Compare( this.ReplicationProvider, Constants.HyperVReplica2012R2, StringComparison.OrdinalIgnoreCase) != 0)) { throw new InvalidOperationException( string.Format( Resources.IncorrectReplicationProvider, this.ReplicationProvider)); } PSRecoveryServicesClient.ValidateReplicationStartTime(this.ReplicationStartTime); var replicationFrequencyInSeconds = PSRecoveryServicesClient.ConvertReplicationFrequencyToUshort( this.ReplicationFrequencyInSeconds); var createPolicyInputProperties = new CreatePolicyInputProperties(); if (string.Compare( this.ReplicationProvider, Constants.HyperVReplica2012, StringComparison.OrdinalIgnoreCase) == 0) { createPolicyInputProperties.ProviderSpecificInput = new HyperVReplicaPolicyInput { AllowedAuthenticationType = (ushort)(string.Compare( this.Authentication, Constants.AuthenticationTypeKerberos, StringComparison.OrdinalIgnoreCase) == 0 ? 1 : 2), ApplicationConsistentSnapshotFrequencyInHours = this.ApplicationConsistentSnapshotFrequencyInHours, Compression = this.MyInvocation.BoundParameters.ContainsKey( Utilities.GetMemberName(() => this.Compression)) ? this.Compression : Constants.Disable, InitialReplicationMethod = string.Compare( this.ReplicationMethod, Constants.OnlineReplicationMethod, StringComparison.OrdinalIgnoreCase) == 0 ? "OverNetwork" : "Offline", OnlineReplicationStartTime = this.ReplicationStartTime.ToString(), RecoveryPoints = this.NumberOfRecoveryPointsToRetain, ReplicaDeletion = this.MyInvocation.BoundParameters.ContainsKey( Utilities.GetMemberName(() => this.ReplicaDeletion)) ? this.ReplicaDeletion : Constants.NotRequired, ReplicationPort = this.ReplicationPort }; } else { createPolicyInputProperties.ProviderSpecificInput = new HyperVReplicaBluePolicyInput { AllowedAuthenticationType = (ushort)(string.Compare( this.Authentication, Constants .AuthenticationTypeKerberos, StringComparison .OrdinalIgnoreCase) == 0 ? 1 : 2), ApplicationConsistentSnapshotFrequencyInHours = this.ApplicationConsistentSnapshotFrequencyInHours, Compression = this.MyInvocation.BoundParameters.ContainsKey( Utilities.GetMemberName(() => this.Compression)) ? this.Compression : Constants.Disable, InitialReplicationMethod = string.Compare( this.ReplicationMethod, Constants.OnlineReplicationMethod, StringComparison.OrdinalIgnoreCase) == 0 ? "OverNetwork" : "Offline", OnlineReplicationStartTime = this.ReplicationStartTime.ToString(), RecoveryPoints = this.NumberOfRecoveryPointsToRetain, ReplicaDeletion = this.MyInvocation.BoundParameters.ContainsKey( Utilities.GetMemberName(() => this.ReplicaDeletion)) ? this.ReplicaDeletion : Constants.NotRequired, ReplicationFrequencyInSeconds = replicationFrequencyInSeconds, ReplicationPort = this.ReplicationPort }; } var createPolicyInput = new CreatePolicyInput { Properties = createPolicyInputProperties }; var responseBlue = this.RecoveryServicesClient.CreatePolicy( this.Name, createPolicyInput); var jobResponseBlue = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(responseBlue.Location)); this.WriteObject(new ASRJob(jobResponseBlue)); } /// <summary> /// Creates an InMageAzureV2 / InMage Policy Object. /// </summary> private void V2AandV2VPolicyObject() { // Validate the Replication Provider. if (string.Compare( this.ReplicationProvider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase) != 0 && string.Compare( this.ReplicationProvider, Constants.InMage, StringComparison.OrdinalIgnoreCase) != 0) { throw new InvalidOperationException( string.Format( Resources.IncorrectReplicationProvider, this.ReplicationProvider)); } // Set the Default Parameters. this.ApplicationConsistentSnapshotFrequencyInHours = this.ApplicationConsistentSnapshotFrequencyInHours; this.RecoveryPointRetentionInHours = this.MyInvocation.BoundParameters.ContainsKey( Utilities.GetMemberName(() => this.RecoveryPointRetentionInHours)) ? this.RecoveryPointRetentionInHours : 24; this.RPOWarningThresholdInMinutes = this.MyInvocation.BoundParameters.ContainsKey( Utilities.GetMemberName(() => this.RPOWarningThresholdInMinutes)) ? this.RPOWarningThresholdInMinutes : 15; this.MultiVmSyncStatus = this.MyInvocation.BoundParameters.ContainsKey( Utilities.GetMemberName(() => this.MultiVmSyncStatus)) ? this.MultiVmSyncStatus : Constants.Enable; var crashConsistentFrequencyInMinutes = 5; // Create the Create Policy Input. var createPolicyInput = new CreatePolicyInput { Properties = new CreatePolicyInputProperties() }; // Check the Replication Provider Type. if (string.Compare( this.ReplicationProvider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase) == 0) { // Set the Provider Specific Input for InMageAzureV2. createPolicyInput.Properties.ProviderSpecificInput = new InMageAzureV2PolicyInput { AppConsistentFrequencyInMinutes = this.ApplicationConsistentSnapshotFrequencyInHours * 60, RecoveryPointHistory = this.RecoveryPointRetentionInHours * 60, // Convert from hours to minutes. RecoveryPointThresholdInMinutes = this.RPOWarningThresholdInMinutes, MultiVmSyncStatus = (SetMultiVmSyncStatus)Enum.Parse( typeof(SetMultiVmSyncStatus), this.MultiVmSyncStatus), CrashConsistentFrequencyInMinutes = crashConsistentFrequencyInMinutes }; } else { // Set the Provider Specific Input for InMage. createPolicyInput.Properties.ProviderSpecificInput = new InMagePolicyInput { AppConsistentFrequencyInMinutes = this.ApplicationConsistentSnapshotFrequencyInHours * 60, RecoveryPointHistory = this.RecoveryPointRetentionInHours * 60, // Convert from hours to minutes. RecoveryPointThresholdInMinutes = this.RPOWarningThresholdInMinutes, MultiVmSyncStatus = (SetMultiVmSyncStatus)Enum.Parse( typeof(SetMultiVmSyncStatus), this.MultiVmSyncStatus) }; } var response = this.RecoveryServicesClient.CreatePolicy(this.Name, createPolicyInput); var jobId = PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location); var jobResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryJobDetails(jobId); this.WriteObject(new ASRJob(jobResponse)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Runtime.InteropServices; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using Microsoft.Scripting; namespace NumpyDotNet { /// <summary> /// Implements array manipulation and construction functionality. This /// class has functionality corresponding to functions in arrayobject.c, /// ctors.c, and multiarraymodule.c /// </summary> public static class NpyArray { /// <summary> /// Copies the source object into the destination array. src can be /// any type so long as the number of elements matches dest. In the /// case of strings, they will be padded with spaces if needed but /// can not be longer than the number of elements in dest. /// </summary> /// <param name="dest">Destination array</param> /// <param name="src">Source object</param> public static void CopyObject(ndarray dest, Object src) { // For char arrays pad the input string. if (dest.Dtype.Type == NpyDefs.NPY_TYPECHAR.NPY_CHARLTR && dest.ndim > 0 && src is String) { int ndimNew = (int)dest.Dims[dest.ndim - 1]; int ndimOld = ((String)src).Length; if (ndimNew > ndimOld) { src = ((String)src).PadRight(ndimNew, ' '); } } ndarray srcArray; if (src is ndarray) { srcArray = (ndarray)src; } else if (false) { // TODO: Not handling scalars. See arrayobject.c:111 } else { srcArray = FromAny(src, dest.Dtype, 0, dest.ndim, dest.Dtype.Flags & NpyDefs.NPY_FORTRAN, null); } NpyCoreApi.MoveInto(dest, srcArray); } internal static void SetField(ndarray dest, IntPtr descr, int offset, object src) { // For char arrays pad the input string. if (dest.Dtype.Type == NpyDefs.NPY_TYPECHAR.NPY_CHARLTR && dest.ndim > 0 && src is String) { int ndimNew = (int)dest.Dims[dest.ndim - 1]; int ndimOld = ((String)src).Length; if (ndimNew > ndimOld) { src = ((String)src).PadRight(ndimNew, ' '); } } ndarray srcArray; if (src is ndarray) { srcArray = (ndarray)src; } else if (false) { // TODO: Not handling scalars. See arrayobject.c:111 } else { dtype src_dtype = NpyCoreApi.ToInterface<dtype>(descr); srcArray = FromAny(src, src_dtype, 0, dest.ndim, dest.Dtype.Flags & NpyDefs.NPY_FORTRAN, null); } NpyCoreApi.Incref(descr); if (NpyCoreApi.SetField(dest, descr, offset, srcArray) < 0) { NpyCoreApi.CheckError(); } } /// <summary> /// Checks the strides against the shape of the array. This duplicates /// NpyArray_CheckStrides and is only here because we don't currently support /// buffers and can simplify this function plus it's much faster to do here /// than to pass the arrays into the native world. /// </summary> /// <param name="elSize">Size of array element in bytes</param> /// <param name="shape">Size of each dimension of the array</param> /// <param name="strides">Stride of each dimension</param> /// <returns>True if strides are ok, false if not</returns> public static bool CheckStrides(int elSize, long[] shape, long[] strides) { // Product of all dimension sizes * element size in bytes. long numbytes = shape.Aggregate(1L, (acc, x) => acc * x) * elSize; long end = numbytes - elSize; for (int i = 0; i < shape.Length; i++) { if (strides[i] * (shape[i] - 1) > end) return false; } return true; } public static ndarray CheckFromAny(Object src, dtype descr, int minDepth, int maxDepth, int requires, Object context) { if ((requires & NpyDefs.NPY_NOTSWAPPED) != 0) { if (descr == null && src is ndarray && !((ndarray)src).Dtype.IsNativeByteOrder) { descr = new dtype(((ndarray)src).Dtype); } else if (descr != null && !descr.IsNativeByteOrder) { // Descr replace } if (descr != null) { descr.ByteOrder = (byte)'='; } } ndarray arr = FromAny(src, descr, minDepth, maxDepth, requires, context); if (arr != null && (requires & NpyDefs.NPY_ELEMENTSTRIDES) != 0 && arr.ElementStrides == 0) { arr = arr.NewCopy(NpyDefs.NPY_ORDER.NPY_ANYORDER); } return arr; } private static Exception UpdateIfCopyError() { return new ArgumentException("UPDATEIFCOPY used for non-array input."); } private static ndarray FromAnyReturn(ndarray result, int minDepth, int maxDepth) { if (minDepth != 0 && result.ndim < minDepth) { throw new ArgumentException("object of too small depth for desired array"); } if (maxDepth != 0 && result.ndim > maxDepth) { throw new ArgumentException("object too deep for desired array"); } return result; } internal static ndarray EnsureArray(object o) { if (o == null) { return null; } if (o.GetType() == typeof(ndarray)) { return (ndarray)o; } if (o is ndarray) { return NpyCoreApi.FromArray((ndarray)o, null, NpyDefs.NPY_ENSUREARRAY); } return FromAny(o, flags: NpyDefs.NPY_ENSUREARRAY); } internal static ndarray EnsureAnyArray(object o) { if (o == null) { return null; } if (o is ndarray) { return (ndarray)o; } return FromAny(o, flags: NpyDefs.NPY_ENSUREARRAY); } /// <summary> /// Constructs a new array from multiple input types, like lists, arrays, etc. /// </summary> /// <param name="src"></param> /// <param name="descr"></param> /// <param name="minDepth"></param> /// <param name="maxDepth"></param> /// <param name="requires"></param> /// <param name="context"></param> /// <returns></returns> public static ndarray FromAny(Object src, dtype descr = null, int minDepth = 0, int maxDepth=0, int flags=0, Object context=null) { ndarray result = null; if (src == null) { return Empty(new long[0], NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_OBJECT)); } Type t = src.GetType(); if (t != typeof(List) && t != typeof(PythonTuple)) { if (src is ndarray) { result = NpyCoreApi.FromArray((ndarray)src, descr, flags); return FromAnyReturn(result, minDepth, maxDepth); } if (src is ScalarGeneric) { if ((flags & NpyDefs.NPY_UPDATEIFCOPY)!=0) { throw UpdateIfCopyError(); } result = FromScalar((ScalarGeneric)src, descr); return FromAnyReturn(result, minDepth, maxDepth); } dtype newtype = (descr ?? FindScalarType(src)); if (descr == null && newtype != null) { if ((flags & NpyDefs.NPY_UPDATEIFCOPY) != 0) { throw UpdateIfCopyError(); } result = FromPythonScalar(src, newtype); return FromAnyReturn(result, minDepth, maxDepth); } // TODO: Handle buffer protocol // TODO: Look at __array_struct__ and __array_interface__ result = FromArrayAttr(NpyUtil_Python.DefaultContext, src, descr, context); if (result != null) { if (descr != null && !NpyCoreApi.EquivTypes(descr, result.Dtype) || flags != 0) { result = NpyCoreApi.FromArray(result, descr, flags); return FromAnyReturn(result, minDepth, maxDepth); } } } bool is_object = false; if ((flags&NpyDefs.NPY_UPDATEIFCOPY)!=0) { throw UpdateIfCopyError(); } if (descr == null) { descr = FindArrayType(src, null); } else if (descr.TypeNum == NpyDefs.NPY_TYPES.NPY_OBJECT) { is_object = true; } if (result == null) { // Hack required because in C# strings are enumerations of chars, not objects. // However, we want to keep src as a string if we are building a string or object array. if (!is_object && (descr.TypeNum != NpyDefs.NPY_TYPES.NPY_STRING || descr.Type == NpyDefs.NPY_TYPECHAR.NPY_CHARLTR) && descr.TypeNum != NpyDefs.NPY_TYPES.NPY_UNICODE && src is string && ((string)src).Length > 1) { src = ((string)src).Cast<object>(); } bool seq = false; if (src is IEnumerable<object>) { try { result = FromIEnumerable((IEnumerable<object>)src, descr, (flags & NpyDefs.NPY_FORTRAN) != 0, minDepth, maxDepth); seq = true; } catch (InsufficientMemoryException) { throw; } catch { if (is_object) { result = FromNestedList(src, descr, (flags & NpyDefs.NPY_FORTRAN) != 0); seq = true; } } } if (!seq) { result = FromPythonScalar(src, descr); } } return FromAnyReturn(result, minDepth, maxDepth); } internal static ndarray FromNestedList(object src, dtype descr, bool fortran) { long[] dims = new long[NpyDefs.NPY_MAXDIMS]; // Python generators appear as IEnumerables but can only be iterated over once // so we need to save the results. if (src is IEnumerableOfTWrapper<object>) { src = ((IEnumerableOfTWrapper<object>)src).ToList(); } int nd = ObjectDepthAndDimension(src, dims, 0, NpyDefs.NPY_MAXDIMS); if (nd == 0) { return FromPythonScalar(src, descr); } ndarray result = NpyCoreApi.AllocArray(descr, nd, dims, fortran); AssignToArray(src, result); return result; } /// <summary> /// Walks a set of nested lists (or tuples) to get the dimensions. The dimensionality must /// be consistent for each nesting level. Thus, if one level is a mix of lsits and scalars, /// it is truncated and all are assumed to be scalar objects. /// /// That is, [[1, 2], 3, 4] is a 1-d array of 3 elements. It just happens that element 0 is /// an object that is a list of [1, 2]. /// </summary> /// <param name="src">Input object to talk</param> /// <param name="dims">Array of dimensions of size 'max' filled in up to the return value</param> /// <param name="idx">Current iteration depth, always start with 0</param> /// <param name="max">Size of dims array at the start, then becomes depth so far when !firstElem</param> /// <param name="firstElem">True if processing the first element of the list (populates dims), false for subsequent (checks dims)</param> /// <returns>Number of dimensions (depth of nesting)</returns> internal static int ObjectDepthAndDimension(object src, long[] dims, int idx, int max, bool firstElem=true) { int nd = -1; // Recursively walk the tree and get the sizes of each dimension. When processing the // first element in each sequence, firstElem is true and we populate dims[]. After that, // we just verify that dims[] matches for subsequent elements. IList<object> list = src as IList<object>; // List and PythonTuple both implement IList if (max < 1 || list == null) { nd = 0; } else if (list.Count == 0) { nd = 0; } else if (max < 2) { // On the first pass, populate the dimensions array. One subsequent passes verify // that the size is the same or, if not, if (firstElem) { dims[idx] = list.Count; nd = 1; } else { nd = (dims[idx] == list.Count) ? 1 : 0; } } else if (!firstElem && dims[idx] != list.Count) { nd = 0; } else { // First element we traverse up to max depth and fill in the dims array. nd = ObjectDepthAndDimension(list.First(), dims, idx + 1, max - 1, firstElem); // Subsequent elements we just check that the size of each dimension is the // same as clip the max depth to shallowest depth we have seen thus far. nd = list.Skip(1).Aggregate(nd, (ndAcc, elem) => Math.Min(ndAcc, ObjectDepthAndDimension(elem, dims, idx + 1, ndAcc, false)) ); nd += 1; dims[idx] = list.Count; } return nd; } internal static ndarray FromArrayAttr(CodeContext cntx, object src, dtype descr, object context) { object f; if (src is PythonType || !PythonOps.TryGetBoundAttr(cntx, src, "__array__", out f)) { return null; } object result; if (context == null) { if (descr == null) { result = PythonCalls.Call(cntx, f); } else { result = PythonCalls.Call(cntx, f, descr); } } else { if (descr == null) { try { result = PythonCalls.Call(cntx, f, null, context); } catch (ArgumentTypeException) { result = PythonCalls.Call(cntx, f); } } else { try { result = PythonCalls.Call(cntx, f, descr, context); } catch (ArgumentTypeException) { result = PythonCalls.Call(cntx, f, context); } } } if (!(result is ndarray)) { throw new ArgumentException("object __array__ method not producing an array"); } return (ndarray)result; } internal static ndarray FromScalar(ScalarGeneric scalar, dtype descr = null) { ndarray arr = scalar.ToArray(); if (descr != null && !NpyCoreApi.EquivTypes((dtype)scalar.dtype, descr)) { arr = NpyCoreApi.CastToType(arr, descr, arr.IsFortran); } return arr; } internal static ndarray FromPythonScalar(object src, dtype descr) { int itemsize = descr.ElementSize; NpyDefs.NPY_TYPES type = descr.TypeNum; if (itemsize == 0 && NpyDefs.IsExtended(type)) { int n = PythonOps.Length(src); if (type == NpyDefs.NPY_TYPES.NPY_UNICODE) { n *= 4; } descr = new dtype(descr); descr.ElementSize = n; } ndarray result = NpyCoreApi.AllocArray(descr, 0, null, false); if (result.ndim > 0) { throw new ArgumentException("shape-mismatch on array construction"); } result.Dtype.f.SetItem(src, 0, result); return result; } /// <summary> /// Builds an array from a sequence of objects. The elements of the sequence /// can also be sequences in which case this function recursively walks the /// nested sequences and builds an n dimentional array. /// /// IronPython tuples and lists work as sequences. /// </summary> /// <param name="src">Input sequence</param> /// <param name="descr">Desired array element type or null to determine automatically</param> /// <param name="fortran">True if array should be Fortran layout, false for C</param> /// <param name="minDepth"></param> /// <param name="maxDepth"></param> /// <returns>New array instance</returns> internal static ndarray FromIEnumerable(IEnumerable<Object> src, dtype descr, bool fortran, int minDepth, int maxDepth) { ndarray result = null; // Python generators appear as IEnumerables but can only be iterated over once // so we need to save the results. if (src is IEnumerableOfTWrapper<object>) { src = ((IEnumerableOfTWrapper<object>)src).ToList(); } if (descr == null) { descr = FindArrayType(src, null, NpyDefs.NPY_MAXDIMS); } int itemsize = descr.ElementSize; NpyDefs.NPY_TYPES type = descr.TypeNum; bool checkIt = (descr.Type != NpyDefs.NPY_TYPECHAR.NPY_CHARLTR); bool stopAtString = type != NpyDefs.NPY_TYPES.NPY_STRING || descr.Type == NpyDefs.NPY_TYPECHAR.NPY_STRINGLTR; bool stopAtTuple = type == NpyDefs.NPY_TYPES.NPY_VOID && (descr.HasNames || descr.HasSubarray); int numDim = DiscoverDepth(src, NpyDefs.NPY_MAXDIMS + 1, stopAtString, stopAtTuple); if (numDim == 0) { return FromPythonScalar(src, descr); } else { if (maxDepth > 0 && type == NpyDefs.NPY_TYPES.NPY_OBJECT && numDim > maxDepth) { numDim = maxDepth; } if (maxDepth > 0 && numDim > maxDepth || minDepth > 0 && numDim < minDepth) { throw new ArgumentException("Invalid number of dimensions."); } long[] dims = new long[numDim]; DiscoverDimensions(src, numDim, dims, 0, checkIt); if (descr.Type == NpyDefs.NPY_TYPECHAR.NPY_CHARLTR && numDim > 0 && dims[numDim - 1] == 1) { numDim--; } if (itemsize == 0 && NpyDefs.IsExtended(descr.TypeNum)) { itemsize = DiscoverItemsize(src, numDim, 0); if (descr.TypeNum == NpyDefs.NPY_TYPES.NPY_UNICODE) { itemsize *= 4; } descr = new dtype(descr); descr.ElementSize = itemsize; } result = NpyCoreApi.AllocArray(descr, numDim, dims, fortran); AssignToArray(src, result); } return result; } internal static ndarray PrependOnes(ndarray arr, int nd, int ndmin) { IntPtr[] newdims = new IntPtr[ndmin]; IntPtr[] newstrides = new IntPtr[ndmin]; int num = ndmin - nd; // Set the first num dims and strides for the 1's for (int i=0; i<num; i++) { newdims[i] = (IntPtr)1; newstrides[i] = (IntPtr)arr.Dtype.ElementSize; } // Copy in the rest of dims and strides for (int i=num; i<ndmin; i++) { int k = i-num; newdims[i] = (IntPtr)arr.Dims[k]; newstrides[i] = (IntPtr)arr.Strides[k]; } return NpyCoreApi.NewView(arr.Dtype, ndmin, newdims, newstrides, arr, IntPtr.Zero, false); } private static dtype FindArrayReturn(dtype chktype, dtype minitype) { dtype result = NpyCoreApi.SmallType(chktype, minitype); if (result.TypeNum == NpyDefs.NPY_TYPES.NPY_VOID && minitype.TypeNum != NpyDefs.NPY_TYPES.NPY_VOID) { result = NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_OBJECT); } return result; } /// <summary> /// Given some object and an optional minimum type, returns the appropriate type descriptor. /// Equivalent to _array_find_type in common.c of CPython interface. /// </summary> /// <param name="src">Source object</param> /// <param name="minitype">Minimum type, or null if any</param> /// <param name="max">Maximum dimensions</param> /// <returns>Type descriptor fitting requirements</returns> public static dtype FindArrayType(Object src, dtype minitype, int max = NpyDefs.NPY_MAXDIMS) { dtype chktype = null; if (src is ndarray) { chktype = ((ndarray)src).Dtype; if (minitype == null) { return chktype; } else { return FindArrayReturn(chktype, minitype); } } if (src is ScalarGeneric) { chktype = (dtype)((ScalarGeneric)src).dtype; if (minitype == null) { return chktype; } else { return FindArrayReturn(chktype, minitype); } } if (minitype == null) { minitype = NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_BOOL); } if (max < 0) { chktype = UseDefaultType(src); return FindArrayReturn(chktype, minitype); } chktype = FindScalarType(src); if (chktype != null) { return FindArrayReturn(chktype, minitype); } if (src is Bytes) { Bytes b = (Bytes)src; chktype = new dtype(NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_STRING)); chktype.ElementSize = b.Count; return FindArrayReturn(chktype, minitype); } if (src is String) { String s = (String)src; chktype = new dtype(NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_UNICODE)); chktype.ElementSize = s.Length*4; return FindArrayReturn(chktype, minitype); } // TODO: Handle buffer protocol // TODO: __array_interface__ // TODO: __array_struct__ CodeContext cntx = NpyUtil_Python.DefaultContext; object arrayAttr; if (PythonOps.TryGetBoundAttr(cntx, src, "__array__", out arrayAttr)) { try { object ip = PythonCalls.Call(cntx, arrayAttr); if (ip is ndarray) { chktype = ((ndarray)ip).Dtype; return FindArrayReturn(chktype, minitype); } } catch { // Ignore errors } } // TODO: PyInstance_Check? if (src is IEnumerable<object> && !(src is dtype)) { // TODO: This does not work for user-defined Python sequences int l; try { l = PythonOps.Length(src); } catch { chktype = UseDefaultType(src); return FindArrayReturn(chktype, minitype); } if (l == 0 && minitype.TypeNum == NpyDefs.NPY_TYPES.NPY_BOOL) { minitype = NpyCoreApi.DescrFromType(NpyDefs.DefaultType); } while (--l >= 0) { object item; try { item = PythonOps.GetIndex(cntx, src, l); } catch { chktype = UseDefaultType(src); return FindArrayReturn(chktype, minitype); } chktype = FindArrayType(item, minitype, max-1); minitype = NpyCoreApi.SmallType(chktype, minitype); } chktype = minitype; return chktype; } chktype = UseDefaultType(src); return FindArrayReturn(chktype, minitype); } private static dtype UseDefaultType(Object src) { // TODO: User-defined types are not implemented yet. return NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_OBJECT); } /// <summary> /// Returns the descriptor for a given native type or null if src is /// not a scalar type /// </summary> /// <param name="src">Object to type</param> /// <returns>Descriptor for type of 'src' or null if not scalar</returns> internal static dtype FindScalarType(Object src) { NpyDefs.NPY_TYPES type; if (src is Double) type = NpyDefs.NPY_TYPES.NPY_DOUBLE; else if (src is Single) type = NpyDefs.NPY_TYPES.NPY_FLOAT; else if (src is Boolean) type = NpyDefs.NPY_TYPES.NPY_BOOL; else if (src is Byte) type = NpyDefs.NPY_TYPES.NPY_BYTE; else if (src is Int16) type = NpyDefs.NPY_TYPES.NPY_SHORT; else if (src is Int32) type = NpyCoreApi.TypeOf_Int32; else if (src is Int64) type = NpyCoreApi.TypeOf_Int64; else if (src is UInt16) type = NpyDefs.NPY_TYPES.NPY_USHORT; else if (src is UInt32) type = NpyCoreApi.TypeOf_UInt32; else if (src is UInt64) type = NpyCoreApi.TypeOf_UInt64; else if (src is BigInteger) { BigInteger bi = (BigInteger)src; if (Int64.MinValue <= bi && bi <= Int64.MaxValue) { type = NpyCoreApi.TypeOf_Int64; } else { type = NpyDefs.NPY_TYPES.NPY_OBJECT; } } else if (src is Complex) type = NpyDefs.NPY_TYPES.NPY_CDOUBLE; else type = NpyDefs.NPY_TYPES.NPY_NOTYPE; return (type != NpyDefs.NPY_TYPES.NPY_NOTYPE) ? NpyCoreApi.DescrFromType(type) : null; } /// <summary> /// Recursively discovers the nesting depth of a source object. /// </summary> /// <param name="src">Input object</param> /// <param name="max">Max recursive depth</param> /// <param name="stopAtString">Stop discovering if string is encounted</param> /// <param name="stopAtTuple">Stop discovering if tuple is encounted</param> /// <returns>Nesting depth or -1 on error</returns> private static int DiscoverDepth(Object src, int max, bool stopAtString, bool stopAtTuple) { int d = 0; if (max < 1) { throw new ArgumentException("invalid input sequence"); } if (stopAtTuple && src is PythonTuple) { return 0; } if (src is string || src is IEnumerable<char>) { return (stopAtString ? 0 : 1); } if (src is ndarray) { return ((ndarray)src).ndim; } if (src is IList<object>) { IList<object> list = (IList<object>)src; if (list.Count == 0) { return 1; } else { d = DiscoverDepth(list[0], max-1, stopAtString, stopAtTuple); return d+1; } } if (src is IEnumerable<object> && !(src is dtype)) { IEnumerable<object> seq = (IEnumerable<object>)src; object first; try { first = seq.First(); } catch (InvalidOperationException) { // Empty sequence return 1; } d = DiscoverDepth(first, max-1, stopAtString, stopAtTuple); return d+1; } // TODO: Not handling __array_struct__ attribute // TODO: Not handling __array_interface__ attribute return 0; } /// <summary> /// Recursively discovers the size of each dimension given an input object. /// </summary> /// <param name="src">Input object</param> /// <param name="numDim">Number of dimensions</param> /// <param name="dims">Uninitialized array of dimension sizes to be filled in</param> /// <param name="dimIdx">Current index into dims, incremented recursively</param> /// <param name="checkIt">Verify that src is consistent</param> private static void DiscoverDimensions(Object src, int numDim, Int64[] dims, int dimIdx, bool checkIt) { Int64 nLowest; if (src is ndarray) { ndarray arr = (ndarray)src; if (arr.ndim == 0) dims[dimIdx] = 0; else { Int64[] d = arr.Dims; for (int i = 0; i < numDim; i++) { dims[i + dimIdx] = d[i]; } } } else if (src is IList<object>) { IList<object> seq = (IList<object>)src; nLowest = 0; dims[dimIdx] = seq.Count(); if (numDim > 1) { foreach (Object o in seq) { DiscoverDimensions(o, numDim - 1, dims, dimIdx + 1, checkIt); if (checkIt && nLowest != 0 && nLowest != dims[dimIdx + 1]) { throw new ArgumentException("Inconsistent shape in sequence"); } if (dims[dimIdx + 1] > nLowest) nLowest = dims[dimIdx + 1]; } dims[dimIdx + 1] = nLowest; } } else if (src is IEnumerable<Object>) { IEnumerable<Object> seq = (IEnumerable<Object>)src; nLowest = 0; dims[dimIdx] = seq.Count(); if (numDim > 1) { foreach (Object o in seq) { DiscoverDimensions(o, numDim - 1, dims, dimIdx + 1, checkIt); if (checkIt && nLowest != 0 && nLowest != dims[dimIdx + 1]) { throw new ArgumentException("Inconsistent shape in sequence"); } if (dims[dimIdx + 1] > nLowest) nLowest = dims[dimIdx + 1]; } dims[dimIdx + 1] = nLowest; } } else { // Scalar condition. dims[dimIdx] = 1; } } private static int DiscoverItemsize(object s, int nd, int min) { if (s is ndarray) { ndarray a = (ndarray)s; return Math.Max(min, a.Dtype.ElementSize); } int n = (int)NpyUtil_Python.CallBuiltin(null, "len", s); if (nd == 0 || s is string || s is Bytes || s is MemoryView || s is PythonBuffer) { return Math.Max(min, n); } else { int result = min; for (int i = 0; i < n; i++) { object item = PythonOps.GetIndex(NpyUtil_Python.DefaultContext, s, i); result = DiscoverItemsize(item, nd - 1, result); } return result; } } public static ndarray Empty(long[] shape, dtype type = null, NpyDefs.NPY_ORDER order = NpyDefs.NPY_ORDER.NPY_CORDER) { if (type == null) { type = NpyCoreApi.DescrFromType(NpyDefs.DefaultType); } return NpyCoreApi.NewFromDescr(type, shape, null, (int)order, null); } public static ndarray Zeros(long[] shape, dtype type = null, NpyDefs.NPY_ORDER order = NpyDefs.NPY_ORDER.NPY_CORDER) { ndarray result = Empty(shape, type, order); NpyCoreApi.ZeroFill(result, IntPtr.Zero); if (type.IsObject) { // Object arrays are zero filled when created FillObjects(result, 0); } else { NpyCoreApi.ZeroFill(result, IntPtr.Zero); } return result; } /// <summary> /// Returns an allocated block of memory the same size as a single element of the given array /// and representing a 'zero' value. Usually this is all bytes set to zero, but for object /// arrays it's a pointer to a boxed zero. /// </summary> /// <param name="arr">Array to take the dtype from</param> /// <returns>Pointer to memory, must be free'd using NpyDataMem_FREE by the caller</returns> public static IntPtr Zero(ndarray arr) { if (arr.Dtype.HasNames && arr.Dtype.IsObject) { throw new ArgumentTypeException("Not supported for this data-type"); } using (ndarray zeroArr = Zeros(new long[] { 1 }, arr.Dtype)) { IntPtr zeroMem = NpyCoreApi.DupZeroElem(zeroArr); if (arr.Dtype.IsObject) { // The "zero value" is a GCHandle to a boxed zero. We need to duplicate the // GCHandle as it will be deallocated when the array goes away. GCHandle h = NpyCoreApi.GCHandleFromIntPtr(Marshal.ReadIntPtr(zeroMem)); h = NpyCoreApi.AllocGCHandle(h.Target); Marshal.WriteIntPtr(zeroMem, GCHandle.ToIntPtr(h)); } return zeroMem; } } public static ndarray Arange(CodeContext cntx, object start, object stop = null, object step = null, dtype d = null) { long[] dims; if (d == null) { d = NpyCoreApi.DescrFromType(NpyDefs.NPY_TYPES.NPY_LONG); d = FindArrayType(start, d); if (stop != null) { d = FindArrayType(stop, d); } if (step != null) { d = FindArrayType(step, d); } } if (step == null) { step = 1; } if (stop == null) { stop = start; start = 0; } object next; IntPtr len = IntPtr.Zero; try { len = CalcLength(cntx, start, stop, step, out next, NpyDefs.IsComplex(d.TypeNum)); } catch (OverflowException) { // Translate the error to make test_regression.py happy. throw new ArgumentException("Maximum allowed size exceeded"); } if (len.ToInt64() < 0) { dims = new long[] { 0 }; return NpyCoreApi.NewFromDescr(d, dims, null, 0, null); } dtype native; bool swap; if (!d.IsNativeByteOrder) { native = NpyCoreApi.DescrNewByteorder(d, '='); swap = true; } else { native = d; swap = false; } dims = new long[] { len.ToInt64() }; ndarray result = NpyCoreApi.NewFromDescr(native, dims, null, 0, null); result.SetItem(start, 0); if (len.ToInt64() > 1) { result.SetItem(next, d.ElementSize); } if (len.ToInt64() > 2) { NpyCoreApi.Fill(result); } if (swap) { NpyCoreApi.Byteswap(result, true); result.Dtype = d; } return result; } internal static IntPtr CeilToIntPtr(double d) { d = Math.Ceiling(d); if (IntPtr.Size == 4) { if (d > int.MaxValue || d < int.MinValue) { throw new OverflowException(); } return (IntPtr)(int)d; } else { if (d > long.MaxValue || d < long.MinValue) { throw new OverflowException(); } return (IntPtr)(long)d; } } internal static IntPtr CalcLength(CodeContext cntx, object start, object stop, object step, out object next, bool complex) { dynamic ops = PythonOps.ImportTop(cntx, "operator", 0); object n = ops.sub(stop, start); object val = ops.truediv(n, step); IntPtr result; if (complex && val is Complex) { Complex c = (Complex)val; result = CeilToIntPtr(Math.Min(c.Real, c.Imaginary)); } else { double d = Convert.ToDouble(val); result = CeilToIntPtr(d); } next = ops.add(start, step); return result; } internal static void FillObjects(ndarray arr, object o) { dtype d = arr.Dtype; if (d.IsObject) { if (d.HasNames) { foreach (string name in d.Names) { using (ndarray view = NpyCoreApi.GetField(arr, name)) { FillObjects(view, o); } } } else { NpyCoreApi.FillWithObject(arr, o); } } } internal static void AssignToArray(Object src, ndarray result) { IEnumerable<object> seq = src as IEnumerable<object>; if (seq == null) { throw new ArgumentException("assignment from non-sequence"); } if (result.ndim == 0) { throw new ArgumentException("assignment to 0-d array"); } AssignFromSeq(seq, result, 0, 0); } private static void AssignFromSeq(IEnumerable<Object> seq, ndarray result, int dim, long offset) { if (dim >= result.ndim) { throw new IronPython.Runtime.Exceptions.RuntimeException( String.Format("Source dimensions ({0}) exceeded target array dimensions ({1}).", dim, result.ndim)); } if (seq is ndarray && seq.GetType() != typeof(ndarray)) { // Convert to an array to ensure the dimensionality reduction // assumption works. ndarray array = NpyCoreApi.FromArray((ndarray)seq, null, NpyDefs.NPY_ENSUREARRAY); seq = (IEnumerable<object>)array; } if (seq.Count() != result.Dims[dim]) { throw new IronPython.Runtime.Exceptions.RuntimeException( "AssignFromSeq: sequence/array shape mismatch."); } long stride = result.Stride(dim); if (dim < result.ndim - 1) { // Sequence elements should be additional sequences seq.Iteri((o, i) => AssignFromSeq((IEnumerable<Object>)o, result, dim + 1, offset + stride * i)); } else { seq.Iteri((o, i) => result.Dtype.f.SetItem(o, offset + i*stride, result)); } } public static ndarray Concatenate(IEnumerable<object> arrays, int axis) { int i; try { arrays.First(); } catch (InvalidOperationException) { throw new ArgumentException("concatenation of zero-length sequence is impossible"); } ndarray[] mps = NpyUtil_ArgProcessing.ConvertToCommonType(arrays); int n = mps.Length; // TODO: Deal with subtypes if (axis >= NpyDefs.NPY_MAXDIMS) { // Flatten the arrays for (i = 0; i < n; i++) { mps[i] = mps[i].Ravel(NpyDefs.NPY_ORDER.NPY_CORDER); } } else if (axis != 0) { // Swap to make the axis 0 for (i = 0; i < n; i++) { mps[i] = NpyCoreApi.FromArray(mps[i].SwapAxes(axis, 0), null, NpyDefs.NPY_C_CONTIGUOUS); } } long[] dims = mps[0].Dims; if (dims.Length == 0) { throw new ArgumentException("0-d arrays can't be concatenated"); } long new_dim = dims[0]; for (i = 1; i < n; i++) { long[] dims2 = mps[i].Dims; if (dims.Length != dims2.Length) { throw new ArgumentException("arrays must have same number of dimensions"); } bool eq = Enumerable.Zip(dims.Skip(1), dims2.Skip(1), (a, b) => (a == b)).All(x => x); if (!eq) { throw new ArgumentException("array dimensions do not agree"); } new_dim += dims2[0]; } dims[0] = new_dim; ndarray result = NpyCoreApi.AllocArray(mps[0].Dtype, dims.Length, dims, false); if (!result.Dtype.IsObject) { // TODO: We really should be doing a memcpy here. unsafe { byte* dest = (byte*)result.UnsafeAddress.ToPointer(); foreach (ndarray a in mps) { long s = a.Size*a.Dtype.ElementSize; byte* src = (byte*)a.UnsafeAddress; while (s-- > 0) { *dest++ = *src++; } } } } else { // Do a high-level copy to get the references right. long j = 0; flatiter flat = result.Flat; foreach (ndarray a in mps) { long size = a.Size; flat[new Slice(j, j+size)] = a.flat; j += size; } } if (0 < axis && axis < NpyDefs.NPY_MAXDIMS || axis < 0) { return result.SwapAxes(axis, 0); } else { return result; } } public static ndarray InnerProduct(object o1, object o2) { dtype d = FindArrayType(o1, null); d = FindArrayType(o2, d); ndarray a1 = FromAny(o1, d, flags: NpyDefs.NPY_ALIGNED); ndarray a2 = FromAny(o2, d, flags: NpyDefs.NPY_ALIGNED); return NpyCoreApi.InnerProduct(a1, a2, d.TypeNum); } public static ndarray MatrixProduct(object o1, object o2) { dtype d = FindArrayType(o1, null); d = FindArrayType(o2, d); ndarray a1 = FromAny(o1, d, flags: NpyDefs.NPY_ALIGNED); ndarray a2 = FromAny(o2, d, flags: NpyDefs.NPY_ALIGNED); if (a1.ndim == 0) { return NpyArray.EnsureAnyArray(a1.item() * a2); } else if (a2.ndim == 0) { return NpyArray.EnsureAnyArray(a1 * a2.item()); } else { return NpyCoreApi.MatrixProduct(a1, a2, d.TypeNum); } } } }
using System; using System.Html; using System.Runtime.CompilerServices; using ScriptFX; [assembly: ScriptAssembly("test")] namespace BasicTests { [ScriptExtension("$global")] public static class GlobalMethodsClass { public static void Run() { } } public class App { public App() { AppHelper helper = new AppHelper(); helper.ShowHelp(); } public void Run() { } private void Initialize() { } void Dispose() { } } public delegate object MyHandler(int indexValue, string textValue); public enum AppFlags { AAA = 0, BBB = 1 } internal class AppHelper { internal void ShowHelp() { } } internal interface IApp { } internal class Bar { public virtual void DoStuff() { } public override string ToString() { return null; } internal void ExecuteHandler(MyHandler handler) { } } internal class Bar2 : Bar { } internal class BarEx : Bar2 { public void Setup() { MyMode mode = MyMode.Numeric; } public override void DoStuff() { Setup(); base.DoStuff(); MyData d = new MyData("a", "b"); d.string1 = d.string2; } internal void DoStuffInternal(int blah) { blah = blah + 2; } internal void DoStuffDelayed(int currentValue) { int numericValue = currentValue + 1; string stringValue = currentValue.ToString(); int value = 0; ExecuteHandler(delegate (int indexValue, string textValue) { ExecuteHandler(delegate (int indexValue, string textValue) { int value = 11; return indexValue; }); int value = 10; int value2 = 11; return numericValue + indexValue + stringValue + textValue + value; }); } internal int Stuff { get { return 0; } set { int x = value; } } internal int StuffProperty { get { ExecuteHandler(delegate (int indexValue, string textValue) { ExecuteHandler(delegate (int indexValue, string textValue) { int value = 11; return indexValue; }); int value = 10; int value2 = 11; return indexValue + textValue + value; }); return 0; } set { int numericValue = value + 1; string stringValue = value.ToString(); ExecuteHandler(delegate (int indexValue, string textValue) { ExecuteHandler(delegate (int indexValue, string textValue) { int value1 = 11; return indexValue; }); int value2 = 10; int value3 = 11; return numericValue + indexValue + stringValue + textValue + value + value3; }); } } } [ScriptName(PreserveName = true)] internal class BarCustom : Bar { } internal class BarCustom2 : BarCustom { public int Foo() { return 0; } [ScriptName(PreserveName = true)] public int Baz() { return 0; } [ScriptName(PreserveName = true)] private void Xyz() { } } internal enum MyMode { Alpha = 0, Numeric = 1 }; public class FooBehavior : Behavior { private int _intVal; private int _intVal2; int _intVal3; static string _strVal; event EventHandler ValueChanged; public FooBehavior(Element e, int i) : base(e, null) { _intVal = i; _intVal2 = i * 2; _intVal3 = i * 4; } public override void Dispose() { _intVal = 0; base.Dispose(); } void OnValueChanged() { } int this[string name] { get { return 0; } } string Property1 { get { return null; } } } internal class MaskTextBox : TextBox { public MaskTextBox(Element e) : base(e) { } private void OnValueChanged() { } void OnClicked() { } } internal class DerivedClass : BaseClass { private void DoStuffDerived() { } } internal class BaseClass : BaseBaseClass { private void DoStuffBase() { } } internal class BaseBaseClass { private void DoStuffBaseBase() { } } [ScriptObject] internal sealed class MyData { public string string1; public string string2; public MyData(string a, string b) { string1 = a; string2 = b; } } [ScriptObject] internal sealed class DataHolder { public string s1; public string s2; } internal class ABC { public ABC() { DataHolder d = new DataHolder(); } } }
// // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Text; using System.Threading; namespace IBM.Data.DB2 { /// <summary> /// /// </summary> /// <remarks>One connection pool per connectionstring</remarks> internal sealed class DB2ConnectionPool { private ArrayList openFreeConnections; // list of pooled connections sorted by age. First connection is present at index 'connectionsUsableOffset' private Queue openFreeMinimalAllocated; private int connectionsOpen; // total number of connections open (in pool, an in use by application) private int connectionsInUse; // total connection in use by application private int connectionsUsableOffset; // Offset to the first pooled connection in 'openFreeConnections' private Timer timer; public string databaseProductName; public string databaseVersion; public int majorVersion; public int minorVersion; private DB2ConnectionSettings connectionSettings; public DB2ConnectionPool(DB2ConnectionSettings connectionSettings) { this.connectionSettings = connectionSettings; openFreeConnections = new ArrayList(); } public DB2ConnectionSettings ConnectionSettings { get { return connectionSettings; } } public DB2OpenConnection GetOpenConnection(DB2Connection db2Conn) { DB2OpenConnection connection = null; lock (openFreeConnections.SyncRoot) { if ((connectionSettings.ConnectionPoolSizeMax > 0) && (connectionsOpen >= connectionSettings.ConnectionPoolSizeMax)) { throw new ArgumentException("Maximum connections reached for connectionstring"); } while (connectionsOpen > connectionsInUse) { connection = (DB2OpenConnection)openFreeConnections[openFreeConnections.Count - 1]; openFreeConnections.RemoveAt(openFreeConnections.Count - 1); // check if connection is dead int isDead; DB2Constants.RetCode sqlRet = (DB2Constants.RetCode)DB2CLIWrapper.SQLGetConnectAttr(connection.DBHandle, DB2Constants.SQL_ATTR_CONNECTION_DEAD, out isDead, 0, IntPtr.Zero); if (((sqlRet == DB2Constants.RetCode.SQL_SUCCESS_WITH_INFO) || (sqlRet == DB2Constants.RetCode.SQL_SUCCESS)) && (isDead == DB2Constants.SQL_CD_FALSE)) { connectionsInUse++; break; } else { connectionsOpen--; connection.Dispose(); connection = null; } } if (connectionsOpen == connectionsInUse) { if (timer != null) { timer.Dispose(); timer = null; } } } if (connection == null) { openFreeConnections.Clear(); connectionsUsableOffset = 0; connection = new DB2OpenConnection(connectionSettings, db2Conn); connectionsOpen++; connectionsInUse++; } return connection; } private void DisposeTimedoutConnections(object state) { lock (openFreeConnections.SyncRoot) { if (timer != null) { TimeSpan timeToDispose = TimeSpan.Zero; DB2OpenConnection connection; while (connectionsOpen > connectionsInUse) { connection = (DB2OpenConnection)openFreeConnections[connectionsUsableOffset]; timeToDispose = connection.PoolDisposalTime.Subtract(DateTime.Now); if ((timeToDispose.Ticks < 0) || // time to die (timeToDispose > connectionSettings.ConnectionLifeTime)) // messing with system clock { connection.Dispose(); openFreeConnections[connectionsUsableOffset] = null; connectionsOpen--; connectionsUsableOffset++; } else { break; } } if (connectionsOpen > connectionsInUse) { connection = (DB2OpenConnection)openFreeConnections[connectionsUsableOffset]; timer.Change(timeToDispose, new TimeSpan(-1)); } else { timer.Dispose(); timer = null; } } if ((connectionsUsableOffset > (openFreeConnections.Capacity / 2)) && (connectionsOpen > connectionsInUse)) { openFreeConnections.RemoveRange(0, connectionsUsableOffset); // cleanup once in a while connectionsUsableOffset = 0; } } } public void AddToFreeConnections(DB2OpenConnection connection) { lock (openFreeConnections.SyncRoot) { connection.PoolDisposalTime = DateTime.Now.Add(connectionSettings.ConnectionLifeTime); if (timer == null) { timer = new Timer(new TimerCallback(DisposeTimedoutConnections), null, connectionSettings.ConnectionLifeTime, new TimeSpan(-1)); } connectionsInUse--; openFreeConnections.Add(connection); } } public void OpenConnectionFinalized() { lock (openFreeConnections.SyncRoot) { connectionsOpen--; connectionsInUse--; } } /// <summary> /// Find a specific connection pool /// </summary> /// <param name="connectionString"></param> /// <returns></returns> static public DB2ConnectionPool FindConnectionPool(string connectionString) { return (DB2ConnectionPool)DB2Environment.Instance.connectionPools[connectionString]; } /// <summary> /// Get a connection pool. If it doesn't exist yet, create it /// </summary> /// <param name="connectionSettings"></param> /// <returns></returns> static public DB2ConnectionPool GetConnectionPool(DB2ConnectionSettings connectionSettings) { DB2Environment environment = DB2Environment.Instance; lock (environment.connectionPools.SyncRoot) { DB2ConnectionPool pool = (DB2ConnectionPool)environment.connectionPools[connectionSettings.ConnectionString]; if (pool == null) { pool = new DB2ConnectionPool(connectionSettings); environment.connectionPools.Add(connectionSettings.ConnectionString, pool); } return pool; } } } }
using System; using System.Collections; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Cms { /** * containing class for an CMS Authenticated Data object */ public class CmsAuthenticatedData { internal RecipientInformationStore recipientInfoStore; internal ContentInfo contentInfo; private AlgorithmIdentifier macAlg; private Asn1Set authAttrs; private Asn1Set unauthAttrs; private byte[] mac; public CmsAuthenticatedData( byte[] authData) : base(CmsUtilities.ReadContentInfo(authData)) { } public CmsAuthenticatedData( Stream authData) : base(CmsUtilities.ReadContentInfo(authData)) { } public CmsAuthenticatedData( ContentInfo contentInfo) { this.contentInfo = contentInfo; AuthenticatedData authData = AuthenticatedData.GetInstance(contentInfo.Content); // // read the encapsulated content info // ContentInfo encInfo = authData.GetEncapsulatedContentInfo(); this.macAlg = authData.GetMacAlgorithm(); this.mac = authData.GetMac().GetOctets(); // // load the RecipientInfoStore // Asn1Set s = authData.GetRecipientInfos(); IList infos = new ArrayList(); byte[] contentOctets = Asn1OctetString.GetInstance(encInfo.Content).GetOctets(); for (int i = 0; i != s.Count; i++) { RecipientInfo info = RecipientInfo.GetInstance(s[i]); MemoryStream contentStream = new MemoryStream(contentOctets, false); object type = info.Info; if (type is KeyTransRecipientInfo) { infos.Add(new KeyTransRecipientInformation( (KeyTransRecipientInfo)type, null, macAlg, contentStream)); } else if (type is KEKRecipientInfo) { infos.Add(new KekRecipientInformation( (KekRecipientInfo)type, null, macAlg, contentStream)); } else if (type is KeyAgreeRecipientInfo) { infos.Add(new KeyAgreeRecipientInformation( (KeyAgreeRecipientInfo)type, null, macAlg, contentStream)); } else if (type is PasswordRecipientInfo) { infos.Add(new PasswordRecipientInformation( (PasswordRecipientInfo)type, null, macAlg, contentStream)); } } this.authAttrs = authData.GetAuthAttrs(); this.recipientInfoStore = new RecipientInformationStore(infos); this.unauthAttrs = authData.GetUnauthAttrs(); } public byte[] GetMac() { return Arrays.Clone(mac); } // private byte[] encodeObj( // Asn1Encodable obj) // { // return obj == null ? null : obj.GetEncoded(); // } public AlgorithmIdentifier MacAlgorithmID { get { return macAlg; } } /** * return the object identifier for the content MAC algorithm. */ public string MacAlgOid { get { return macAlg.ObjectID.Id; } } // /** // * return the ASN.1 encoded MAC algorithm parameters, or null if // * there aren't any. // */ // public byte[] getMacAlgParams() // { // try // { // return encodeObj(macAlg.getParameters()); // } // catch (Exception e) // { // throw new RuntimeException("exception getting encryption parameters " + e); // } // } // /** // * Return an AlgorithmParameters object giving the MAC parameters // * used to digest the message content. // * // * @param provider the provider to generate the parameters for. // * @return the parameters object, null if there is not one. // * @throws org.bouncycastle.cms.CMSException if the algorithm cannot be found, or the parameters can't be parsed. // * @throws java.security.NoSuchProviderException if the provider cannot be found. // */ // public AlgorithmParameters getMacAlgorithmParameters( // String provider) // throws CMSException, NoSuchProviderException // { // return getMacAlgorithmParameters(CMSUtils.getProvider(provider)); // } // // /** // * Return an AlgorithmParameters object giving the MAC parameters // * used to digest the message content. // * // * @param provider the provider to generate the parameters for. // * @return the parameters object, null if there is not one. // * @throws org.bouncycastle.cms.CMSException if the algorithm cannot be found, or the parameters can't be parsed. // */ // public AlgorithmParameters getMacAlgorithmParameters( // Provider provider) // throws CMSException // { // return CMSEnvelopedHelper.INSTANCE.getEncryptionAlgorithmParameters(getMacAlgOID(), getMacAlgParams(), provider); // } /** * return a store of the intended recipients for this message */ public RecipientInformationStore GetRecipientInfos() { return recipientInfoStore; } /** * return the ContentInfo */ public ContentInfo ContentInfo { get { return contentInfo; } } /** * return a table of the digested attributes indexed by * the OID of the attribute. */ public Asn1.Cms.AttributeTable GetAuthAttrs() { if (authAttrs == null) return null; return new Asn1.Cms.AttributeTable(authAttrs); } /** * return a table of the undigested attributes indexed by * the OID of the attribute. */ public Asn1.Cms.AttributeTable GetUnauthAttrs() { if (unauthAttrs == null) return null; return new Asn1.Cms.AttributeTable(unauthAttrs); } /** * return the ASN.1 encoded representation of this object. */ public byte[] GetEncoded() { return contentInfo.GetEncoded(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Controls.Utils; using Avalonia.LogicalTree; using Avalonia.Markup.Xaml; using Avalonia.Styling; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Controls.UnitTests { public class TabControlTests { [Fact] public void First_Tab_Should_Be_Selected_By_Default() { TabItem selected; var target = new TabControl { Template = TabControlTemplate(), Items = new[] { (selected = new TabItem { Name = "first", Content = "foo", }), new TabItem { Name = "second", Content = "bar", }, } }; target.ApplyTemplate(); Assert.Equal(0, target.SelectedIndex); Assert.Equal(selected, target.SelectedItem); } [Fact] public void Pre_Selecting_TabItem_Should_Set_SelectedContent_After_It_Was_Added() { var target = new TabControl { Template = TabControlTemplate(), }; const string secondContent = "Second"; var items = new AvaloniaList<object> { new TabItem { Header = "First"}, new TabItem { Header = "Second", Content = secondContent, IsSelected = true } }; target.Items = items; ApplyTemplate(target); Assert.Equal(secondContent, target.SelectedContent); } [Fact] public void Logical_Children_Should_Be_TabItems() { var items = new[] { new TabItem { Content = "foo" }, new TabItem { Content = "bar" }, }; var target = new TabControl { Template = TabControlTemplate(), Items = items, }; Assert.Equal(items, target.GetLogicalChildren()); target.ApplyTemplate(); Assert.Equal(items, target.GetLogicalChildren()); } [Fact] public void Removal_Should_Set_First_Tab() { var collection = new ObservableCollection<TabItem>() { new TabItem { Name = "first", Content = "foo", }, new TabItem { Name = "second", Content = "bar", }, new TabItem { Name = "3rd", Content = "barf", }, }; var target = new TabControl { Template = TabControlTemplate(), Items = collection, }; Prepare(target); target.SelectedItem = collection[1]; Assert.Same(collection[1], target.SelectedItem); Assert.Equal(collection[1].Content, target.SelectedContent); collection.RemoveAt(1); Assert.Same(collection[0], target.SelectedItem); Assert.Equal(collection[0].Content, target.SelectedContent); } [Fact] public void Removal_Should_Set_New_Item0_When_Item0_Selected() { var collection = new ObservableCollection<TabItem>() { new TabItem { Name = "first", Content = "foo", }, new TabItem { Name = "second", Content = "bar", }, new TabItem { Name = "3rd", Content = "barf", }, }; var target = new TabControl { Template = TabControlTemplate(), Items = collection, }; Prepare(target); target.SelectedItem = collection[0]; Assert.Same(collection[0], target.SelectedItem); Assert.Equal(collection[0].Content, target.SelectedContent); collection.RemoveAt(0); Assert.Same(collection[0], target.SelectedItem); Assert.Equal(collection[0].Content, target.SelectedContent); } [Fact] public void Removal_Should_Set_New_Item0_When_Item0_Selected_With_DataTemplate() { using var app = UnitTestApplication.Start(TestServices.StyledWindow); var collection = new ObservableCollection<Item>() { new Item("first"), new Item("second"), new Item("3rd"), }; var target = new TabControl { Template = TabControlTemplate(), Items = collection, }; Prepare(target); target.SelectedItem = collection[0]; Assert.Same(collection[0], target.SelectedItem); Assert.Equal(collection[0], target.SelectedContent); collection.RemoveAt(0); Assert.Same(collection[0], target.SelectedItem); Assert.Equal(collection[0], target.SelectedContent); } [Fact] public void TabItem_Templates_Should_Be_Set_Before_TabItem_ApplyTemplate() { var collection = new[] { new TabItem { Name = "first", Content = "foo", }, new TabItem { Name = "second", Content = "bar", }, new TabItem { Name = "3rd", Content = "barf", }, }; var template = new FuncControlTemplate<TabItem>((x, __) => new Decorator()); using (UnitTestApplication.Start(TestServices.RealStyler)) { var root = new TestRoot { Styles = { new Style(x => x.OfType<TabItem>()) { Setters = { new Setter(TemplatedControl.TemplateProperty, template) } } }, Child = new TabControl { Template = TabControlTemplate(), Items = collection, } }; } Assert.Same(collection[0].Template, template); Assert.Same(collection[1].Template, template); Assert.Same(collection[2].Template, template); } [Fact] public void DataContexts_Should_Be_Correctly_Set() { var items = new object[] { "Foo", new Item("Bar"), new TextBlock { Text = "Baz" }, new TabItem { Content = "Qux" }, new TabItem { Content = new TextBlock { Text = "Bob" } } }; var target = new TabControl { Template = TabControlTemplate(), DataContext = "Base", DataTemplates = { new FuncDataTemplate<Item>((x, __) => new Button { Content = x }) }, Items = items, }; ApplyTemplate(target); ((ContentPresenter)target.ContentPart).UpdateChild(); var dataContext = ((TextBlock)target.ContentPart.Child).DataContext; Assert.Equal(items[0], dataContext); target.SelectedIndex = 1; ((ContentPresenter)target.ContentPart).UpdateChild(); dataContext = ((Button)target.ContentPart.Child).DataContext; Assert.Equal(items[1], dataContext); target.SelectedIndex = 2; ((ContentPresenter)target.ContentPart).UpdateChild(); dataContext = ((TextBlock)target.ContentPart.Child).DataContext; Assert.Equal("Base", dataContext); target.SelectedIndex = 3; ((ContentPresenter)target.ContentPart).UpdateChild(); dataContext = ((TextBlock)target.ContentPart.Child).DataContext; Assert.Equal("Qux", dataContext); target.SelectedIndex = 4; ((ContentPresenter)target.ContentPart).UpdateChild(); dataContext = target.ContentPart.DataContext; Assert.Equal("Base", dataContext); } /// <summary> /// Non-headered control items should result in TabItems with empty header. /// </summary> /// <remarks> /// If a TabControl is created with non IHeadered controls as its items, don't try to /// display the control in the header: if the control is part of the header then /// *that* control would also end up in the content region, resulting in dual-parentage /// breakage. /// </remarks> [Fact] public void Non_IHeadered_Control_Items_Should_Be_Ignored() { var items = new[] { new TextBlock { Text = "foo" }, new TextBlock { Text = "bar" }, }; var target = new TabControl { Template = TabControlTemplate(), Items = items, }; ApplyTemplate(target); var logicalChildren = target.ItemsPresenterPart.Panel.GetLogicalChildren(); var result = logicalChildren .OfType<TabItem>() .Select(x => x.Header) .ToList(); Assert.Equal(new object[] { null, null }, result); } [Fact] public void Should_Handle_Changing_To_TabItem_With_Null_Content() { TabControl target = new TabControl { Template = TabControlTemplate(), Items = new[] { new TabItem { Header = "Foo" }, new TabItem { Header = "Foo", Content = new Decorator() }, new TabItem { Header = "Baz" }, }, }; ApplyTemplate(target); target.SelectedIndex = 2; var page = (TabItem)target.SelectedItem; Assert.Null(page.Content); } [Fact] public void DataTemplate_Created_Content_Should_Be_Logical_Child_After_ApplyTemplate() { TabControl target = new TabControl { Template = TabControlTemplate(), ContentTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Tag = "bar", Text = x }), Items = new[] { "Foo" }, }; ApplyTemplate(target); ((ContentPresenter)target.ContentPart).UpdateChild(); var content = Assert.IsType<TextBlock>(target.ContentPart.Child); Assert.Equal("bar", content.Tag); Assert.Same(target, content.GetLogicalParent()); Assert.Single(target.GetLogicalChildren(), content); } [Fact] public void Should_Not_Propagate_DataContext_To_TabItem_Content() { var dataContext = "DataContext"; var tabItem = new TabItem(); var target = new TabControl { Template = TabControlTemplate(), DataContext = dataContext, Items = new AvaloniaList<object> { tabItem } }; ApplyTemplate(target); Assert.NotEqual(dataContext, tabItem.Content); } [Fact] public void Can_Have_Empty_Tab_Control() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var xaml = @" <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'> <TabControl Name='tabs' Items='{Binding Tabs}'/> </Window>"; var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml); var tabControl = window.FindControl<TabControl>("tabs"); tabControl.DataContext = new { Tabs = new List<string>() }; window.ApplyTemplate(); Assert.Equal(0, tabControl.Items.Count()); } } private IControlTemplate TabControlTemplate() { return new FuncControlTemplate<TabControl>((parent, scope) => new StackPanel { Children = { new ItemsPresenter { Name = "PART_ItemsPresenter", [!TabStrip.ItemsProperty] = parent[!TabControl.ItemsProperty], [!TabStrip.ItemTemplateProperty] = parent[!TabControl.ItemTemplateProperty], }.RegisterInNameScope(scope), new ContentPresenter { Name = "PART_SelectedContentHost", [!ContentPresenter.ContentProperty] = parent[!TabControl.SelectedContentProperty], [!ContentPresenter.ContentTemplateProperty] = parent[!TabControl.SelectedContentTemplateProperty], }.RegisterInNameScope(scope) } }); } private IControlTemplate TabItemTemplate() { return new FuncControlTemplate<TabItem>((parent, scope) => new ContentPresenter { Name = "PART_ContentPresenter", [!ContentPresenter.ContentProperty] = parent[!TabItem.HeaderProperty], [!ContentPresenter.ContentTemplateProperty] = parent[!TabItem.HeaderTemplateProperty] }.RegisterInNameScope(scope)); } private void Prepare(TabControl target) { ApplyTemplate(target); target.Measure(Size.Infinity); target.Arrange(new Rect(target.DesiredSize)); } private void ApplyTemplate(TabControl target) { target.ApplyTemplate(); target.Presenter.ApplyTemplate(); foreach (var tabItem in target.GetLogicalChildren().OfType<TabItem>()) { tabItem.Template = TabItemTemplate(); tabItem.ApplyTemplate(); ((ContentPresenter)tabItem.Presenter).UpdateChild(); } target.ContentPart.ApplyTemplate(); } private class Item { public Item(string value) { Value = value; } public string Value { get; } } } }
// 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 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.Cloud.Compute.V1 { /// <summary>Settings for <see cref="ImageFamilyViewsClient"/> instances.</summary> public sealed partial class ImageFamilyViewsSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ImageFamilyViewsSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ImageFamilyViewsSettings"/>.</returns> public static ImageFamilyViewsSettings GetDefault() => new ImageFamilyViewsSettings(); /// <summary>Constructs a new <see cref="ImageFamilyViewsSettings"/> object with default settings.</summary> public ImageFamilyViewsSettings() { } private ImageFamilyViewsSettings(ImageFamilyViewsSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetSettings = existing.GetSettings; OnCopy(existing); } partial void OnCopy(ImageFamilyViewsSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>ImageFamilyViewsClient.Get</c> /// and <c>ImageFamilyViewsClient.GetAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 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.DeadlineExceeded"/>, /// <see cref="grpccore::StatusCode.Unavailable"/>. /// </description> /// </item> /// <item><description>Timeout: 600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ImageFamilyViewsSettings"/> object.</returns> public ImageFamilyViewsSettings Clone() => new ImageFamilyViewsSettings(this); } /// <summary> /// Builder class for <see cref="ImageFamilyViewsClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class ImageFamilyViewsClientBuilder : gaxgrpc::ClientBuilderBase<ImageFamilyViewsClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ImageFamilyViewsSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ImageFamilyViewsClientBuilder() { UseJwtAccessWithScopes = ImageFamilyViewsClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ImageFamilyViewsClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ImageFamilyViewsClient> task); /// <summary>Builds the resulting client.</summary> public override ImageFamilyViewsClient Build() { ImageFamilyViewsClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ImageFamilyViewsClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ImageFamilyViewsClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ImageFamilyViewsClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ImageFamilyViewsClient.Create(callInvoker, Settings); } private async stt::Task<ImageFamilyViewsClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ImageFamilyViewsClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ImageFamilyViewsClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ImageFamilyViewsClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ImageFamilyViewsClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => ComputeRestAdapter.ComputeAdapter; } /// <summary>ImageFamilyViews client wrapper, for convenient use.</summary> /// <remarks> /// The ImageFamilyViews API. /// </remarks> public abstract partial class ImageFamilyViewsClient { /// <summary> /// The default endpoint for the ImageFamilyViews service, which is a host of "compute.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "compute.googleapis.com:443"; /// <summary>The default ImageFamilyViews scopes.</summary> /// <remarks> /// The default ImageFamilyViews scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/compute.readonly</description></item> /// <item><description>https://www.googleapis.com/auth/compute</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", }); 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="ImageFamilyViewsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ImageFamilyViewsClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ImageFamilyViewsClient"/>.</returns> public static stt::Task<ImageFamilyViewsClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ImageFamilyViewsClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ImageFamilyViewsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ImageFamilyViewsClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ImageFamilyViewsClient"/>.</returns> public static ImageFamilyViewsClient Create() => new ImageFamilyViewsClientBuilder().Build(); /// <summary> /// Creates a <see cref="ImageFamilyViewsClient"/> 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="ImageFamilyViewsSettings"/>.</param> /// <returns>The created <see cref="ImageFamilyViewsClient"/>.</returns> internal static ImageFamilyViewsClient Create(grpccore::CallInvoker callInvoker, ImageFamilyViewsSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ImageFamilyViews.ImageFamilyViewsClient grpcClient = new ImageFamilyViews.ImageFamilyViewsClient(callInvoker); return new ImageFamilyViewsClientImpl(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 ImageFamilyViews client</summary> public virtual ImageFamilyViews.ImageFamilyViewsClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the latest image that is part of an image family, is not deprecated and is rolled out in the specified zone. /// </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 ImageFamilyView Get(GetImageFamilyViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the latest image that is part of an image family, is not deprecated and is rolled out in the specified zone. /// </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<ImageFamilyView> GetAsync(GetImageFamilyViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the latest image that is part of an image family, is not deprecated and is rolled out in the specified zone. /// </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<ImageFamilyView> GetAsync(GetImageFamilyViewRequest request, st::CancellationToken cancellationToken) => GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the latest image that is part of an image family, is not deprecated and is rolled out in the specified zone. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="zone"> /// The name of the zone for this request. /// </param> /// <param name="family"> /// Name of the image family to search for. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ImageFamilyView Get(string project, string zone, string family, gaxgrpc::CallSettings callSettings = null) => Get(new GetImageFamilyViewRequest { Family = gax::GaxPreconditions.CheckNotNullOrEmpty(family, nameof(family)), Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)), }, callSettings); /// <summary> /// Returns the latest image that is part of an image family, is not deprecated and is rolled out in the specified zone. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="zone"> /// The name of the zone for this request. /// </param> /// <param name="family"> /// Name of the image family to search for. /// </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<ImageFamilyView> GetAsync(string project, string zone, string family, gaxgrpc::CallSettings callSettings = null) => GetAsync(new GetImageFamilyViewRequest { Family = gax::GaxPreconditions.CheckNotNullOrEmpty(family, nameof(family)), Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)), Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)), }, callSettings); /// <summary> /// Returns the latest image that is part of an image family, is not deprecated and is rolled out in the specified zone. /// </summary> /// <param name="project"> /// Project ID for this request. /// </param> /// <param name="zone"> /// The name of the zone for this request. /// </param> /// <param name="family"> /// Name of the image family to search for. /// </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<ImageFamilyView> GetAsync(string project, string zone, string family, st::CancellationToken cancellationToken) => GetAsync(project, zone, family, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ImageFamilyViews client wrapper implementation, for convenient use.</summary> /// <remarks> /// The ImageFamilyViews API. /// </remarks> public sealed partial class ImageFamilyViewsClientImpl : ImageFamilyViewsClient { private readonly gaxgrpc::ApiCall<GetImageFamilyViewRequest, ImageFamilyView> _callGet; /// <summary> /// Constructs a client wrapper for the ImageFamilyViews service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ImageFamilyViewsSettings"/> used within this client.</param> public ImageFamilyViewsClientImpl(ImageFamilyViews.ImageFamilyViewsClient grpcClient, ImageFamilyViewsSettings settings) { GrpcClient = grpcClient; ImageFamilyViewsSettings effectiveSettings = settings ?? ImageFamilyViewsSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGet = clientHelper.BuildApiCall<GetImageFamilyViewRequest, ImageFamilyView>(grpcClient.GetAsync, grpcClient.Get, effectiveSettings.GetSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("zone", request => request.Zone).WithGoogleRequestParam("family", request => request.Family); Modify_ApiCall(ref _callGet); Modify_GetApiCall(ref _callGet); 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_GetApiCall(ref gaxgrpc::ApiCall<GetImageFamilyViewRequest, ImageFamilyView> call); partial void OnConstruction(ImageFamilyViews.ImageFamilyViewsClient grpcClient, ImageFamilyViewsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ImageFamilyViews client</summary> public override ImageFamilyViews.ImageFamilyViewsClient GrpcClient { get; } partial void Modify_GetImageFamilyViewRequest(ref GetImageFamilyViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the latest image that is part of an image family, is not deprecated and is rolled out in the specified zone. /// </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 ImageFamilyView Get(GetImageFamilyViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetImageFamilyViewRequest(ref request, ref callSettings); return _callGet.Sync(request, callSettings); } /// <summary> /// Returns the latest image that is part of an image family, is not deprecated and is rolled out in the specified zone. /// </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<ImageFamilyView> GetAsync(GetImageFamilyViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetImageFamilyViewRequest(ref request, ref callSettings); return _callGet.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Text; using SubSonic.DataProviders; using SubSonic.Extensions; using System.Linq.Expressions; using SubSonic.Schema; using SubSonic.Repository; using System.Data.Common; using SubSonic.SqlGeneration.Schema; namespace Solution.DataAccess.DataModel { /// <summary> /// A class which represents the Shifts table in the HKHR Database. /// </summary> public partial class Shifts: IActiveRecord { #region Built-in testing static TestRepository<Shifts> _testRepo; static void SetTestRepo(){ _testRepo = _testRepo ?? new TestRepository<Shifts>(new Solution.DataAccess.DataModel.HKHRDB()); } public static void ResetTestRepo(){ _testRepo = null; SetTestRepo(); } public static void Setup(List<Shifts> testlist){ SetTestRepo(); foreach (var item in testlist) { _testRepo._items.Add(item); } } public static void Setup(Shifts item) { SetTestRepo(); _testRepo._items.Add(item); } public static void Setup(int testItems) { SetTestRepo(); for(int i=0;i<testItems;i++){ Shifts item=new Shifts(); _testRepo._items.Add(item); } } public bool TestMode = false; #endregion IRepository<Shifts> _repo; ITable tbl; bool _isNew; public bool IsNew(){ return _isNew; } public void SetIsLoaded(bool isLoaded){ _isLoaded=isLoaded; if(isLoaded) OnLoaded(); } public void SetIsNew(bool isNew){ _isNew=isNew; } bool _isLoaded; public bool IsLoaded(){ return _isLoaded; } List<IColumn> _dirtyColumns; public bool IsDirty(){ return _dirtyColumns.Count>0; } public List<IColumn> GetDirtyColumns (){ return _dirtyColumns; } Solution.DataAccess.DataModel.HKHRDB _db; public Shifts(string connectionString, string providerName) { _db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); Init(); } void Init(){ TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); _dirtyColumns=new List<IColumn>(); if(TestMode){ Shifts.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<Shifts>(_db); } tbl=_repo.GetTable(); SetIsNew(true); OnCreated(); } public Shifts(){ _db=new Solution.DataAccess.DataModel.HKHRDB(); Init(); } public void ORMapping(IDataRecord dataRecord) { IReadRecord readRecord = SqlReadRecord.GetIReadRecord(); readRecord.DataRecord = dataRecord; Id = readRecord.get_int("Id",null); SHIFT_ID = readRecord.get_string("SHIFT_ID",null); SHIFT_NAME = readRecord.get_string("SHIFT_NAME",null); DEPART_ID = readRecord.get_string("DEPART_ID",null); SHIFT_KIND = readRecord.get_int("SHIFT_KIND",null); WORK_HRS = readRecord.get_decimal("WORK_HRS",null); NEED_HRS = readRecord.get_decimal("NEED_HRS",null); IS_DEFAULT = readRecord.get_short("IS_DEFAULT",null); RULE_ID = readRecord.get_string("RULE_ID",null); CLASS_ID = readRecord.get_int("CLASS_ID",null); NEED_SIGN_COUNT = readRecord.get_int("NEED_SIGN_COUNT",null); IS_COMMON = readRecord.get_short("IS_COMMON",null); AHEAD1 = readRecord.get_int("AHEAD1",null); IN1 = readRecord.get_datetime("IN1",null); NEEDIN1 = readRecord.get_short("NEEDIN1",null); BOVERTIME1 = readRecord.get_short("BOVERTIME1",null); OUT1 = readRecord.get_datetime("OUT1",null); DELAY1 = readRecord.get_short("DELAY1",null); NEEDOUT1 = readRecord.get_short("NEEDOUT1",null); EOVERTIME1 = readRecord.get_short("EOVERTIME1",null); REST1 = readRecord.get_short("REST1",null); REST_BEGIN1 = readRecord.get_datetime("REST_BEGIN1",null); BREAK1 = readRecord.get_short("BREAK1",null); OT1 = readRecord.get_short("OT1",null); EXT1 = readRecord.get_short("EXT1",null); CANOT1 = readRecord.get_short("CANOT1",null); OT_REST1 = readRecord.get_int("OT_REST1",null); OT_REST_BEGIN1 = readRecord.get_datetime("OT_REST_BEGIN1",null); BASICHRS1 = readRecord.get_decimal("BASICHRS1",null); NEEDHRS1 = readRecord.get_decimal("NEEDHRS1",null); DAY1 = readRecord.get_decimal("DAY1",null); AHEAD2 = readRecord.get_int("AHEAD2",null); IN2 = readRecord.get_datetime("IN2",null); NEEDIN2 = readRecord.get_short("NEEDIN2",null); BOVERTIME2 = readRecord.get_short("BOVERTIME2",null); OUT2 = readRecord.get_datetime("OUT2",null); DELAY2 = readRecord.get_short("DELAY2",null); NEEDOUT2 = readRecord.get_short("NEEDOUT2",null); EOVERTIME2 = readRecord.get_short("EOVERTIME2",null); REST2 = readRecord.get_short("REST2",null); REST_BEGIN2 = readRecord.get_datetime("REST_BEGIN2",null); BREAK2 = readRecord.get_short("BREAK2",null); OT2 = readRecord.get_short("OT2",null); EXT2 = readRecord.get_short("EXT2",null); CANOT2 = readRecord.get_short("CANOT2",null); OT_REST2 = readRecord.get_int("OT_REST2",null); OT_REST_BEGIN2 = readRecord.get_datetime("OT_REST_BEGIN2",null); BASICHRS2 = readRecord.get_decimal("BASICHRS2",null); NEEDHRS2 = readRecord.get_decimal("NEEDHRS2",null); DAY2 = readRecord.get_decimal("DAY2",null); AHEAD3 = readRecord.get_int("AHEAD3",null); IN3 = readRecord.get_datetime("IN3",null); NEEDIN3 = readRecord.get_short("NEEDIN3",null); BOVERTIME3 = readRecord.get_short("BOVERTIME3",null); OUT3 = readRecord.get_datetime("OUT3",null); DELAY3 = readRecord.get_short("DELAY3",null); NEEDOUT3 = readRecord.get_short("NEEDOUT3",null); EOVERTIME3 = readRecord.get_short("EOVERTIME3",null); REST3 = readRecord.get_short("REST3",null); REST_BEGIN3 = readRecord.get_datetime("REST_BEGIN3",null); BREAK3 = readRecord.get_short("BREAK3",null); OT3 = readRecord.get_short("OT3",null); EXT3 = readRecord.get_short("EXT3",null); CANOT3 = readRecord.get_short("CANOT3",null); OT_REST3 = readRecord.get_int("OT_REST3",null); OT_REST_BEGIN3 = readRecord.get_datetime("OT_REST_BEGIN3",null); BASICHRS3 = readRecord.get_decimal("BASICHRS3",null); NEEDHRS3 = readRecord.get_decimal("NEEDHRS3",null); DAY3 = readRecord.get_decimal("DAY3",null); AHEAD4 = readRecord.get_int("AHEAD4",null); IN4 = readRecord.get_datetime("IN4",null); NEEDIN4 = readRecord.get_short("NEEDIN4",null); BOVERTIME4 = readRecord.get_short("BOVERTIME4",null); OUT4 = readRecord.get_datetime("OUT4",null); DELAY4 = readRecord.get_short("DELAY4",null); NEEDOUT4 = readRecord.get_short("NEEDOUT4",null); EOVERTIME4 = readRecord.get_short("EOVERTIME4",null); REST4 = readRecord.get_short("REST4",null); REST_BEGIN4 = readRecord.get_datetime("REST_BEGIN4",null); BREAK4 = readRecord.get_short("BREAK4",null); OT4 = readRecord.get_short("OT4",null); EXT4 = readRecord.get_short("EXT4",null); CANOT4 = readRecord.get_short("CANOT4",null); OT_REST4 = readRecord.get_int("OT_REST4",null); OT_REST_BEGIN4 = readRecord.get_datetime("OT_REST_BEGIN4",null); BASICHRS4 = readRecord.get_decimal("BASICHRS4",null); NEEDHRS4 = readRecord.get_decimal("NEEDHRS4",null); DAY4 = readRecord.get_decimal("DAY4",null); } partial void OnCreated(); partial void OnLoaded(); partial void OnSaved(); partial void OnChanged(); public IList<IColumn> Columns{ get{ return tbl.Columns; } } public Shifts(Expression<Func<Shifts, bool>> expression):this() { SetIsLoaded(_repo.Load(this,expression)); } internal static IRepository<Shifts> GetRepo(string connectionString, string providerName){ Solution.DataAccess.DataModel.HKHRDB db; if(String.IsNullOrEmpty(connectionString)){ db=new Solution.DataAccess.DataModel.HKHRDB(); }else{ db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); } IRepository<Shifts> _repo; if(db.TestMode){ Shifts.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<Shifts>(db); } return _repo; } internal static IRepository<Shifts> GetRepo(){ return GetRepo("",""); } public static Shifts SingleOrDefault(Expression<Func<Shifts, bool>> expression) { var repo = GetRepo(); var results=repo.Find(expression); Shifts single=null; if(results.Count() > 0){ single=results.ToList()[0]; single.OnLoaded(); single.SetIsLoaded(true); single.SetIsNew(false); } return single; } public static Shifts SingleOrDefault(Expression<Func<Shifts, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); var results=repo.Find(expression); Shifts single=null; if(results.Count() > 0){ single=results.ToList()[0]; } return single; } public static bool Exists(Expression<Func<Shifts, bool>> expression,string connectionString, string providerName) { return All(connectionString,providerName).Any(expression); } public static bool Exists(Expression<Func<Shifts, bool>> expression) { return All().Any(expression); } public static IList<Shifts> Find(Expression<Func<Shifts, bool>> expression) { var repo = GetRepo(); return repo.Find(expression).ToList(); } public static IList<Shifts> Find(Expression<Func<Shifts, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); return repo.Find(expression).ToList(); } public static IQueryable<Shifts> All(string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetAll(); } public static IQueryable<Shifts> All() { return GetRepo().GetAll(); } public static PagedList<Shifts> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<Shifts> GetPaged(string sortBy, int pageIndex, int pageSize) { return GetRepo().GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<Shifts> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); } public static PagedList<Shifts> GetPaged(int pageIndex, int pageSize) { return GetRepo().GetPaged(pageIndex, pageSize); } public string KeyName() { return "SHIFT_ID"; } public object KeyValue() { return this.SHIFT_ID; } public void SetKeyValue(object value) { if (value != null && value!=DBNull.Value) { var settable = value.ChangeTypeTo<string>(); this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); } } public override string ToString(){ var sb = new StringBuilder(); sb.Append("Id=" + Id + "; "); sb.Append("SHIFT_ID=" + SHIFT_ID + "; "); sb.Append("SHIFT_NAME=" + SHIFT_NAME + "; "); sb.Append("DEPART_ID=" + DEPART_ID + "; "); sb.Append("SHIFT_KIND=" + SHIFT_KIND + "; "); sb.Append("WORK_HRS=" + WORK_HRS + "; "); sb.Append("NEED_HRS=" + NEED_HRS + "; "); sb.Append("IS_DEFAULT=" + IS_DEFAULT + "; "); sb.Append("RULE_ID=" + RULE_ID + "; "); sb.Append("CLASS_ID=" + CLASS_ID + "; "); sb.Append("NEED_SIGN_COUNT=" + NEED_SIGN_COUNT + "; "); sb.Append("IS_COMMON=" + IS_COMMON + "; "); sb.Append("AHEAD1=" + AHEAD1 + "; "); sb.Append("IN1=" + IN1 + "; "); sb.Append("NEEDIN1=" + NEEDIN1 + "; "); sb.Append("BOVERTIME1=" + BOVERTIME1 + "; "); sb.Append("OUT1=" + OUT1 + "; "); sb.Append("DELAY1=" + DELAY1 + "; "); sb.Append("NEEDOUT1=" + NEEDOUT1 + "; "); sb.Append("EOVERTIME1=" + EOVERTIME1 + "; "); sb.Append("REST1=" + REST1 + "; "); sb.Append("REST_BEGIN1=" + REST_BEGIN1 + "; "); sb.Append("BREAK1=" + BREAK1 + "; "); sb.Append("OT1=" + OT1 + "; "); sb.Append("EXT1=" + EXT1 + "; "); sb.Append("CANOT1=" + CANOT1 + "; "); sb.Append("OT_REST1=" + OT_REST1 + "; "); sb.Append("OT_REST_BEGIN1=" + OT_REST_BEGIN1 + "; "); sb.Append("BASICHRS1=" + BASICHRS1 + "; "); sb.Append("NEEDHRS1=" + NEEDHRS1 + "; "); sb.Append("DAY1=" + DAY1 + "; "); sb.Append("AHEAD2=" + AHEAD2 + "; "); sb.Append("IN2=" + IN2 + "; "); sb.Append("NEEDIN2=" + NEEDIN2 + "; "); sb.Append("BOVERTIME2=" + BOVERTIME2 + "; "); sb.Append("OUT2=" + OUT2 + "; "); sb.Append("DELAY2=" + DELAY2 + "; "); sb.Append("NEEDOUT2=" + NEEDOUT2 + "; "); sb.Append("EOVERTIME2=" + EOVERTIME2 + "; "); sb.Append("REST2=" + REST2 + "; "); sb.Append("REST_BEGIN2=" + REST_BEGIN2 + "; "); sb.Append("BREAK2=" + BREAK2 + "; "); sb.Append("OT2=" + OT2 + "; "); sb.Append("EXT2=" + EXT2 + "; "); sb.Append("CANOT2=" + CANOT2 + "; "); sb.Append("OT_REST2=" + OT_REST2 + "; "); sb.Append("OT_REST_BEGIN2=" + OT_REST_BEGIN2 + "; "); sb.Append("BASICHRS2=" + BASICHRS2 + "; "); sb.Append("NEEDHRS2=" + NEEDHRS2 + "; "); sb.Append("DAY2=" + DAY2 + "; "); sb.Append("AHEAD3=" + AHEAD3 + "; "); sb.Append("IN3=" + IN3 + "; "); sb.Append("NEEDIN3=" + NEEDIN3 + "; "); sb.Append("BOVERTIME3=" + BOVERTIME3 + "; "); sb.Append("OUT3=" + OUT3 + "; "); sb.Append("DELAY3=" + DELAY3 + "; "); sb.Append("NEEDOUT3=" + NEEDOUT3 + "; "); sb.Append("EOVERTIME3=" + EOVERTIME3 + "; "); sb.Append("REST3=" + REST3 + "; "); sb.Append("REST_BEGIN3=" + REST_BEGIN3 + "; "); sb.Append("BREAK3=" + BREAK3 + "; "); sb.Append("OT3=" + OT3 + "; "); sb.Append("EXT3=" + EXT3 + "; "); sb.Append("CANOT3=" + CANOT3 + "; "); sb.Append("OT_REST3=" + OT_REST3 + "; "); sb.Append("OT_REST_BEGIN3=" + OT_REST_BEGIN3 + "; "); sb.Append("BASICHRS3=" + BASICHRS3 + "; "); sb.Append("NEEDHRS3=" + NEEDHRS3 + "; "); sb.Append("DAY3=" + DAY3 + "; "); sb.Append("AHEAD4=" + AHEAD4 + "; "); sb.Append("IN4=" + IN4 + "; "); sb.Append("NEEDIN4=" + NEEDIN4 + "; "); sb.Append("BOVERTIME4=" + BOVERTIME4 + "; "); sb.Append("OUT4=" + OUT4 + "; "); sb.Append("DELAY4=" + DELAY4 + "; "); sb.Append("NEEDOUT4=" + NEEDOUT4 + "; "); sb.Append("EOVERTIME4=" + EOVERTIME4 + "; "); sb.Append("REST4=" + REST4 + "; "); sb.Append("REST_BEGIN4=" + REST_BEGIN4 + "; "); sb.Append("BREAK4=" + BREAK4 + "; "); sb.Append("OT4=" + OT4 + "; "); sb.Append("EXT4=" + EXT4 + "; "); sb.Append("CANOT4=" + CANOT4 + "; "); sb.Append("OT_REST4=" + OT_REST4 + "; "); sb.Append("OT_REST_BEGIN4=" + OT_REST_BEGIN4 + "; "); sb.Append("BASICHRS4=" + BASICHRS4 + "; "); sb.Append("NEEDHRS4=" + NEEDHRS4 + "; "); sb.Append("DAY4=" + DAY4 + "; "); return sb.ToString(); } public override bool Equals(object obj){ if(obj.GetType()==typeof(Shifts)){ Shifts compare=(Shifts)obj; return compare.KeyValue()==this.KeyValue(); }else{ return base.Equals(obj); } } public string DescriptorValue() { return this.SHIFT_ID.ToString(); } public string DescriptorColumn() { return "SHIFT_ID"; } public static string GetKeyColumn() { return "SHIFT_ID"; } public static string GetDescriptorColumn() { return "SHIFT_ID"; } #region ' Foreign Keys ' #endregion int _Id; /// <summary> /// /// </summary> public int Id { get { return _Id; } set { if(_Id!=value || _isLoaded){ _Id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _SHIFT_ID; /// <summary> /// /// </summary> [SubSonicPrimaryKey] public string SHIFT_ID { get { return _SHIFT_ID; } set { if(_SHIFT_ID!=value || _isLoaded){ _SHIFT_ID=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SHIFT_ID"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _SHIFT_NAME; /// <summary> /// /// </summary> public string SHIFT_NAME { get { return _SHIFT_NAME; } set { if(_SHIFT_NAME!=value || _isLoaded){ _SHIFT_NAME=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SHIFT_NAME"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _DEPART_ID; /// <summary> /// /// </summary> public string DEPART_ID { get { return _DEPART_ID; } set { if(_DEPART_ID!=value || _isLoaded){ _DEPART_ID=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DEPART_ID"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _SHIFT_KIND; /// <summary> /// /// </summary> public int? SHIFT_KIND { get { return _SHIFT_KIND; } set { if(_SHIFT_KIND!=value || _isLoaded){ _SHIFT_KIND=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SHIFT_KIND"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _WORK_HRS; /// <summary> /// /// </summary> public decimal? WORK_HRS { get { return _WORK_HRS; } set { if(_WORK_HRS!=value || _isLoaded){ _WORK_HRS=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="WORK_HRS"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _NEED_HRS; /// <summary> /// /// </summary> public decimal? NEED_HRS { get { return _NEED_HRS; } set { if(_NEED_HRS!=value || _isLoaded){ _NEED_HRS=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEED_HRS"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short _IS_DEFAULT; /// <summary> /// /// </summary> public short IS_DEFAULT { get { return _IS_DEFAULT; } set { if(_IS_DEFAULT!=value || _isLoaded){ _IS_DEFAULT=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IS_DEFAULT"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _RULE_ID; /// <summary> /// /// </summary> public string RULE_ID { get { return _RULE_ID; } set { if(_RULE_ID!=value || _isLoaded){ _RULE_ID=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="RULE_ID"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _CLASS_ID; /// <summary> /// /// </summary> public int? CLASS_ID { get { return _CLASS_ID; } set { if(_CLASS_ID!=value || _isLoaded){ _CLASS_ID=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CLASS_ID"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _NEED_SIGN_COUNT; /// <summary> /// /// </summary> public int? NEED_SIGN_COUNT { get { return _NEED_SIGN_COUNT; } set { if(_NEED_SIGN_COUNT!=value || _isLoaded){ _NEED_SIGN_COUNT=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEED_SIGN_COUNT"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _IS_COMMON; /// <summary> /// /// </summary> public short? IS_COMMON { get { return _IS_COMMON; } set { if(_IS_COMMON!=value || _isLoaded){ _IS_COMMON=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IS_COMMON"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _AHEAD1; /// <summary> /// /// </summary> public int? AHEAD1 { get { return _AHEAD1; } set { if(_AHEAD1!=value || _isLoaded){ _AHEAD1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="AHEAD1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _IN1; /// <summary> /// /// </summary> public DateTime? IN1 { get { return _IN1; } set { if(_IN1!=value || _isLoaded){ _IN1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IN1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _NEEDIN1; /// <summary> /// /// </summary> public short? NEEDIN1 { get { return _NEEDIN1; } set { if(_NEEDIN1!=value || _isLoaded){ _NEEDIN1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDIN1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _BOVERTIME1; /// <summary> /// /// </summary> public short? BOVERTIME1 { get { return _BOVERTIME1; } set { if(_BOVERTIME1!=value || _isLoaded){ _BOVERTIME1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BOVERTIME1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _OUT1; /// <summary> /// /// </summary> public DateTime? OUT1 { get { return _OUT1; } set { if(_OUT1!=value || _isLoaded){ _OUT1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OUT1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _DELAY1; /// <summary> /// /// </summary> public short? DELAY1 { get { return _DELAY1; } set { if(_DELAY1!=value || _isLoaded){ _DELAY1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DELAY1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _NEEDOUT1; /// <summary> /// /// </summary> public short? NEEDOUT1 { get { return _NEEDOUT1; } set { if(_NEEDOUT1!=value || _isLoaded){ _NEEDOUT1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDOUT1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _EOVERTIME1; /// <summary> /// /// </summary> public short? EOVERTIME1 { get { return _EOVERTIME1; } set { if(_EOVERTIME1!=value || _isLoaded){ _EOVERTIME1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EOVERTIME1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _REST1; /// <summary> /// /// </summary> public short? REST1 { get { return _REST1; } set { if(_REST1!=value || _isLoaded){ _REST1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="REST1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _REST_BEGIN1; /// <summary> /// /// </summary> public DateTime? REST_BEGIN1 { get { return _REST_BEGIN1; } set { if(_REST_BEGIN1!=value || _isLoaded){ _REST_BEGIN1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="REST_BEGIN1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _BREAK1; /// <summary> /// /// </summary> public short? BREAK1 { get { return _BREAK1; } set { if(_BREAK1!=value || _isLoaded){ _BREAK1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BREAK1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _OT1; /// <summary> /// /// </summary> public short? OT1 { get { return _OT1; } set { if(_OT1!=value || _isLoaded){ _OT1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _EXT1; /// <summary> /// /// </summary> public short? EXT1 { get { return _EXT1; } set { if(_EXT1!=value || _isLoaded){ _EXT1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EXT1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _CANOT1; /// <summary> /// /// </summary> public short? CANOT1 { get { return _CANOT1; } set { if(_CANOT1!=value || _isLoaded){ _CANOT1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CANOT1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _OT_REST1; /// <summary> /// /// </summary> public int? OT_REST1 { get { return _OT_REST1; } set { if(_OT_REST1!=value || _isLoaded){ _OT_REST1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT_REST1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _OT_REST_BEGIN1; /// <summary> /// /// </summary> public DateTime? OT_REST_BEGIN1 { get { return _OT_REST_BEGIN1; } set { if(_OT_REST_BEGIN1!=value || _isLoaded){ _OT_REST_BEGIN1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT_REST_BEGIN1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _BASICHRS1; /// <summary> /// /// </summary> public decimal? BASICHRS1 { get { return _BASICHRS1; } set { if(_BASICHRS1!=value || _isLoaded){ _BASICHRS1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BASICHRS1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _NEEDHRS1; /// <summary> /// /// </summary> public decimal? NEEDHRS1 { get { return _NEEDHRS1; } set { if(_NEEDHRS1!=value || _isLoaded){ _NEEDHRS1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDHRS1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _DAY1; /// <summary> /// /// </summary> public decimal? DAY1 { get { return _DAY1; } set { if(_DAY1!=value || _isLoaded){ _DAY1=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DAY1"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _AHEAD2; /// <summary> /// /// </summary> public int? AHEAD2 { get { return _AHEAD2; } set { if(_AHEAD2!=value || _isLoaded){ _AHEAD2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="AHEAD2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _IN2; /// <summary> /// /// </summary> public DateTime? IN2 { get { return _IN2; } set { if(_IN2!=value || _isLoaded){ _IN2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IN2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _NEEDIN2; /// <summary> /// /// </summary> public short? NEEDIN2 { get { return _NEEDIN2; } set { if(_NEEDIN2!=value || _isLoaded){ _NEEDIN2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDIN2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _BOVERTIME2; /// <summary> /// /// </summary> public short? BOVERTIME2 { get { return _BOVERTIME2; } set { if(_BOVERTIME2!=value || _isLoaded){ _BOVERTIME2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BOVERTIME2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _OUT2; /// <summary> /// /// </summary> public DateTime? OUT2 { get { return _OUT2; } set { if(_OUT2!=value || _isLoaded){ _OUT2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OUT2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _DELAY2; /// <summary> /// /// </summary> public short? DELAY2 { get { return _DELAY2; } set { if(_DELAY2!=value || _isLoaded){ _DELAY2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DELAY2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _NEEDOUT2; /// <summary> /// /// </summary> public short? NEEDOUT2 { get { return _NEEDOUT2; } set { if(_NEEDOUT2!=value || _isLoaded){ _NEEDOUT2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDOUT2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _EOVERTIME2; /// <summary> /// /// </summary> public short? EOVERTIME2 { get { return _EOVERTIME2; } set { if(_EOVERTIME2!=value || _isLoaded){ _EOVERTIME2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EOVERTIME2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _REST2; /// <summary> /// /// </summary> public short? REST2 { get { return _REST2; } set { if(_REST2!=value || _isLoaded){ _REST2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="REST2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _REST_BEGIN2; /// <summary> /// /// </summary> public DateTime? REST_BEGIN2 { get { return _REST_BEGIN2; } set { if(_REST_BEGIN2!=value || _isLoaded){ _REST_BEGIN2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="REST_BEGIN2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _BREAK2; /// <summary> /// /// </summary> public short? BREAK2 { get { return _BREAK2; } set { if(_BREAK2!=value || _isLoaded){ _BREAK2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BREAK2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _OT2; /// <summary> /// /// </summary> public short? OT2 { get { return _OT2; } set { if(_OT2!=value || _isLoaded){ _OT2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _EXT2; /// <summary> /// /// </summary> public short? EXT2 { get { return _EXT2; } set { if(_EXT2!=value || _isLoaded){ _EXT2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EXT2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _CANOT2; /// <summary> /// /// </summary> public short? CANOT2 { get { return _CANOT2; } set { if(_CANOT2!=value || _isLoaded){ _CANOT2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CANOT2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _OT_REST2; /// <summary> /// /// </summary> public int? OT_REST2 { get { return _OT_REST2; } set { if(_OT_REST2!=value || _isLoaded){ _OT_REST2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT_REST2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _OT_REST_BEGIN2; /// <summary> /// /// </summary> public DateTime? OT_REST_BEGIN2 { get { return _OT_REST_BEGIN2; } set { if(_OT_REST_BEGIN2!=value || _isLoaded){ _OT_REST_BEGIN2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT_REST_BEGIN2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _BASICHRS2; /// <summary> /// /// </summary> public decimal? BASICHRS2 { get { return _BASICHRS2; } set { if(_BASICHRS2!=value || _isLoaded){ _BASICHRS2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BASICHRS2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _NEEDHRS2; /// <summary> /// /// </summary> public decimal? NEEDHRS2 { get { return _NEEDHRS2; } set { if(_NEEDHRS2!=value || _isLoaded){ _NEEDHRS2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDHRS2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _DAY2; /// <summary> /// /// </summary> public decimal? DAY2 { get { return _DAY2; } set { if(_DAY2!=value || _isLoaded){ _DAY2=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DAY2"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _AHEAD3; /// <summary> /// /// </summary> public int? AHEAD3 { get { return _AHEAD3; } set { if(_AHEAD3!=value || _isLoaded){ _AHEAD3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="AHEAD3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _IN3; /// <summary> /// /// </summary> public DateTime? IN3 { get { return _IN3; } set { if(_IN3!=value || _isLoaded){ _IN3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IN3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _NEEDIN3; /// <summary> /// /// </summary> public short? NEEDIN3 { get { return _NEEDIN3; } set { if(_NEEDIN3!=value || _isLoaded){ _NEEDIN3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDIN3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _BOVERTIME3; /// <summary> /// /// </summary> public short? BOVERTIME3 { get { return _BOVERTIME3; } set { if(_BOVERTIME3!=value || _isLoaded){ _BOVERTIME3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BOVERTIME3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _OUT3; /// <summary> /// /// </summary> public DateTime? OUT3 { get { return _OUT3; } set { if(_OUT3!=value || _isLoaded){ _OUT3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OUT3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _DELAY3; /// <summary> /// /// </summary> public short? DELAY3 { get { return _DELAY3; } set { if(_DELAY3!=value || _isLoaded){ _DELAY3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DELAY3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _NEEDOUT3; /// <summary> /// /// </summary> public short? NEEDOUT3 { get { return _NEEDOUT3; } set { if(_NEEDOUT3!=value || _isLoaded){ _NEEDOUT3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDOUT3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _EOVERTIME3; /// <summary> /// /// </summary> public short? EOVERTIME3 { get { return _EOVERTIME3; } set { if(_EOVERTIME3!=value || _isLoaded){ _EOVERTIME3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EOVERTIME3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _REST3; /// <summary> /// /// </summary> public short? REST3 { get { return _REST3; } set { if(_REST3!=value || _isLoaded){ _REST3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="REST3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _REST_BEGIN3; /// <summary> /// /// </summary> public DateTime? REST_BEGIN3 { get { return _REST_BEGIN3; } set { if(_REST_BEGIN3!=value || _isLoaded){ _REST_BEGIN3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="REST_BEGIN3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _BREAK3; /// <summary> /// /// </summary> public short? BREAK3 { get { return _BREAK3; } set { if(_BREAK3!=value || _isLoaded){ _BREAK3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BREAK3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _OT3; /// <summary> /// /// </summary> public short? OT3 { get { return _OT3; } set { if(_OT3!=value || _isLoaded){ _OT3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _EXT3; /// <summary> /// /// </summary> public short? EXT3 { get { return _EXT3; } set { if(_EXT3!=value || _isLoaded){ _EXT3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EXT3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _CANOT3; /// <summary> /// /// </summary> public short? CANOT3 { get { return _CANOT3; } set { if(_CANOT3!=value || _isLoaded){ _CANOT3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CANOT3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _OT_REST3; /// <summary> /// /// </summary> public int? OT_REST3 { get { return _OT_REST3; } set { if(_OT_REST3!=value || _isLoaded){ _OT_REST3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT_REST3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _OT_REST_BEGIN3; /// <summary> /// /// </summary> public DateTime? OT_REST_BEGIN3 { get { return _OT_REST_BEGIN3; } set { if(_OT_REST_BEGIN3!=value || _isLoaded){ _OT_REST_BEGIN3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT_REST_BEGIN3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _BASICHRS3; /// <summary> /// /// </summary> public decimal? BASICHRS3 { get { return _BASICHRS3; } set { if(_BASICHRS3!=value || _isLoaded){ _BASICHRS3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BASICHRS3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _NEEDHRS3; /// <summary> /// /// </summary> public decimal? NEEDHRS3 { get { return _NEEDHRS3; } set { if(_NEEDHRS3!=value || _isLoaded){ _NEEDHRS3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDHRS3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _DAY3; /// <summary> /// /// </summary> public decimal? DAY3 { get { return _DAY3; } set { if(_DAY3!=value || _isLoaded){ _DAY3=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DAY3"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _AHEAD4; /// <summary> /// /// </summary> public int? AHEAD4 { get { return _AHEAD4; } set { if(_AHEAD4!=value || _isLoaded){ _AHEAD4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="AHEAD4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _IN4; /// <summary> /// /// </summary> public DateTime? IN4 { get { return _IN4; } set { if(_IN4!=value || _isLoaded){ _IN4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IN4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _NEEDIN4; /// <summary> /// /// </summary> public short? NEEDIN4 { get { return _NEEDIN4; } set { if(_NEEDIN4!=value || _isLoaded){ _NEEDIN4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDIN4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _BOVERTIME4; /// <summary> /// /// </summary> public short? BOVERTIME4 { get { return _BOVERTIME4; } set { if(_BOVERTIME4!=value || _isLoaded){ _BOVERTIME4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BOVERTIME4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _OUT4; /// <summary> /// /// </summary> public DateTime? OUT4 { get { return _OUT4; } set { if(_OUT4!=value || _isLoaded){ _OUT4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OUT4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _DELAY4; /// <summary> /// /// </summary> public short? DELAY4 { get { return _DELAY4; } set { if(_DELAY4!=value || _isLoaded){ _DELAY4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DELAY4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _NEEDOUT4; /// <summary> /// /// </summary> public short? NEEDOUT4 { get { return _NEEDOUT4; } set { if(_NEEDOUT4!=value || _isLoaded){ _NEEDOUT4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDOUT4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _EOVERTIME4; /// <summary> /// /// </summary> public short? EOVERTIME4 { get { return _EOVERTIME4; } set { if(_EOVERTIME4!=value || _isLoaded){ _EOVERTIME4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EOVERTIME4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _REST4; /// <summary> /// /// </summary> public short? REST4 { get { return _REST4; } set { if(_REST4!=value || _isLoaded){ _REST4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="REST4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _REST_BEGIN4; /// <summary> /// /// </summary> public DateTime? REST_BEGIN4 { get { return _REST_BEGIN4; } set { if(_REST_BEGIN4!=value || _isLoaded){ _REST_BEGIN4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="REST_BEGIN4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _BREAK4; /// <summary> /// /// </summary> public short? BREAK4 { get { return _BREAK4; } set { if(_BREAK4!=value || _isLoaded){ _BREAK4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BREAK4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _OT4; /// <summary> /// /// </summary> public short? OT4 { get { return _OT4; } set { if(_OT4!=value || _isLoaded){ _OT4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _EXT4; /// <summary> /// /// </summary> public short? EXT4 { get { return _EXT4; } set { if(_EXT4!=value || _isLoaded){ _EXT4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EXT4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _CANOT4; /// <summary> /// /// </summary> public short? CANOT4 { get { return _CANOT4; } set { if(_CANOT4!=value || _isLoaded){ _CANOT4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CANOT4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _OT_REST4; /// <summary> /// /// </summary> public int? OT_REST4 { get { return _OT_REST4; } set { if(_OT_REST4!=value || _isLoaded){ _OT_REST4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT_REST4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _OT_REST_BEGIN4; /// <summary> /// /// </summary> public DateTime? OT_REST_BEGIN4 { get { return _OT_REST_BEGIN4; } set { if(_OT_REST_BEGIN4!=value || _isLoaded){ _OT_REST_BEGIN4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OT_REST_BEGIN4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _BASICHRS4; /// <summary> /// /// </summary> public decimal? BASICHRS4 { get { return _BASICHRS4; } set { if(_BASICHRS4!=value || _isLoaded){ _BASICHRS4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BASICHRS4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _NEEDHRS4; /// <summary> /// /// </summary> public decimal? NEEDHRS4 { get { return _NEEDHRS4; } set { if(_NEEDHRS4!=value || _isLoaded){ _NEEDHRS4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NEEDHRS4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _DAY4; /// <summary> /// /// </summary> public decimal? DAY4 { get { return _DAY4; } set { if(_DAY4!=value || _isLoaded){ _DAY4=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DAY4"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } public DbCommand GetUpdateCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetInsertCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetDeleteCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); } public void Update(){ Update(_db.DataProvider); } public void Update(IDataProvider provider){ if(this._dirtyColumns.Count>0){ _repo.Update(this,provider); _dirtyColumns.Clear(); } OnSaved(); } public void Add(){ Add(_db.DataProvider); } public void Add(IDataProvider provider){ var key=KeyValue(); if(key==null){ var newKey=_repo.Add(this,provider); this.SetKeyValue(newKey); }else{ _repo.Add(this,provider); } SetIsNew(false); OnSaved(); } public void Save() { Save(_db.DataProvider); } public void Save(IDataProvider provider) { if (_isNew) { Add(provider); } else { Update(provider); } } public void Delete(IDataProvider provider) { _repo.Delete(KeyValue()); } public void Delete() { Delete(_db.DataProvider); } public static void Delete(Expression<Func<Shifts, bool>> expression) { var repo = GetRepo(); repo.DeleteMany(expression); } public void Load(IDataReader rdr) { Load(rdr, true); } public void Load(IDataReader rdr, bool closeReader) { if (rdr.Read()) { try { rdr.Load(this); SetIsNew(false); SetIsLoaded(true); } catch { SetIsLoaded(false); throw; } }else{ SetIsLoaded(false); } if (closeReader) rdr.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. using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Threading; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { internal class EventLogInternal : IDisposable, ISupportInitialize { private EventLogEntryCollection entriesCollection; internal string logName; // used in monitoring for event postings. private int lastSeenCount; // holds the machine we're on, or null if it's the local machine internal readonly string machineName; // the delegate to call when an event arrives internal EntryWrittenEventHandler onEntryWrittenHandler; // holds onto the handle for reading private SafeEventLogReadHandle readHandle; // the source name - used only when writing internal readonly string sourceName; // holds onto the handle for writing private SafeEventLogWriteHandle writeHandle; private string logDisplayName; // cache system state variables // the initial size of the buffer (it can be made larger if necessary) private const int BUF_SIZE = 40000; // the number of bytes in the cache that belong to entries (not necessarily // the same as BUF_SIZE, because the cache only holds whole entries) private int bytesCached; // the actual cache buffer private byte[] cache; // the number of the entry at the beginning of the cache private int firstCachedEntry = -1; // the number of the entry that we got out of the cache most recently private int lastSeenEntry; // where that entry was private int lastSeenPos; //support for threadpool based deferred execution private ISynchronizeInvoke synchronizingObject; // the EventLog object that publicly exposes this instance. private readonly EventLog parent; private const string EventLogKey = "SYSTEM\\CurrentControlSet\\Services\\EventLog"; internal const string DllName = "EventLogMessages.dll"; private const string eventLogMutexName = "netfxeventlog.1.0"; private const int SecondsPerDay = 60 * 60 * 24; private const int DefaultMaxSize = 512 * 1024; private const int DefaultRetention = 7 * SecondsPerDay; private const int Flag_notifying = 0x1; // keeps track of whether we're notifying our listeners - to prevent double notifications private const int Flag_forwards = 0x2; // whether the cache contains entries in forwards order (true) or backwards (false) private const int Flag_initializing = 0x4; internal const int Flag_monitoring = 0x8; private const int Flag_registeredAsListener = 0x10; private const int Flag_writeGranted = 0x20; private const int Flag_disposed = 0x100; private const int Flag_sourceVerified = 0x200; private BitVector32 boolFlags = new BitVector32(); private Hashtable messageLibraries; private readonly static Hashtable listenerInfos = new Hashtable(StringComparer.OrdinalIgnoreCase); private Object m_InstanceLockObject; private Object InstanceLockObject { get { if (m_InstanceLockObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref m_InstanceLockObject, o, null); } return m_InstanceLockObject; } } private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } public EventLogInternal() : this("", ".", "", null) { } public EventLogInternal(string logName) : this(logName, ".", "", null) { } public EventLogInternal(string logName, string machineName) : this(logName, machineName, "", null) { } public EventLogInternal(string logName, string machineName, string source) : this(logName, machineName, source, null) { } public EventLogInternal(string logName, string machineName, string source, EventLog parent) { //look out for invalid log names if (logName == null) throw new ArgumentNullException(nameof(logName)); if (!ValidLogName(logName, true)) throw new ArgumentException(SR.BadLogName); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); this.machineName = machineName; this.logName = logName; this.sourceName = source; readHandle = null; writeHandle = null; boolFlags[Flag_forwards] = true; this.parent = parent; } public EventLogEntryCollection Entries { get { string currentMachineName = this.machineName; if (entriesCollection == null) entriesCollection = new EventLogEntryCollection(this); return entriesCollection; } } internal int EntryCount { get { if (!IsOpenForRead) OpenForRead(this.machineName); int count; bool success = UnsafeNativeMethods.GetNumberOfEventLogRecords(readHandle, out count); if (!success) throw SharedUtils.CreateSafeWin32Exception(); return count; } } private bool IsOpen { get { return readHandle != null || writeHandle != null; } } private bool IsOpenForRead { get { return readHandle != null; } } private bool IsOpenForWrite { get { return writeHandle != null; } } public string LogDisplayName { get { if (logDisplayName != null) return logDisplayName; string currentMachineName = this.machineName; if (GetLogName(currentMachineName) != null) { RegistryKey logkey = null; try { // we figure out what logs are on the machine by looking in the registry. logkey = GetLogRegKey(currentMachineName, false); if (logkey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, GetLogName(currentMachineName), currentMachineName)); string resourceDll = (string)logkey.GetValue("DisplayNameFile"); if (resourceDll == null) logDisplayName = GetLogName(currentMachineName); else { int resourceId = (int)logkey.GetValue("DisplayNameID"); logDisplayName = FormatMessageWrapper(resourceDll, (uint)resourceId, null); if (logDisplayName == null) logDisplayName = GetLogName(currentMachineName); } } finally { logkey?.Close(); } } return logDisplayName; } } public string Log { get { string currentMachineName = this.machineName; return GetLogName(currentMachineName); } } private string GetLogName(string currentMachineName) { if ((logName == null || logName.Length == 0) && sourceName != null && sourceName.Length != 0) { logName = EventLog._InternalLogNameFromSourceName(sourceName, currentMachineName); } return logName; } public string MachineName { get { return this.machineName; } } [ComVisible(false)] public long MaximumKilobytes { get { string currentMachineName = this.machineName; object val = GetLogRegValue(currentMachineName, "MaxSize"); if (val != null) { int intval = (int)val; // cast to an int first to unbox return ((uint)intval) / 1024; // then convert to kilobytes } // 512k is the default value return 0x200; } set { string currentMachineName = this.machineName; // valid range is 64 KB to 4 GB if (value < 64 || value > 0x3FFFC0 || value % 64 != 0) throw new ArgumentOutOfRangeException("MaximumKilobytes", SR.MaximumKilobytesOutOfRange); long regvalue = value * 1024; // convert to bytes int i = unchecked((int)regvalue); using (RegistryKey logkey = GetLogRegKey(currentMachineName, true)) logkey.SetValue("MaxSize", i, RegistryValueKind.DWord); } } internal Hashtable MessageLibraries { get { if (messageLibraries == null) messageLibraries = new Hashtable(StringComparer.OrdinalIgnoreCase); return messageLibraries; } } [ComVisible(false)] public OverflowAction OverflowAction { get { string currentMachineName = this.machineName; object retentionobj = GetLogRegValue(currentMachineName, "Retention"); if (retentionobj != null) { int retention = (int)retentionobj; if (retention == 0) return OverflowAction.OverwriteAsNeeded; else if (retention == -1) return OverflowAction.DoNotOverwrite; else return OverflowAction.OverwriteOlder; } // default value as listed in MSDN return OverflowAction.OverwriteOlder; } } [ComVisible(false)] public int MinimumRetentionDays { get { string currentMachineName = this.machineName; object retentionobj = GetLogRegValue(currentMachineName, "Retention"); if (retentionobj != null) { int retention = (int)retentionobj; if (retention == 0 || retention == -1) return retention; else return (int)(((double)retention) / SecondsPerDay); } return 7; } } public bool EnableRaisingEvents { get { string currentMachineName = this.machineName; return boolFlags[Flag_monitoring]; } set { string currentMachineName = this.machineName; if (parent.ComponentDesignMode) this.boolFlags[Flag_monitoring] = value; else { if (value) StartRaisingEvents(currentMachineName, GetLogName(currentMachineName)); else StopRaisingEvents(/*currentMachineName,*/ GetLogName(currentMachineName)); } } } private int OldestEntryNumber { get { if (!IsOpenForRead) OpenForRead(this.machineName); int num; bool success = UnsafeNativeMethods.GetOldestEventLogRecord(readHandle, out num); if (!success) throw SharedUtils.CreateSafeWin32Exception(); if (num == 0) num = 1; return num; } } internal SafeEventLogReadHandle ReadHandle { get { if (!IsOpenForRead) OpenForRead(this.machineName); return readHandle; } } public ISynchronizeInvoke SynchronizingObject { get { string currentMachineName = this.machineName; if (this.synchronizingObject == null && parent.ComponentDesignMode) { IDesignerHost host = (IDesignerHost)parent.ComponentGetService(typeof(IDesignerHost)); if (host != null) { object baseComponent = host.RootComponent; if (baseComponent != null && baseComponent is ISynchronizeInvoke) this.synchronizingObject = (ISynchronizeInvoke)baseComponent; } } return this.synchronizingObject; } set { this.synchronizingObject = value; } } public string Source { get { string currentMachineName = this.machineName; return sourceName; } } private static void AddListenerComponent(EventLogInternal component, string compMachineName, string compLogName) { lock (InternalSyncObject) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::AddListenerComponent(" + compLogName + ")"); LogListeningInfo info = (LogListeningInfo)listenerInfos[compLogName]; if (info != null) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::AddListenerComponent: listener already active."); info.listeningComponents.Add(component); return; } info = new LogListeningInfo(); info.listeningComponents.Add(component); info.handleOwner = new EventLogInternal(compLogName, compMachineName); // tell the event log system about it info.waitHandle = new AutoResetEvent(false); bool success = UnsafeNativeMethods.NotifyChangeEventLog(info.handleOwner.ReadHandle, info.waitHandle.SafeWaitHandle); if (!success) throw new InvalidOperationException(SR.CantMonitorEventLog, SharedUtils.CreateSafeWin32Exception()); info.registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(info.waitHandle, new WaitOrTimerCallback(StaticCompletionCallback), info, -1, false); listenerInfos[compLogName] = info; } } public event EntryWrittenEventHandler EntryWritten { add { string currentMachineName = this.machineName; onEntryWrittenHandler += value; } remove { string currentMachineName = this.machineName; onEntryWrittenHandler -= value; } } public void BeginInit() { string currentMachineName = this.machineName; if (boolFlags[Flag_initializing]) throw new InvalidOperationException(SR.InitTwice); boolFlags[Flag_initializing] = true; if (boolFlags[Flag_monitoring]) StopListening(GetLogName(currentMachineName)); } public void Clear() { string currentMachineName = this.machineName; if (!IsOpenForRead) OpenForRead(currentMachineName); bool success = UnsafeNativeMethods.ClearEventLog(readHandle, NativeMethods.NullHandleRef); if (!success) { // Ignore file not found errors. ClearEventLog seems to try to delete the file where the event log is // stored. If it can't find it, it gives an error. int error = Marshal.GetLastWin32Error(); if (error != NativeMethods.ERROR_FILE_NOT_FOUND) throw SharedUtils.CreateSafeWin32Exception(); } // now that we've cleared the event log, we need to re-open our handles, because // the internal state of the event log has changed. Reset(currentMachineName); } public void Close() { Close(this.machineName); } private void Close(string currentMachineName) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Close"); //Trace("Close", "Closing the event log"); if (readHandle != null) { try { readHandle.Close(); } catch (IOException) { throw SharedUtils.CreateSafeWin32Exception(); } readHandle = null; //Trace("Close", "Closed read handle"); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Close: closed read handle"); } if (writeHandle != null) { try { writeHandle.Close(); } catch (IOException) { throw SharedUtils.CreateSafeWin32Exception(); } writeHandle = null; //Trace("Close", "Closed write handle"); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Close: closed write handle"); } if (boolFlags[Flag_monitoring]) StopRaisingEvents(/*currentMachineName,*/ GetLogName(currentMachineName)); if (messageLibraries != null) { foreach (SafeLibraryHandle handle in messageLibraries.Values) handle.Close(); messageLibraries = null; } boolFlags[Flag_sourceVerified] = false; } private void CompletionCallback(object context) { if (boolFlags[Flag_disposed]) { // This object has been disposed previously, ignore firing the event. return; } Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: starting at " + lastSeenCount.ToString(CultureInfo.InvariantCulture)); lock (InstanceLockObject) { if (boolFlags[Flag_notifying]) { // don't do double notifications. Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: aborting because we're already notifying."); return; } boolFlags[Flag_notifying] = true; } int i = lastSeenCount; try { int oldest = OldestEntryNumber; int count = EntryCount + oldest; // Ensure lastSeenCount is within bounds. This deals with the case where the event log has been cleared between // notifications. if (lastSeenCount < oldest || lastSeenCount > count) { lastSeenCount = oldest; i = lastSeenCount; } Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: OldestEntryNumber is " + OldestEntryNumber + ", EntryCount is " + EntryCount); while (i < count) { while (i < count) { EventLogEntry entry = GetEntryWithOldest(i); if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) this.SynchronizingObject.BeginInvoke(this.onEntryWrittenHandler, new object[] { this, new EntryWrittenEventArgs(entry) }); else onEntryWrittenHandler(this, new EntryWrittenEventArgs(entry)); i++; } oldest = OldestEntryNumber; count = EntryCount + oldest; } } catch (Exception e) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: Caught exception notifying event handlers: " + e.ToString()); } try { // if the user cleared the log while we were receiving events, the call to GetEntryWithOldest above could have // thrown an exception and i could be too large. Make sure we don't set lastSeenCount to something bogus. int newCount = EntryCount + OldestEntryNumber; if (i > newCount) lastSeenCount = newCount; else lastSeenCount = i; Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: finishing at " + lastSeenCount.ToString(CultureInfo.InvariantCulture)); } catch (Win32Exception e) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: Caught exception updating last entry number: " + e.ToString()); } lock (InstanceLockObject) { boolFlags[Flag_notifying] = false; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } internal void Dispose(bool disposing) { try { if (disposing) { //Dispose unmanaged and managed resources if (IsOpen) { Close(); } // This is probably unnecessary if (readHandle != null) { readHandle.Close(); readHandle = null; } if (writeHandle != null) { writeHandle.Close(); writeHandle = null; } } } finally { messageLibraries = null; this.boolFlags[Flag_disposed] = true; } } public void EndInit() { string currentMachineName = this.machineName; boolFlags[Flag_initializing] = false; if (boolFlags[Flag_monitoring]) StartListening(currentMachineName, GetLogName(currentMachineName)); } internal string FormatMessageWrapper(string dllNameList, uint messageNum, string[] insertionStrings) { if (dllNameList == null) return null; if (insertionStrings == null) insertionStrings = new string[0]; string[] listDll = dllNameList.Split(';'); // Find first mesage in DLL list foreach (string dllName in listDll) { if (dllName == null || dllName.Length == 0) continue; SafeLibraryHandle hModule = null; if (IsOpen) { hModule = MessageLibraries[dllName] as SafeLibraryHandle; if (hModule == null || hModule.IsInvalid) { hModule = Interop.Kernel32.LoadLibraryExW(dllName, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE); MessageLibraries[dllName] = hModule; } } else { hModule = Interop.Kernel32.LoadLibraryExW(dllName, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE); } if (hModule.IsInvalid) continue; string msg = null; try { msg = EventLog.TryFormatMessage(hModule, messageNum, insertionStrings); } finally { if (!IsOpen) { hModule.Close(); } } if (msg != null) { return msg; } } return null; } internal EventLogEntry[] GetAllEntries() { // we could just call getEntryAt() on all the entries, but it'll be faster // if we grab multiple entries at once. string currentMachineName = this.machineName; if (!IsOpenForRead) OpenForRead(currentMachineName); EventLogEntry[] entries = new EventLogEntry[EntryCount]; int idx = 0; int oldestEntry = OldestEntryNumber; int bytesRead; int minBytesNeeded; int error = 0; while (idx < entries.Length) { byte[] buf = new byte[BUF_SIZE]; bool success = UnsafeNativeMethods.ReadEventLog(readHandle, NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ, oldestEntry + idx, buf, buf.Length, out bytesRead, out minBytesNeeded); if (!success) { error = Marshal.GetLastWin32Error(); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "Error from ReadEventLog is " + error.ToString(CultureInfo.InvariantCulture)); if (error == Interop.Kernel32.ERROR_INSUFFICIENT_BUFFER || error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) { if (error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) { Reset(currentMachineName); } // try again with a bigger buffer if necessary else if (minBytesNeeded > buf.Length) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "Increasing buffer size from " + buf.Length.ToString(CultureInfo.InvariantCulture) + " to " + minBytesNeeded.ToString(CultureInfo.InvariantCulture) + " bytes"); buf = new byte[minBytesNeeded]; } success = UnsafeNativeMethods.ReadEventLog(readHandle, NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ, oldestEntry + idx, buf, buf.Length, out bytesRead, out minBytesNeeded); if (!success) break; } else { break; } error = 0; } entries[idx] = new EventLogEntry(buf, 0, this); int sum = IntFrom(buf, 0); idx++; while (sum < bytesRead && idx < entries.Length) { entries[idx] = new EventLogEntry(buf, sum, this); sum += IntFrom(buf, sum); idx++; } } if (idx != entries.Length) { if (error != 0) throw new InvalidOperationException(SR.CantRetrieveEntries, SharedUtils.CreateSafeWin32Exception(error)); else throw new InvalidOperationException(SR.CantRetrieveEntries); } return entries; } private int GetCachedEntryPos(int entryIndex) { if (cache == null || (boolFlags[Flag_forwards] && entryIndex < firstCachedEntry) || (!boolFlags[Flag_forwards] && entryIndex > firstCachedEntry) || firstCachedEntry == -1) { // the index falls before anything we have in the cache, or the cache // is not yet valid return -1; } while (lastSeenEntry < entryIndex) { lastSeenEntry++; if (boolFlags[Flag_forwards]) { lastSeenPos = GetNextEntryPos(lastSeenPos); if (lastSeenPos >= bytesCached) break; } else { lastSeenPos = GetPreviousEntryPos(lastSeenPos); if (lastSeenPos < 0) break; } } while (lastSeenEntry > entryIndex) { lastSeenEntry--; if (boolFlags[Flag_forwards]) { lastSeenPos = GetPreviousEntryPos(lastSeenPos); if (lastSeenPos < 0) break; } else { lastSeenPos = GetNextEntryPos(lastSeenPos); if (lastSeenPos >= bytesCached) break; } } if (lastSeenPos >= bytesCached) { // we ran past the end. move back to the last one and return -1 lastSeenPos = GetPreviousEntryPos(lastSeenPos); if (boolFlags[Flag_forwards]) lastSeenEntry--; else lastSeenEntry++; return -1; } else if (lastSeenPos < 0) { // we ran past the beginning. move back to the first one and return -1 lastSeenPos = 0; if (boolFlags[Flag_forwards]) lastSeenEntry++; else lastSeenEntry--; return -1; } else { // we found it. return lastSeenPos; } } internal EventLogEntry GetEntryAt(int index) { EventLogEntry entry = GetEntryAtNoThrow(index); if (entry == null) throw new ArgumentException(SR.Format(SR.IndexOutOfBounds, index.ToString(CultureInfo.CurrentCulture))); return entry; } internal EventLogEntry GetEntryAtNoThrow(int index) { if (!IsOpenForRead) OpenForRead(this.machineName); if (index < 0 || index >= EntryCount) return null; index += OldestEntryNumber; EventLogEntry entry = null; try { entry = GetEntryWithOldest(index); } catch (InvalidOperationException) { } return entry; } private EventLogEntry GetEntryWithOldest(int index) { EventLogEntry entry = null; int entryPos = GetCachedEntryPos(index); if (entryPos >= 0) { entry = new EventLogEntry(cache, entryPos, this); return entry; } string currentMachineName = this.machineName; int flags = 0; if (GetCachedEntryPos(index + 1) < 0) { flags = NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ; boolFlags[Flag_forwards] = true; } else { flags = NativeMethods.BACKWARDS_READ | NativeMethods.SEEK_READ; boolFlags[Flag_forwards] = false; } cache = new byte[BUF_SIZE]; int bytesRead; int minBytesNeeded; bool success = UnsafeNativeMethods.ReadEventLog(readHandle, flags, index, cache, cache.Length, out bytesRead, out minBytesNeeded); if (!success) { int error = Marshal.GetLastWin32Error(); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "Error from ReadEventLog is " + error.ToString(CultureInfo.InvariantCulture)); if (error == Interop.Kernel32.ERROR_INSUFFICIENT_BUFFER || error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) { if (error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) { byte[] tempcache = cache; Reset(currentMachineName); cache = tempcache; } else { // try again with a bigger buffer. if (minBytesNeeded > cache.Length) { cache = new byte[minBytesNeeded]; } } success = UnsafeNativeMethods.ReadEventLog(readHandle, NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ, index, cache, cache.Length, out bytesRead, out minBytesNeeded); } if (!success) { throw new InvalidOperationException(SR.Format(SR.CantReadLogEntryAt, index.ToString(CultureInfo.CurrentCulture)), SharedUtils.CreateSafeWin32Exception()); } } bytesCached = bytesRead; firstCachedEntry = index; lastSeenEntry = index; lastSeenPos = 0; return new EventLogEntry(cache, 0, this); } internal static RegistryKey GetEventLogRegKey(string machine, bool writable) { RegistryKey lmkey = null; try { if (machine.Equals(".")) { lmkey = Registry.LocalMachine; } else { lmkey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine); } if (lmkey != null) return lmkey.OpenSubKey(EventLogKey, writable); } finally { lmkey?.Close(); } return null; } private RegistryKey GetLogRegKey(string currentMachineName, bool writable) { string logname = GetLogName(currentMachineName); if (!ValidLogName(logname, false)) throw new InvalidOperationException(SR.BadLogName); RegistryKey eventkey = null; RegistryKey logkey = null; try { eventkey = GetEventLogRegKey(currentMachineName, false); if (eventkey == null) throw new InvalidOperationException(SR.Format(SR.RegKeyMissingShort, EventLogKey, currentMachineName)); logkey = eventkey.OpenSubKey(logname, writable); if (logkey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, logname, currentMachineName)); } finally { eventkey?.Close(); } return logkey; } private object GetLogRegValue(string currentMachineName, string valuename) { RegistryKey logkey = null; try { logkey = GetLogRegKey(currentMachineName, false); if (logkey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, GetLogName(currentMachineName), currentMachineName)); object val = logkey.GetValue(valuename); return val; } finally { logkey?.Close(); } } private int GetNextEntryPos(int pos) { return pos + IntFrom(cache, pos); } private int GetPreviousEntryPos(int pos) { return pos - IntFrom(cache, pos - 4); } internal static string GetDllPath(string machineName) { return Path.Combine(SharedUtils.GetLatestBuildDllDirectory(machineName), DllName); } private static int IntFrom(byte[] buf, int offset) { // assumes Little Endian byte order. return (unchecked((int)0xFF000000) & (buf[offset + 3] << 24)) | (0xFF0000 & (buf[offset + 2] << 16)) | (0xFF00 & (buf[offset + 1] << 8)) | (0xFF & (buf[offset])); } [ComVisible(false)] public void ModifyOverflowPolicy(OverflowAction action, int retentionDays) { string currentMachineName = this.machineName; if (action < OverflowAction.DoNotOverwrite || action > OverflowAction.OverwriteOlder) throw new InvalidEnumArgumentException("action", (int)action, typeof(OverflowAction)); // this is a long because in the if statement we may need to store values as // large as UInt32.MaxValue - 1. This would overflow an int. long retentionvalue = (long)action; if (action == OverflowAction.OverwriteOlder) { if (retentionDays < 1 || retentionDays > 365) throw new ArgumentOutOfRangeException(SR.RentionDaysOutOfRange); retentionvalue = (long)retentionDays * SecondsPerDay; } using (RegistryKey logkey = GetLogRegKey(currentMachineName, true)) logkey.SetValue("Retention", retentionvalue, RegistryValueKind.DWord); } private void OpenForRead(string currentMachineName) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::OpenForRead"); if (this.boolFlags[Flag_disposed]) throw new ObjectDisposedException(GetType().Name); string logname = GetLogName(currentMachineName); if (logname == null || logname.Length == 0) throw new ArgumentException(SR.MissingLogProperty); if (!EventLog.Exists(logname, currentMachineName)) // do not open non-existing Log [alexvec] throw new InvalidOperationException(SR.Format(SR.LogDoesNotExists, logname, currentMachineName)); // Clean up cache variables. // The initilizing code is put here to guarantee, that first read of events // from log file will start by filling up the cache buffer. lastSeenEntry = 0; lastSeenPos = 0; bytesCached = 0; firstCachedEntry = -1; SafeEventLogReadHandle handle = SafeEventLogReadHandle.OpenEventLog(currentMachineName, logname); if (handle.IsInvalid) { Win32Exception e = null; if (Marshal.GetLastWin32Error() != 0) { e = SharedUtils.CreateSafeWin32Exception(); } throw new InvalidOperationException(SR.Format(SR.CantOpenLog, logname.ToString(), currentMachineName, e?.Message ?? "")); } readHandle = handle; } private void OpenForWrite(string currentMachineName) { //Cannot allocate the writeHandle if the object has been disposed, since finalization has been suppressed. if (this.boolFlags[Flag_disposed]) throw new ObjectDisposedException(GetType().Name); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::OpenForWrite"); if (sourceName == null || sourceName.Length == 0) throw new ArgumentException(SR.NeedSourceToOpen); SafeEventLogWriteHandle handle = SafeEventLogWriteHandle.RegisterEventSource(currentMachineName, sourceName); if (handle.IsInvalid) { Win32Exception e = null; if (Marshal.GetLastWin32Error() != 0) { e = SharedUtils.CreateSafeWin32Exception(); } throw new InvalidOperationException(SR.Format(SR.CantOpenLogAccess, sourceName), e); } writeHandle = handle; } [ComVisible(false)] public void RegisterDisplayName(string resourceFile, long resourceId) { string currentMachineName = this.machineName; using (RegistryKey logkey = GetLogRegKey(currentMachineName, true)) { logkey.SetValue("DisplayNameFile", resourceFile, RegistryValueKind.ExpandString); logkey.SetValue("DisplayNameID", resourceId, RegistryValueKind.DWord); } } private void Reset(string currentMachineName) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Reset"); // save the state we're in now bool openRead = IsOpenForRead; bool openWrite = IsOpenForWrite; bool isMonitoring = boolFlags[Flag_monitoring]; bool isListening = boolFlags[Flag_registeredAsListener]; // close everything down Close(currentMachineName); cache = null; // and get us back into the same state as before if (openRead) OpenForRead(currentMachineName); if (openWrite) OpenForWrite(currentMachineName); if (isListening) StartListening(currentMachineName, GetLogName(currentMachineName)); boolFlags[Flag_monitoring] = isMonitoring; } [HostProtection(Synchronization = true)] private static void RemoveListenerComponent(EventLogInternal component, string compLogName) { lock (InternalSyncObject) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::RemoveListenerComponent(" + compLogName + ")"); LogListeningInfo info = (LogListeningInfo)listenerInfos[compLogName]; Debug.Assert(info != null); // remove the requested component from the list. info.listeningComponents.Remove(component); if (info.listeningComponents.Count != 0) return; // if that was the last interested compononent, destroy the handles and stop listening. info.handleOwner.Dispose(); //Unregister the thread pool wait handle info.registeredWaitHandle.Unregister(info.waitHandle); // close the handle info.waitHandle.Close(); listenerInfos[compLogName] = null; } } private void StartListening(string currentMachineName, string currentLogName) { // make sure we don't fire events for entries that are already there Debug.Assert(!boolFlags[Flag_registeredAsListener], "StartListening called with boolFlags[Flag_registeredAsListener] true."); lastSeenCount = EntryCount + OldestEntryNumber; Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::StartListening: lastSeenCount = " + lastSeenCount); AddListenerComponent(this, currentMachineName, currentLogName); boolFlags[Flag_registeredAsListener] = true; } private void StartRaisingEvents(string currentMachineName, string currentLogName) { if (!boolFlags[Flag_initializing] && !boolFlags[Flag_monitoring] && !parent.ComponentDesignMode) { StartListening(currentMachineName, currentLogName); } boolFlags[Flag_monitoring] = true; } private static void StaticCompletionCallback(object context, bool wasSignaled) { LogListeningInfo info = (LogListeningInfo)context; if (info == null) return; // get a snapshot of the components to fire the event on EventLogInternal[] interestedComponents; lock (InternalSyncObject) { interestedComponents = (EventLogInternal[])info.listeningComponents.ToArray(typeof(EventLogInternal)); } Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::StaticCompletionCallback: notifying " + interestedComponents.Length + " components."); for (int i = 0; i < interestedComponents.Length; i++) { try { if (interestedComponents[i] != null) { interestedComponents[i].CompletionCallback(null); } } catch (ObjectDisposedException) { // The EventLog that was registered to listen has been disposed. Nothing much we can do here // we don't want to propigate this error up as it will likely be unhandled and will cause the app // to crash. Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::StaticCompletionCallback: ignored an ObjectDisposedException"); } } } private void StopListening(/*string currentMachineName,*/ string currentLogName) { Debug.Assert(boolFlags[Flag_registeredAsListener], "StopListening called without StartListening."); RemoveListenerComponent(this, currentLogName); boolFlags[Flag_registeredAsListener] = false; } private void StopRaisingEvents(/*string currentMachineName,*/ string currentLogName) { if (!boolFlags[Flag_initializing] && boolFlags[Flag_monitoring] && !parent.ComponentDesignMode) { StopListening(currentLogName); } boolFlags[Flag_monitoring] = false; } private static bool CharIsPrintable(char c) { UnicodeCategory uc = Char.GetUnicodeCategory(c); return (!(uc == UnicodeCategory.Control) || (uc == UnicodeCategory.Format) || (uc == UnicodeCategory.LineSeparator) || (uc == UnicodeCategory.ParagraphSeparator) || (uc == UnicodeCategory.OtherNotAssigned)); } internal static bool ValidLogName(string logName, bool ignoreEmpty) { if (logName.Length == 0 && !ignoreEmpty) return false; //any space, backslash, asterisk, or question mark is bad //any non-printable characters are also bad foreach (char c in logName) if (!CharIsPrintable(c) || (c == '\\') || (c == '*') || (c == '?')) return false; return true; } private void VerifyAndCreateSource(string sourceName, string currentMachineName) { if (boolFlags[Flag_sourceVerified]) return; if (!EventLog.SourceExists(sourceName, currentMachineName, true)) { Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { SharedUtils.EnterMutex(eventLogMutexName, ref mutex); if (!EventLog.SourceExists(sourceName, currentMachineName, true)) { if (GetLogName(currentMachineName) == null) this.logName = "Application"; // we automatically add an entry in the registry if there's not already // one there for this source EventLog.CreateEventSource(new EventSourceCreationData(sourceName, GetLogName(currentMachineName), currentMachineName)); // The user may have set a custom log and tried to read it before trying to // write. Due to a quirk in the event log API, we would have opened the Application // log to read (because the custom log wasn't there). Now that we've created // the custom log, we should close so that when we re-open, we get a read // handle on the _new_ log instead of the Application log. Reset(currentMachineName); } else { string rightLogName = EventLog.LogNameFromSourceName(sourceName, currentMachineName); string currentLogName = GetLogName(currentMachineName); if (rightLogName != null && currentLogName != null && String.Compare(rightLogName, currentLogName, StringComparison.OrdinalIgnoreCase) != 0) throw new ArgumentException(SR.Format(SR.LogSourceMismatch, Source.ToString(), currentLogName, rightLogName)); } } finally { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); } } } else { string rightLogName = EventLog._InternalLogNameFromSourceName(sourceName, currentMachineName); string currentLogName = GetLogName(currentMachineName); if (rightLogName != null && currentLogName != null && String.Compare(rightLogName, currentLogName, StringComparison.OrdinalIgnoreCase) != 0) throw new ArgumentException(SR.Format(SR.LogSourceMismatch, Source.ToString(), currentLogName, rightLogName)); } boolFlags[Flag_sourceVerified] = true; } public void WriteEntry(string message) { WriteEntry(message, EventLogEntryType.Information, (short)0, 0, null); } public void WriteEntry(string message, EventLogEntryType type) { WriteEntry(message, type, (short)0, 0, null); } public void WriteEntry(string message, EventLogEntryType type, int eventID) { WriteEntry(message, type, eventID, 0, null); } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category) { WriteEntry(message, type, eventID, category, null); } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, byte[] rawData) { if (eventID < 0 || eventID > ushort.MaxValue) throw new ArgumentException(SR.Format(SR.EventID, eventID.ToString(), 0, ushort.MaxValue)); if (Source.Length == 0) throw new ArgumentException(SR.NeedSourceToWrite); if (!Enum.IsDefined(typeof(EventLogEntryType), type)) throw new InvalidEnumArgumentException(nameof(type), (int)type, typeof(EventLogEntryType)); string currentMachineName = machineName; if (!boolFlags[Flag_writeGranted]) { boolFlags[Flag_writeGranted] = true; } VerifyAndCreateSource(sourceName, currentMachineName); // now that the source has been hooked up to our DLL, we can use "normal" // (message-file driven) logging techniques. // Our DLL has 64K different entries; all of them just display the first // insertion string. InternalWriteEvent((uint)eventID, (ushort)category, type, new string[] { message }, rawData, currentMachineName); } [ComVisible(false)] public void WriteEvent(EventInstance instance, params Object[] values) { WriteEvent(instance, null, values); } [ComVisible(false)] public void WriteEvent(EventInstance instance, byte[] data, params Object[] values) { if (instance == null) throw new ArgumentNullException(nameof(instance)); if (Source.Length == 0) throw new ArgumentException(SR.NeedSourceToWrite); string currentMachineName = machineName; if (!boolFlags[Flag_writeGranted]) { boolFlags[Flag_writeGranted] = true; } VerifyAndCreateSource(Source, currentMachineName); string[] strings = null; if (values != null) { strings = new string[values.Length]; for (int i = 0; i < values.Length; i++) { if (values[i] != null) strings[i] = values[i].ToString(); else strings[i] = String.Empty; } } InternalWriteEvent((uint)instance.InstanceId, (ushort)instance.CategoryId, instance.EntryType, strings, data, currentMachineName); } private void InternalWriteEvent(uint eventID, ushort category, EventLogEntryType type, string[] strings, byte[] rawData, string currentMachineName) { // check arguments if (strings == null) strings = new string[0]; if (strings.Length >= 256) throw new ArgumentException(SR.TooManyReplacementStrings); for (int i = 0; i < strings.Length; i++) { if (strings[i] == null) strings[i] = String.Empty; // make sure the strings aren't too long. MSDN says each string has a limit of 32k (32768) characters, but // experimentation shows that it doesn't like anything larger than 32766 if (strings[i].Length > 32766) throw new ArgumentException(SR.LogEntryTooLong); } if (rawData == null) rawData = new byte[0]; if (Source.Length == 0) throw new ArgumentException(SR.NeedSourceToWrite); if (!IsOpenForWrite) OpenForWrite(currentMachineName); // pin each of the strings in memory IntPtr[] stringRoots = new IntPtr[strings.Length]; GCHandle[] stringHandles = new GCHandle[strings.Length]; GCHandle stringsRootHandle = GCHandle.Alloc(stringRoots, GCHandleType.Pinned); try { for (int strIndex = 0; strIndex < strings.Length; strIndex++) { stringHandles[strIndex] = GCHandle.Alloc(strings[strIndex], GCHandleType.Pinned); stringRoots[strIndex] = stringHandles[strIndex].AddrOfPinnedObject(); } byte[] sid = null; // actually report the event bool success = UnsafeNativeMethods.ReportEvent(writeHandle, (short)type, category, eventID, sid, (short)strings.Length, rawData.Length, new HandleRef(this, stringsRootHandle.AddrOfPinnedObject()), rawData); if (!success) { //Trace("WriteEvent", "Throwing Win32Exception"); throw SharedUtils.CreateSafeWin32Exception(); } } finally { // now free the pinned strings for (int i = 0; i < strings.Length; i++) { if (stringHandles[i].IsAllocated) stringHandles[i].Free(); } stringsRootHandle.Free(); } } private class LogListeningInfo { public EventLogInternal handleOwner; public RegisteredWaitHandle registeredWaitHandle; public WaitHandle waitHandle; public ArrayList listeningComponents = new ArrayList(); } } }
namespace java.util { [global::MonoJavaBridge.JavaClass()] public sealed partial class Formatter : java.lang.Object, java.io.Closeable, java.io.Flushable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Formatter() { InitJNI(); } internal Formatter(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _toString15412; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Formatter._toString15412)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Formatter.staticClass, global::java.util.Formatter._toString15412)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _format15413; public global::java.util.Formatter format(java.util.Locale arg0, java.lang.String arg1, java.lang.Object[] arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Formatter._format15413, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.util.Formatter; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Formatter.staticClass, global::java.util.Formatter._format15413, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.util.Formatter; } internal static global::MonoJavaBridge.MethodId _format15414; public global::java.util.Formatter format(java.lang.String arg0, java.lang.Object[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Formatter._format15414, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.util.Formatter; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Formatter.staticClass, global::java.util.Formatter._format15414, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.util.Formatter; } internal static global::MonoJavaBridge.MethodId _out15415; public global::java.lang.Appendable @out() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.Appendable>(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Formatter._out15415)) as java.lang.Appendable; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.Appendable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Formatter.staticClass, global::java.util.Formatter._out15415)) as java.lang.Appendable; } internal static global::MonoJavaBridge.MethodId _flush15416; public void flush() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.util.Formatter._flush15416); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Formatter.staticClass, global::java.util.Formatter._flush15416); } internal static global::MonoJavaBridge.MethodId _close15417; public void close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.util.Formatter._close15417); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Formatter.staticClass, global::java.util.Formatter._close15417); } internal static global::MonoJavaBridge.MethodId _locale15418; public global::java.util.Locale locale() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Formatter._locale15418)) as java.util.Locale; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Formatter.staticClass, global::java.util.Formatter._locale15418)) as java.util.Locale; } internal static global::MonoJavaBridge.MethodId _ioException15419; public global::java.io.IOException ioException() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Formatter._ioException15419)) as java.io.IOException; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Formatter.staticClass, global::java.util.Formatter._ioException15419)) as java.io.IOException; } internal static global::MonoJavaBridge.MethodId _Formatter15420; public Formatter(java.io.OutputStream arg0, java.lang.String arg1, java.util.Locale arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15420, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15421; public Formatter() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15421); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15422; public Formatter(java.lang.Appendable arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15422, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15423; public Formatter(java.util.Locale arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15423, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15424; public Formatter(java.lang.Appendable arg0, java.util.Locale arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15424, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15425; public Formatter(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15425, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15426; public Formatter(java.lang.String arg0, java.lang.String arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15426, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15427; public Formatter(java.lang.String arg0, java.lang.String arg1, java.util.Locale arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15427, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15428; public Formatter(java.io.File arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15428, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15429; public Formatter(java.io.File arg0, java.lang.String arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15429, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15430; public Formatter(java.io.File arg0, java.lang.String arg1, java.util.Locale arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15430, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15431; public Formatter(java.io.PrintStream arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15431, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15432; public Formatter(java.io.OutputStream arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15432, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Formatter15433; public Formatter(java.io.OutputStream arg0, java.lang.String arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Formatter.staticClass, global::java.util.Formatter._Formatter15433, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.Formatter.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/Formatter")); global::java.util.Formatter._toString15412 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "toString", "()Ljava/lang/String;"); global::java.util.Formatter._format15413 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "format", "(Ljava/util/Locale;Ljava/lang/String;[Ljava/lang/Object;)Ljava/util/Formatter;"); global::java.util.Formatter._format15414 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/util/Formatter;"); global::java.util.Formatter._out15415 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "@out", "()Ljava/lang/Appendable;"); global::java.util.Formatter._flush15416 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "flush", "()V"); global::java.util.Formatter._close15417 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "close", "()V"); global::java.util.Formatter._locale15418 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "locale", "()Ljava/util/Locale;"); global::java.util.Formatter._ioException15419 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "ioException", "()Ljava/io/IOException;"); global::java.util.Formatter._Formatter15420 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/io/OutputStream;Ljava/lang/String;Ljava/util/Locale;)V"); global::java.util.Formatter._Formatter15421 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "()V"); global::java.util.Formatter._Formatter15422 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/lang/Appendable;)V"); global::java.util.Formatter._Formatter15423 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/util/Locale;)V"); global::java.util.Formatter._Formatter15424 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/lang/Appendable;Ljava/util/Locale;)V"); global::java.util.Formatter._Formatter15425 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/lang/String;)V"); global::java.util.Formatter._Formatter15426 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V"); global::java.util.Formatter._Formatter15427 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/util/Locale;)V"); global::java.util.Formatter._Formatter15428 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/io/File;)V"); global::java.util.Formatter._Formatter15429 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/io/File;Ljava/lang/String;)V"); global::java.util.Formatter._Formatter15430 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/io/File;Ljava/lang/String;Ljava/util/Locale;)V"); global::java.util.Formatter._Formatter15431 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/io/PrintStream;)V"); global::java.util.Formatter._Formatter15432 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/io/OutputStream;)V"); global::java.util.Formatter._Formatter15433 = @__env.GetMethodIDNoThrow(global::java.util.Formatter.staticClass, "<init>", "(Ljava/io/OutputStream;Ljava/lang/String;)V"); } } }
// // http://code.google.com/p/servicestack/wiki/TypeSerializer // ServiceStack.Text: .NET C# POCO Type Text Serializer. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2011 Liquidbit Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Globalization; using System.IO; using System.Text; using ServiceStack.Text.Common; namespace ServiceStack.Text.Json { internal class JsonTypeSerializer : ITypeSerializer { public static ITypeSerializer Instance = new JsonTypeSerializer(); public string TypeAttrInObject { get { return "{\"__type\":"; } } public static readonly bool[] WhiteSpaceFlags = new bool[(int)' ' + 1]; static JsonTypeSerializer() { WhiteSpaceFlags[(int)' '] = true; WhiteSpaceFlags[(int)'\t'] = true; WhiteSpaceFlags[(int)'\r'] = true; WhiteSpaceFlags[(int)'\n'] = true; } public WriteObjectDelegate GetWriteFn<T>() { return JsonWriter<T>.WriteFn(); } public WriteObjectDelegate GetWriteFn(Type type) { return JsonWriter.GetWriteFn(type); } public TypeInfo GetTypeInfo(Type type) { return JsonWriter.GetTypeInfo(type); } /// <summary> /// Shortcut escape when we're sure value doesn't contain any escaped chars /// </summary> /// <param name="writer"></param> /// <param name="value"></param> public void WriteRawString(TextWriter writer, string value) { writer.Write(JsWriter.QuoteChar); writer.Write(value); writer.Write(JsWriter.QuoteChar); } public void WritePropertyName(TextWriter writer, string value) { if (JsState.WritingKeyCount > 0) { writer.Write(JsWriter.EscapedQuoteString); writer.Write(value); writer.Write(JsWriter.EscapedQuoteString); } else { WriteRawString(writer, value); } } public void WriteString(TextWriter writer, string value) { JsonUtils.WriteString(writer, value); } public void WriteBuiltIn(TextWriter writer, object value) { if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar); WriteRawString(writer, value.ToString()); if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar); } public void WriteObjectString(TextWriter writer, object value) { JsonUtils.WriteString(writer, value != null ? value.ToString() : null); } public void WriteException(TextWriter writer, object value) { WriteString(writer, ((Exception)value).Message); } public void WriteDateTime(TextWriter writer, object oDateTime) { WriteRawString(writer, DateTimeSerializer.ToWcfJsonDate((DateTime)oDateTime)); } public void WriteNullableDateTime(TextWriter writer, object dateTime) { if (dateTime == null) writer.Write( JsonUtils.Null ); else WriteDateTime(writer, dateTime); } public void WriteGuid(TextWriter writer, object oValue) { WriteRawString(writer, ((Guid)oValue).ToString("N")); } public void WriteNullableGuid(TextWriter writer, object oValue) { if (oValue == null) return; WriteRawString(writer, ((Guid)oValue).ToString("N")); } public void WriteBytes(TextWriter writer, object oByteValue) { if (oByteValue == null) return; WriteRawString(writer, Convert.ToBase64String((byte[])oByteValue)); } public void WriteChar(TextWriter writer, object charValue) { if (charValue == null) writer.Write(JsonUtils.Null); else WriteRawString(writer, ((char)charValue).ToString(CultureInfo.InvariantCulture)); } public void WriteByte(TextWriter writer, object byteValue) { if (byteValue == null) writer.Write(JsonUtils.Null); else writer.Write((byte)byteValue); } public void WriteInt16(TextWriter writer, object intValue) { if (intValue == null) writer.Write(JsonUtils.Null); else writer.Write((short)intValue); } public void WriteUInt16(TextWriter writer, object intValue) { if (intValue == null) writer.Write(JsonUtils.Null); else writer.Write((ushort)intValue); } public void WriteInt32(TextWriter writer, object intValue) { if (intValue == null) writer.Write(JsonUtils.Null); else writer.Write((int)intValue); } public void WriteUInt32(TextWriter writer, object uintValue) { if (uintValue == null) writer.Write(JsonUtils.Null); else writer.Write((uint)uintValue); } public void WriteInt64(TextWriter writer, object integerValue) { if (integerValue == null) writer.Write(JsonUtils.Null); else writer.Write((long)integerValue); } public void WriteUInt64(TextWriter writer, object ulongValue) { if (ulongValue == null) { writer.Write(JsonUtils.Null); } else writer.Write((ulong)ulongValue); } public void WriteBool(TextWriter writer, object boolValue) { if (boolValue == null) writer.Write(JsonUtils.Null); else writer.Write(((bool)boolValue) ? JsonUtils.True : JsonUtils.False); } public void WriteFloat(TextWriter writer, object floatValue) { if (floatValue == null) writer.Write(JsonUtils.Null); else { var floatVal = (float)floatValue; if (Equals(floatVal, float.MaxValue) || Equals(floatVal, float.MinValue)) writer.Write(floatVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(floatVal.ToString(CultureInfo.InvariantCulture)); } } public void WriteDouble(TextWriter writer, object doubleValue) { if (doubleValue == null) writer.Write(JsonUtils.Null); else { var doubleVal = (double)doubleValue; if (Equals(doubleVal, double.MaxValue) || Equals(doubleVal, double.MinValue)) writer.Write(doubleVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(doubleVal.ToString(CultureInfo.InvariantCulture)); } } public void WriteDecimal(TextWriter writer, object decimalValue) { if (decimalValue == null) writer.Write(JsonUtils.Null); else writer.Write(((decimal)decimalValue).ToString(CultureInfo.InvariantCulture)); } public void WriteEnum(TextWriter writer, object enumValue) { if (enumValue == null) return; WriteRawString(writer, enumValue.ToString()); } public void WriteEnumFlags(TextWriter writer, object enumFlagValue) { if (enumFlagValue == null) return; var intVal = (int)enumFlagValue; writer.Write(intVal); } public void WriteLinqBinary(TextWriter writer, object linqBinaryValue) { #if !MONOTOUCH && !SILVERLIGHT && !XBOX WriteRawString(writer, Convert.ToBase64String(((System.Data.Linq.Binary)linqBinaryValue).ToArray())); #endif } public ParseStringDelegate GetParseFn<T>() { return JsonReader.Instance.GetParseFn<T>(); } public ParseStringDelegate GetParseFn(Type type) { return JsonReader.GetParseFn(type); } public string ParseRawString(string value) { if (String.IsNullOrEmpty(value)) return value; return value[0] == JsonUtils.QuoteChar && value[value.Length - 1] == JsonUtils.QuoteChar && value.Length > 1 ? value.Substring(1, value.Length - 2) : value; } public string ParseString(string value) { return string.IsNullOrEmpty(value) ? value : ParseRawString(value); } static readonly char[] IsSafeJsonChars = new[] { JsonUtils.QuoteChar, JsonUtils.EscapeChar }; internal static string ParseJsonString(string json, ref int index) { var jsonLength = json.Length; for (; index < json.Length; index++) { var ch = json[index]; if (ch >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[ch]) break; } //Whitespace inline if (json[index] == JsonUtils.QuoteChar) { index++; //MicroOp: See if we can short-circuit evaluation (to avoid StringBuilder) var strEndPos = json.IndexOfAny(IsSafeJsonChars, index); if (strEndPos == -1) return json.Substring(index, jsonLength - index); if (json[strEndPos] == JsonUtils.QuoteChar) { var potentialValue = json.Substring(index, strEndPos - index); index = strEndPos + 1; return potentialValue; } } var sb = new StringBuilder(jsonLength); char c; while (true) { if (index == jsonLength) break; c = json[index++]; if (c == JsonUtils.QuoteChar) break; if (c == '\\') { if (index == jsonLength) { break; } c = json[index++]; switch (c) { case '"': sb.Append('"'); break; case '\\': sb.Append('\\'); break; case '/': sb.Append('/'); break; case 'b': sb.Append('\b'); break; case 'f': sb.Append('\f'); break; case 'n': sb.Append('\n'); break; case 'r': sb.Append('\r'); break; case 't': sb.Append('\t'); break; case 'u': var remainingLength = jsonLength - index; if (remainingLength >= 4) { var unicodeString = json.Substring(index, 4); var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber); sb.Append(ConvertFromUtf32((int)unicodeIntVal)); index += 4; } else { break; } break; } } else { sb.Append(c); } } var strValue = sb.ToString(); return strValue == JsonUtils.Null ? null : strValue; } /// <summary> /// Since Silverlight doesn't have char.ConvertFromUtf32() so putting Mono's implemenation inline. /// </summary> /// <param name="utf32"></param> /// <returns></returns> private static string ConvertFromUtf32(int utf32) { if (utf32 < 0 || utf32 > 0x10FFFF) throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF."); if (0xD800 <= utf32 && utf32 <= 0xDFFF) throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range."); if (utf32 < 0x10000) return new string((char)utf32, 1); utf32 -= 0x10000; return new string(new[] {(char) ((utf32 >> 10) + 0xD800), (char) (utf32 % 0x0400 + 0xDC00)}); } private static void EatWhitespace(string json, ref int index) { int c; for (; index < json.Length; index++) { c = json[index]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) { break; } } } public string EatTypeValue(string value, ref int i) { return EatValue(value, ref i); } public bool EatMapStartChar(string value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline return value[i++] == JsWriter.MapStartChar; } public string EatMapKey(string value, ref int i) { return ParseJsonString(value, ref i); } public bool EatMapKeySeperator(string value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline if (value.Length == i) return false; return value[i++] == JsWriter.MapKeySeperator; } public bool EatItemSeperatorOrMapEndChar(string value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline if (i == value.Length) return false; var success = value[i] == JsWriter.ItemSeperator || value[i] == JsWriter.MapEndChar; i++; if (success) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline } return success; } public string EatValue(string value, ref int i) { var valueLength = value.Length; if (i == valueLength) return null; for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline var tokenStartPos = i; var valueChar = value[i]; var withinQuotes = false; var endsToEat = 1; switch (valueChar) { //If we are at the end, return. case JsWriter.ItemSeperator: case JsWriter.MapEndChar: return null; //Is Within Quotes, i.e. "..." case JsWriter.QuoteChar: return ParseJsonString(value, ref i); //Is Type/Map, i.e. {...} case JsWriter.MapStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar && value[i - 1] != JsonUtils.EscapeChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.MapStartChar) endsToEat++; if (valueChar == JsWriter.MapEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); //Is List, i.e. [...] case JsWriter.ListStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar && value[i - 1] != JsonUtils.EscapeChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.ListStartChar) endsToEat++; if (valueChar == JsWriter.ListEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); } //Is Value while (++i < valueLength) { valueChar = value[i]; if (valueChar == JsWriter.ItemSeperator || valueChar == JsWriter.MapEndChar //If it doesn't have quotes it's either a keyword or number so also has a ws boundary || (valueChar < WhiteSpaceFlags.Length && WhiteSpaceFlags[valueChar]) ) { break; } } var strValue = value.Substring(tokenStartPos, i - tokenStartPos); return strValue == JsonUtils.Null ? null : strValue; } } }
// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using CorDebugInterop; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudio.OLE.Interop; using nanoFramework.Tools.Debugger; using System; using System.Collections; using System.Runtime.InteropServices; namespace nanoFramework.Tools.VisualStudio.Extension { public class DebugPort : IDebugPort2, IDebugPortEx2, IDebugPortNotify2, IConnectionPointContainer { private Guid _guid; private ArrayList _alProcesses; private string _name; private ConnectionPoint _cpDebugPortEvents2; //This can't be shared with other debugPorts, for remote attaching to multiple processes....??? protected uint _pidNext; public NanoDeviceBase Device { get; protected set; } public DebugPort(NanoDeviceBase device, DebugPortSupplier portSupplier) { _name = device.Description; DebugPortSupplier = portSupplier; Device = device; _cpDebugPortEvents2 = new ConnectionPoint(this, typeof(IDebugPortEvents2).GUID); _alProcesses = ArrayList.Synchronized(new ArrayList(1)); _pidNext = 1; _guid = Guid.NewGuid(); } public bool ContainsProcess(CorDebugProcess process) { return _alProcesses.Contains(process); } public void RefreshProcesses() { ArrayList processes = new ArrayList(_alProcesses.Count + NanoFrameworkPackage.NanoDeviceCommService.DebugClient.NanoFrameworkDevices.Count); foreach (NanoDeviceBase device in NanoFrameworkPackage.NanoDeviceCommService.DebugClient.NanoFrameworkDevices) { CorDebugProcess process = EnsureProcess(device); processes.Add(process); } for (int i = _alProcesses.Count - 1; i >= 0; i--) { CorDebugProcess process = (CorDebugProcess)_alProcesses[i]; if (!processes.Contains(process)) { RemoveProcess(process); } } } public DebugPortSupplier DebugPortSupplier { [System.Diagnostics.DebuggerHidden]get; protected set; } public void AddProcess(CorDebugProcess process) { if(!_alProcesses.Contains( process )) { _alProcesses.Add( process ); } } public CorDebugProcess EnsureProcess(NanoDeviceBase device) { CorDebugProcess process = ProcessFromPortDefinition(device); if (process == null) { process = new CorDebugProcess(this, device); uint pid = _pidNext++; process.SetPid(pid); AddProcess(process); } return process; } private void RemoveProcess(CorDebugProcess process) { ((ICorDebugProcess)process).Terminate(0); _alProcesses.Remove(process); } public void RemoveProcess(NanoDeviceBase device) { CorDebugProcess process = ProcessFromPortDefinition(device); if (process != null) { RemoveProcess(process); } } public bool AreProcessIdEqual(AD_PROCESS_ID pid1, AD_PROCESS_ID pid2) { if (pid1.ProcessIdType != pid2.ProcessIdType) return false; switch ((AD_PROCESS_ID_TYPE) pid1.ProcessIdType) { case AD_PROCESS_ID_TYPE.AD_PROCESS_ID_SYSTEM: return pid1.dwProcessId == pid2.dwProcessId; case AD_PROCESS_ID_TYPE.AD_PROCESS_ID_GUID: return Guid.Equals(pid1.guidProcessId, pid2.guidProcessId); default: return false; } } public Guid PortId { get { return _guid; } } public string Name { [System.Diagnostics.DebuggerHidden] get { return _name; } } public CorDebugProcess GetDeviceProcess(string deviceName, int eachSecondRetryMaxCount) { if (string.IsNullOrEmpty(deviceName)) throw new Exception("DebugPort.GetDeviceProcess() called with no argument"); NanoFrameworkPackage.MessageCentre.StartProgressMessage(String.Format(Resources.ResourceStrings.StartDeviceSearch, deviceName, eachSecondRetryMaxCount)); CorDebugProcess process = this.InternalGetDeviceProcess(deviceName); if (process != null) return process; if (eachSecondRetryMaxCount < 0) eachSecondRetryMaxCount = 0; for (int i = 0; i < eachSecondRetryMaxCount && process == null; i++) { System.Threading.Thread.Sleep(1000); process = this.InternalGetDeviceProcess(deviceName); } NanoFrameworkPackage.MessageCentre.StopProgressMessage(String.Format((process == null) ? Resources.ResourceStrings.DeviceFound : Resources.ResourceStrings.DeviceNotFound, deviceName)); return process; } public CorDebugProcess GetDeviceProcess(string deviceName) { if (string.IsNullOrEmpty(deviceName)) throw new Exception("DebugPort.GetDeviceProcess() called with no argument"); return this.InternalGetDeviceProcess(deviceName); } private CorDebugProcess InternalGetDeviceProcess(string deviceName) { CorDebugProcess process = null; RefreshProcesses(); for(int i = 0; i < _alProcesses.Count; i++) { CorDebugProcess processT = (CorDebugProcess)_alProcesses[i]; NanoDeviceBase device = processT.Device; if (String.Compare(GetDeviceName(device), deviceName, true) == 0) { process = processT; break; } } // TODO //if(m_portFilter == PortFilter.TcpIp && process == null) //{ // process = EnsureProcess(PortDefinition.CreateInstanceForTcp(deviceName)); //} return process; } public string GetDeviceName(NanoDeviceBase device) { return device.Description; } private bool ArePortEntriesEqual(NanoDeviceBase device1, NanoDeviceBase device2) { if (device1.Description != device2.Description) return false; if (device1.GetType() != device2.GetType()) return false; return true; } private CorDebugProcess ProcessFromPortDefinition(NanoDeviceBase device) { foreach (CorDebugProcess process in _alProcesses) { if (ArePortEntriesEqual(device, process.Device)) return process; } return null; } private CorDebugProcess GetProcess( AD_PROCESS_ID ProcessId ) { AD_PROCESS_ID pid; foreach (CorDebugProcess process in _alProcesses) { pid = process.PhysicalProcessId; if (AreProcessIdEqual(ProcessId, pid)) { return process; } } return null; } private CorDebugProcess GetProcess( IDebugProgramNode2 programNode ) { AD_PROCESS_ID[] pids = new AD_PROCESS_ID[1]; programNode.GetHostPid( pids ); return GetProcess( pids[0] ); } private CorDebugAppDomain GetAppDomain( IDebugProgramNode2 programNode ) { uint appDomainId; CorDebugProcess process = GetProcess( programNode ); IDebugCOMPlusProgramNode2 node = (IDebugCOMPlusProgramNode2)programNode; node.GetAppDomainId( out appDomainId ); CorDebugAppDomain appDomain = process.GetAppDomainFromId( appDomainId ); return appDomain; } private void SendProgramEvent(IDebugProgramNode2 programNode, enum_EVENTATTRIBUTES attributes, Guid iidEvent) { CorDebugProcess process = GetProcess( programNode ); CorDebugAppDomain appDomain = GetAppDomain( programNode ); IDebugEvent2 evt = new DebugEvent((uint) attributes); foreach (IDebugPortEvents2 dpe in _cpDebugPortEvents2.Sinks) { dpe.Event(this.DebugPortSupplier.CoreServer, this, (IDebugProcess2)process, (IDebugProgram2) appDomain, evt, ref iidEvent); } } #region IDebugPort2 Members int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetPortId(out Guid pguidPort) { pguidPort = PortId; return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetProcess(AD_PROCESS_ID ProcessId, out IDebugProcess2 ppProcess) { ppProcess = ((DebugPort)this).GetProcess( ProcessId ); return COM_HResults.BOOL_TO_HRESULT_FAIL( ppProcess != null ); } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetPortSupplier(out IDebugPortSupplier2 ppSupplier) { ppSupplier = DebugPortSupplier; return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetPortRequest(out IDebugPortRequest2 ppRequest) { ppRequest = null; return COM_HResults.E_NOTIMPL; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.EnumProcesses(out IEnumDebugProcesses2 ppEnum) { RefreshProcesses(); ppEnum = new CorDebugEnum(_alProcesses, typeof(IDebugProcess2), typeof(IEnumDebugProcesses2)); return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPort2.GetPortName(out string pbstrName) { pbstrName = _name; return COM_HResults.S_OK; } #endregion #region IDebugPortEx2 Members int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.GetProgram(IDebugProgramNode2 pProgramNode, out IDebugProgram2 ppProgram) { CorDebugAppDomain appDomain = GetAppDomain( pProgramNode ); ppProgram = appDomain; return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.LaunchSuspended(string pszExe, string pszArgs, string pszDir, string bstrEnv, uint hStdInput, uint hStdOutput, uint hStdError, out IDebugProcess2 ppPortProcess) { System.Windows.Forms.MessageBox.Show("Hello from LaunchSuspended!"); ppPortProcess = null; return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.TerminateProcess(IDebugProcess2 pPortProcess) { return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.ResumeProcess(IDebugProcess2 pPortProcess) { return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.CanTerminateProcess(IDebugProcess2 pPortProcess) { return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortEx2.GetPortProcessId(out uint pdwProcessId) { pdwProcessId = 0; return COM_HResults.S_OK; } #endregion #region IDebugPortNotify2 Members int Microsoft.VisualStudio.Debugger.Interop.IDebugPortNotify2.AddProgramNode(IDebugProgramNode2 pProgramNode) { SendProgramEvent(pProgramNode, enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, typeof(IDebugProgramCreateEvent2).GUID); return COM_HResults.S_OK; } int Microsoft.VisualStudio.Debugger.Interop.IDebugPortNotify2.RemoveProgramNode(IDebugProgramNode2 pProgramNode) { SendProgramEvent(pProgramNode, enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS, typeof(IDebugProgramDestroyEvent2).GUID); return COM_HResults.S_OK; } #endregion #region IConnectionPointContainer Members void Microsoft.VisualStudio.OLE.Interop.IConnectionPointContainer.FindConnectionPoint(ref Guid riid, out IConnectionPoint ppCP) { if (riid.Equals(typeof(IDebugPortEvents2).GUID)) { ppCP = _cpDebugPortEvents2; } else { ppCP = null; Marshal.ThrowExceptionForHR(COM_HResults.CONNECT_E_NOCONNECTION); } } void Microsoft.VisualStudio.OLE.Interop.IConnectionPointContainer.EnumConnectionPoints(out IEnumConnectionPoints ppEnum) { throw new NotImplementedException(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { /// <summary> /// Named pipe server /// </summary> public sealed partial class NamedPipeServerStream : PipeStream { [SecurityCritical] private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, HandleInheritability inheritability) { Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty"); Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction"); Debug.Assert(inBufferSize >= 0, "inBufferSize is negative"); Debug.Assert(outBufferSize >= 0, "outBufferSize is negative"); Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid"); Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range"); string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName); // Make sure the pipe name isn't one of our reserved names for anonymous pipes. if (String.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } int openMode = ((int)direction) | (maxNumberOfServerInstances == 1 ? Interop.Kernel32.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) | (int)options; // We automatically set the ReadMode to match the TransmissionMode. int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1; // Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254). if (maxNumberOfServerInstances == MaxAllowedServerInstances) { maxNumberOfServerInstances = 255; } Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability); SafePipeHandle handle = Interop.Kernel32.CreateNamedPipe(fullPipeName, openMode, pipeModes, maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs); if (handle.IsInvalid) { throw Win32Marshal.GetExceptionForLastWin32Error(); } InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0); } // This will wait until the client calls Connect(). If we return from this method, we guarantee that // the client has returned from its Connect call. The client may have done so before this method // was called (but not before this server is been created, or, if we were servicing another client, // not before we called Disconnect), in which case, there may be some buffer already in the pipe waiting // for us to read. See NamedPipeClientStream.Connect for more information. [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] public void WaitForConnection() { CheckConnectOperationsServerWithHandle(); if (IsAsync) { WaitForConnectionCoreAsync(CancellationToken.None).GetAwaiter().GetResult(); } else { if (!Interop.Kernel32.ConnectNamedPipe(InternalHandle, IntPtr.Zero)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_PIPE_CONNECTED) { throw Win32Marshal.GetExceptionForWin32Error(errorCode); } // pipe already connected if (errorCode == Interop.Errors.ERROR_PIPE_CONNECTED && State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } // If we reach here then a connection has been established. This can happen if a client // connects in the interval between the call to CreateNamedPipe and the call to ConnectNamedPipe. // In this situation, there is still a good connection between client and server, even though // ConnectNamedPipe returns zero. } State = PipeState.Connected; } } public Task WaitForConnectionAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (!IsAsync) { return Task.Factory.StartNew(s => ((NamedPipeServerStream)s).WaitForConnection(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } return WaitForConnectionCoreAsync(cancellationToken); } [SecurityCritical] public void Disconnect() { CheckDisconnectOperations(); // Disconnect the pipe. if (!Interop.Kernel32.DisconnectNamedPipe(InternalHandle)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } State = PipeState.Disconnected; } // Gets the username of the connected client. Not that we will not have access to the client's // username until it has written at least once to the pipe (and has set its impersonationLevel // argument appropriately). [SecurityCritical] public String GetImpersonationUserName() { CheckWriteOperations(); StringBuilder userName = new StringBuilder(Interop.Kernel32.CREDUI_MAX_USERNAME_LENGTH + 1); if (!Interop.Kernel32.GetNamedPipeHandleState(InternalHandle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, userName, userName.Capacity)) { throw WinIOError(Marshal.GetLastWin32Error()); } return userName.ToString(); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- // This method calls a delegate while impersonating the client. Note that we will not have // access to the client's security token until it has written at least once to the pipe // (and has set its impersonationLevel argument appropriately). public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker) { CheckWriteOperations(); ExecuteHelper execHelper = new ExecuteHelper(impersonationWorker, InternalHandle); RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, execHelper); // now handle win32 impersonate/revert specific errors by throwing corresponding exceptions if (execHelper._impersonateErrorCode != 0) { throw WinIOError(execHelper._impersonateErrorCode); } else if (execHelper._revertImpersonateErrorCode != 0) { throw WinIOError(execHelper._revertImpersonateErrorCode); } } // the following are needed for CER private static RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(ImpersonateAndTryCode); private static RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(RevertImpersonationOnBackout); private static void ImpersonateAndTryCode(Object helper) { ExecuteHelper execHelper = (ExecuteHelper)helper; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (Interop.Advapi32.ImpersonateNamedPipeClient(execHelper._handle)) { execHelper._mustRevert = true; } else { execHelper._impersonateErrorCode = Marshal.GetLastWin32Error(); } } if (execHelper._mustRevert) { // impersonate passed so run user code execHelper._userCode(); } } private static void RevertImpersonationOnBackout(Object helper, bool exceptionThrown) { ExecuteHelper execHelper = (ExecuteHelper)helper; if (execHelper._mustRevert) { if (!Interop.Advapi32.RevertToSelf()) { execHelper._revertImpersonateErrorCode = Marshal.GetLastWin32Error(); } } } internal class ExecuteHelper { internal PipeStreamImpersonationWorker _userCode; internal SafePipeHandle _handle; internal bool _mustRevert; internal int _impersonateErrorCode; internal int _revertImpersonateErrorCode; [SecurityCritical] internal ExecuteHelper(PipeStreamImpersonationWorker userCode, SafePipeHandle handle) { _userCode = userCode; _handle = handle; } } // Async version of WaitForConnection. See the comments above for more info. private unsafe Task WaitForConnectionCoreAsync(CancellationToken cancellationToken) { CheckConnectOperationsServerWithHandle(); if (!IsAsync) { throw new InvalidOperationException(SR.InvalidOperation_PipeNotAsync); } var completionSource = new ConnectionCompletionSource(this, cancellationToken); if (!Interop.Kernel32.ConnectNamedPipe(InternalHandle, completionSource.Overlapped)) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case Interop.Errors.ERROR_IO_PENDING: break; // If we are here then the pipe is already connected, or there was an error // so we should unpin and free the overlapped. case Interop.Errors.ERROR_PIPE_CONNECTED: // IOCompletitionCallback will not be called because we completed synchronously. completionSource.ReleaseResources(); if (State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } completionSource.SetCompletedSynchronously(); // We return a cached task instead of TaskCompletionSource's Task allowing the GC to collect it. return Task.CompletedTask; default: completionSource.ReleaseResources(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } // If we are here then connection is pending. completionSource.RegisterForCancellation(); return completionSource.Task; } private void CheckConnectOperationsServerWithHandle() { if (InternalHandle == null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } CheckConnectOperationsServer(); } } }
using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.Data; namespace DataAccess { public class CDataParameterList : ArrayList { /// <summary> /// constructor /// </summary> public CDataParameterList() { //set the lists initial capacity this.Capacity = 25; } /// <summary> /// constructor /// </summary> public CDataParameterList(BaseMaster BaseMstr) { //set the lists initial capacity this.Capacity = 500; //add in standard params from basemstr if (BaseMstr != null) { //use ASP session id NOT DBSession id! AddInputParameter("pi_vSessionID", BaseMstr.ASPSessionID); AddInputParameter("pi_vSessionClientIP", BaseMstr.ClientIP); AddInputParameter("pi_nUserID", BaseMstr.FXUserID); } } public void AddStatusCodeParams() { long lStatusCode = 0; string strStatusComment = ""; AddOutputParameter("po_nStatusCode", lStatusCode); AddOutputParameter("po_vStatusComment", strStatusComment); } /// <summary> /// add a date parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="dtValue"></param> /// <returns></returns> public bool AddInputParameter(string strName, DateTime dtValue) { return AddParameter(strName, dtValue, ParameterDirection.Input); } /// <summary> /// add a string parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="strValue"></param> /// <returns></returns> public bool AddInputParameter(string strName, string strValue) { return AddParameter(strName, strValue, ParameterDirection.Input); } /// <summary> /// add a string parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="strValue"></param> /// <returns></returns> public bool AddInputParameterCLOB(string strName, string strValue) { return AddCLOBParameter(strName, strValue, ParameterDirection.Input); } /// <summary> /// add a long parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="lValue"></param> /// <returns></returns> public bool AddInputParameter(string strName, long lValue) { return AddParameter(strName, lValue, ParameterDirection.Input); } /// <summary> /// add a bool parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="bValue"></param> /// <returns></returns> public bool AddInputParameter(string strName, bool bValue) { return AddParameter(strName, bValue, ParameterDirection.Input); } /// <summary> /// add a double parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="dblValue"></param> /// <returns></returns> public bool AddInputParameter(string strName, double dblValue) { return AddParameter(strName, dblValue, ParameterDirection.Input); } /// <summary> /// add a date parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="dtValue"></param> /// <returns></returns> public bool AddOutputParameter(string strName, DateTime dtValue) { return AddParameter(strName, dtValue, ParameterDirection.Output); } /// <summary> /// add a string parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="strValue"></param> /// <returns></returns> public bool AddOutputParameter(string strName, string strValue) { return AddParameter(strName, strValue, ParameterDirection.Output); } /// <summary> /// add a long parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="lValue"></param> /// <returns></returns> public bool AddOutputParameter(string strName, long lValue) { return AddParameter(strName, lValue, ParameterDirection.Output); } /// <summary> /// add a bool parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="bValue"></param> /// <returns></returns> public bool AddOutputParameter(string strName, bool bValue) { return AddParameter(strName, bValue, ParameterDirection.Output); } /// <summary> /// add a double parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="dblValue"></param> /// <returns></returns> public bool AddOutputParameter(string strName, double dblValue) { return AddParameter(strName, dblValue, ParameterDirection.Output); } /// <summary> /// add a bool parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="bValue"></param> /// <param name="pmDirection"></param> /// <returns></returns> public bool AddParameter(string strName, bool bValue, ParameterDirection pmDirection) { CDataParameter p = new CDataParameter(); p.ParameterName = strName; p.ParameterType = (int)DataParameterType.BoolParameter; p.BoolParameterValue = bValue; p.Direction = pmDirection; base.Add(p); return true; } /// <summary> /// add a double parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="dblValue"></param> /// <param name="pmDirection"></param> /// <returns></returns> public bool AddParameter(string strName, double dblValue, ParameterDirection pmDirection) { CDataParameter p = new CDataParameter(); p.ParameterName = strName; p.ParameterType = (int)DataParameterType.DoubleParameter; p.DoubleParameterValue = dblValue; p.Direction = pmDirection; base.Add(p); return true; } /// <summary> /// add a date parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="dtValue"></param> /// <param name="pmDirection"></param> /// <returns></returns> public bool AddParameter(string strName, DateTime dtValue, ParameterDirection pmDirection) { CDataParameter p = new CDataParameter(); p.ParameterName = strName; if (dtValue.Year < 1800) { dtValue = new System.DateTime(0); } p.DateParameterValue = dtValue; p.ParameterType = (int)DataParameterType.DateParameter; p.Direction = pmDirection; base.Add(p); return true; } /// <summary> /// add a string parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="strValue"></param> /// <param name="pmDirection"></param> /// <returns></returns> public bool AddParameter(string strName, string strValue, ParameterDirection pmDirection) { CDataParameter p = new CDataParameter(); p.ParameterName = strName; p.StringParameterValue = strValue; p.ParameterType = (int)DataParameterType.StringParameter; p.Direction = pmDirection; base.Add(p); return true; } public bool AddCLOBParameter(string strName, string strValue, ParameterDirection pmDirection) { CDataParameter p = new CDataParameter(); p.ParameterName = strName; p.CLOBParameterValue = strValue; p.ParameterType = (int)DataParameterType.CLOBParameter; p.Direction = pmDirection; base.Add(p); return true; } /// <summary> /// add a long parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="lValue"></param> /// <param name="pmDirection"></param> /// <returns></returns> public bool AddParameter(string strName, long lValue, ParameterDirection pmDirection) { CDataParameter p = new CDataParameter(); p.ParameterName = strName; p.LongParameterValue = lValue; p.ParameterType = (int)DataParameterType.LongParameter; p.Direction = pmDirection; base.Add(p); return true; } /// <summary> /// get an item by ID /// </summary> /// <param name="strParameterName"></param> /// <returns></returns> public CDataParameter GetItemByName(string strParameterName) { foreach (CDataParameter parameter in this) { if (parameter.ParameterName.Equals(strParameterName)) { return parameter; } } return null; } /// <summary> /// get an item by index /// </summary> /// <param name="nIndex"></param> /// <returns></returns> public CDataParameter GetItemByIndex(int nIndex) { return (CDataParameter)this[nIndex]; } /// <summary> /// add a parameter to the list /// </summary> /// <param name="parameter"></param> /// <returns></returns> public bool Add(CDataParameter parameter) { if (parameter != null) { this.Add(parameter); } return true; } /// <summary> /// add a blob paramateter /// </summary> /// <param name="strName"></param> /// <param name="byValue"></param> /// <param name="pmDirection"></param> /// <returns></returns> public bool AddBLOBParameter(string strName, byte[] byValue, ParameterDirection pmDirection) { CDataParameter p = new CDataParameter(); p.ParameterName = strName; p.BLOBParameterValue = byValue; p.ParameterType = (int)DataParameterType.BLOBParameter; p.Direction = pmDirection; base.Add(p); return true; } /// <summary> /// add a blob parameter to the list /// </summary> /// <param name="strName"></param> /// <param name="strValue"></param> /// <returns></returns> public bool AddInputParameterBLOB(string strName, byte[] byValue) { return AddBLOBParameter(strName, byValue, ParameterDirection.Input); } /// <summary> /// add a blob parameter to the list from an input control /// </summary> /// <param name="strName"></param> /// <param name="strValue"></param> /// <returns></returns> public bool AddInputParameterBLOB(string strName, System.Web.UI.HtmlControls.HtmlInputFile FileInput) { //get the contents of the file as a stream System.IO.Stream stream = FileInput.PostedFile.InputStream; //read the stream to a memory stream byte[] buffer = new byte[16 * 1024]; System.IO.MemoryStream ms = new System.IO.MemoryStream(); int nRead; while ((nRead = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, nRead); } //get a byte array of the full file, this is what we store in oracle byte[] byFile = ms.ToArray(); //add the blob paramater return AddBLOBParameter(strName, byFile, ParameterDirection.Input); } } }
namespace MagiWol { partial class MainForm { /// <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(MainForm)); this.mnu = new System.Windows.Forms.ToolStrip(); this.mnuNew = new System.Windows.Forms.ToolStripButton(); this.mnuOpenRoot = new System.Windows.Forms.ToolStripSplitButton(); this.mnuOpen = new System.Windows.Forms.ToolStripMenuItem(); this.mnuImport = new System.Windows.Forms.ToolStripMenuItem(); this.mnuImport0 = new System.Windows.Forms.ToolStripSeparator(); this.mnuSaveRoot = new System.Windows.Forms.ToolStripSplitButton(); this.mnuSave = new System.Windows.Forms.ToolStripMenuItem(); this.mnuSaveAs = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.mnuCut = new System.Windows.Forms.ToolStripButton(); this.mnuCopy = new System.Windows.Forms.ToolStripButton(); this.mnuPaste = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.mnuAdd = new System.Windows.Forms.ToolStripButton(); this.mnuChange = new System.Windows.Forms.ToolStripButton(); this.mnuRemove = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.mnuWake = new System.Windows.Forms.ToolStripButton(); this.mnuWakeAll = new System.Windows.Forms.ToolStripButton(); this.mnuApp = new System.Windows.Forms.ToolStripDropDownButton(); this.mnuAppOptions = new System.Windows.Forms.ToolStripMenuItem(); this.mnuApp0 = new System.Windows.Forms.ToolStripSeparator(); this.mnuAppFeedback = new System.Windows.Forms.ToolStripMenuItem(); this.mnuAppUpgrade = new System.Windows.Forms.ToolStripMenuItem(); this.mnuApp1 = new System.Windows.Forms.ToolStripSeparator(); this.mnuAppAbout = new System.Windows.Forms.ToolStripMenuItem(); this.mnuQuickWake = new System.Windows.Forms.ToolStripButton(); this.list = new System.Windows.Forms.ListView(); this.list_Name = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.list_MAC = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.list_Notes = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.mnxList = new System.Windows.Forms.ContextMenuStrip(this.components); this.mnxListCut = new System.Windows.Forms.ToolStripMenuItem(); this.mnxListCopy = new System.Windows.Forms.ToolStripMenuItem(); this.mnxListPaste = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripSeparator(); this.mnxListEditSelectAll = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator(); this.mnxListAdd = new System.Windows.Forms.ToolStripMenuItem(); this.mnxListChange = new System.Windows.Forms.ToolStripMenuItem(); this.mnxListRemove = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator(); this.mnxListActionWake = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem10 = new System.Windows.Forms.ToolStripSeparator(); this.mnxListQuickWake = new System.Windows.Forms.ToolStripMenuItem(); this.timerEnableDisable = new System.Windows.Forms.Timer(this.components); this.tmrReSort = new System.Windows.Forms.Timer(this.components); this.bwCheckForUpgrade = new System.ComponentModel.BackgroundWorker(); this.mnu.SuspendLayout(); this.mnxList.SuspendLayout(); this.SuspendLayout(); // // mnu // this.mnu.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.mnu.ImageScalingSize = new System.Drawing.Size(20, 20); this.mnu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuNew, this.mnuOpenRoot, this.mnuSaveRoot, this.toolStripSeparator1, this.mnuCut, this.mnuCopy, this.mnuPaste, this.toolStripSeparator3, this.mnuAdd, this.mnuChange, this.mnuRemove, this.toolStripSeparator2, this.mnuWake, this.mnuWakeAll, this.mnuApp, this.mnuQuickWake}); this.mnu.Location = new System.Drawing.Point(0, 0); this.mnu.Name = "mnu"; this.mnu.Padding = new System.Windows.Forms.Padding(1, 0, 1, 0); this.mnu.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.mnu.Size = new System.Drawing.Size(742, 27); this.mnu.Stretch = true; this.mnu.TabIndex = 1; // // mnuNew // this.mnuNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuNew.Image = global::MagiWol.Properties.Resources.mnuNew_16; this.mnuNew.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuNew.Name = "mnuNew"; this.mnuNew.Size = new System.Drawing.Size(24, 24); this.mnuNew.Text = "New"; this.mnuNew.ToolTipText = "New file (Ctrl+N)"; this.mnuNew.Click += new System.EventHandler(this.mnuNew_Click); // // mnuOpenRoot // this.mnuOpenRoot.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuOpenRoot.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuOpen, this.mnuImport, this.mnuImport0}); this.mnuOpenRoot.Image = global::MagiWol.Properties.Resources.mnuOpen_16; this.mnuOpenRoot.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuOpenRoot.Name = "mnuOpenRoot"; this.mnuOpenRoot.Size = new System.Drawing.Size(39, 24); this.mnuOpenRoot.Tag = "mnuOpen"; this.mnuOpenRoot.Text = "Open"; this.mnuOpenRoot.ToolTipText = "Open file (Ctrl+O)"; this.mnuOpenRoot.ButtonClick += new System.EventHandler(this.mnuOpen_Click); // // mnuOpen // this.mnuOpen.Image = global::MagiWol.Properties.Resources.mnuOpen_16; this.mnuOpen.Name = "mnuOpen"; this.mnuOpen.ShortcutKeyDisplayString = "Ctrl+O"; this.mnuOpen.Size = new System.Drawing.Size(173, 26); this.mnuOpen.Text = "&Open"; this.mnuOpen.Click += new System.EventHandler(this.mnuOpen_Click); // // mnuImport // this.mnuImport.Image = global::MagiWol.Properties.Resources.mnuImport_16; this.mnuImport.Name = "mnuImport"; this.mnuImport.Size = new System.Drawing.Size(173, 26); this.mnuImport.Text = "&Import"; this.mnuImport.Click += new System.EventHandler(this.mnuImport_Click); // // mnuImport0 // this.mnuImport0.Name = "mnuImport0"; this.mnuImport0.Size = new System.Drawing.Size(170, 6); // // mnuSaveRoot // this.mnuSaveRoot.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuSaveRoot.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuSave, this.mnuSaveAs}); this.mnuSaveRoot.Image = global::MagiWol.Properties.Resources.mnuSave_16; this.mnuSaveRoot.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuSaveRoot.Name = "mnuSaveRoot"; this.mnuSaveRoot.Size = new System.Drawing.Size(39, 24); this.mnuSaveRoot.Tag = "mnuSave"; this.mnuSaveRoot.Text = "Save"; this.mnuSaveRoot.ToolTipText = "Save file (Ctrl+S)"; this.mnuSaveRoot.ButtonClick += new System.EventHandler(this.mnuSave_Click); // // mnuSave // this.mnuSave.Image = global::MagiWol.Properties.Resources.mnuSave_16; this.mnuSave.Name = "mnuSave"; this.mnuSave.ShortcutKeyDisplayString = "Ctrl+S"; this.mnuSave.Size = new System.Drawing.Size(223, 26); this.mnuSave.Text = "&Save"; this.mnuSave.Click += new System.EventHandler(this.mnuSave_Click); // // mnuSaveAs // this.mnuSaveAs.Name = "mnuSaveAs"; this.mnuSaveAs.ShortcutKeyDisplayString = "Ctrl+Shift+S"; this.mnuSaveAs.Size = new System.Drawing.Size(223, 26); this.mnuSaveAs.Text = "Save &as"; this.mnuSaveAs.Click += new System.EventHandler(this.mnuSaveAs_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 27); // // mnuCut // this.mnuCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuCut.Image = global::MagiWol.Properties.Resources.mnuCut_16; this.mnuCut.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuCut.Name = "mnuCut"; this.mnuCut.Size = new System.Drawing.Size(24, 24); this.mnuCut.Text = "Cut"; this.mnuCut.ToolTipText = "Cut (Ctrl+X)"; this.mnuCut.Click += new System.EventHandler(this.mnuCut_Click); // // mnuCopy // this.mnuCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuCopy.Image = global::MagiWol.Properties.Resources.mnuCopy_16; this.mnuCopy.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuCopy.Name = "mnuCopy"; this.mnuCopy.Size = new System.Drawing.Size(24, 24); this.mnuCopy.Text = "Copy"; this.mnuCopy.ToolTipText = "Copy (Ctrl+C)"; this.mnuCopy.Click += new System.EventHandler(this.mnuCopy_Click); // // mnuPaste // this.mnuPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuPaste.Image = global::MagiWol.Properties.Resources.mnuPaste_16; this.mnuPaste.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuPaste.Name = "mnuPaste"; this.mnuPaste.Size = new System.Drawing.Size(24, 24); this.mnuPaste.Text = "Paste"; this.mnuPaste.ToolTipText = "Paste (Ctrl+V)"; this.mnuPaste.Click += new System.EventHandler(this.mnuPaste_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(6, 27); // // mnuAdd // this.mnuAdd.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuAdd.Image = global::MagiWol.Properties.Resources.mnuAdd_16; this.mnuAdd.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuAdd.Name = "mnuAdd"; this.mnuAdd.Size = new System.Drawing.Size(24, 24); this.mnuAdd.Text = "Add"; this.mnuAdd.ToolTipText = "Add (Ins)"; this.mnuAdd.Click += new System.EventHandler(this.mnuAdd_Click); // // mnuChange // this.mnuChange.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuChange.Image = global::MagiWol.Properties.Resources.mnuEdit_16; this.mnuChange.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuChange.Name = "mnuChange"; this.mnuChange.Size = new System.Drawing.Size(24, 24); this.mnuChange.Tag = "mnuEdit"; this.mnuChange.Text = "Change"; this.mnuChange.ToolTipText = "Change (F4)"; this.mnuChange.Click += new System.EventHandler(this.mnuChange_Click); // // mnuRemove // this.mnuRemove.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuRemove.Image = global::MagiWol.Properties.Resources.mnuSave_16; this.mnuRemove.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuRemove.Name = "mnuRemove"; this.mnuRemove.Size = new System.Drawing.Size(24, 24); this.mnuRemove.Text = "Remove"; this.mnuRemove.ToolTipText = "Remove (Del)"; this.mnuRemove.Click += new System.EventHandler(this.mnuRemove_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 27); // // mnuWake // this.mnuWake.Image = global::MagiWol.Properties.Resources.mnuWake_16; this.mnuWake.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuWake.Name = "mnuWake"; this.mnuWake.Size = new System.Drawing.Size(128, 24); this.mnuWake.Text = "Wake selected"; this.mnuWake.ToolTipText = "Wake selected (F6)"; this.mnuWake.Click += new System.EventHandler(this.mnuWake_Click); // // mnuWakeAll // this.mnuWakeAll.Image = global::MagiWol.Properties.Resources.mnuWakeAll_16; this.mnuWakeAll.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuWakeAll.Name = "mnuWakeAll"; this.mnuWakeAll.Size = new System.Drawing.Size(89, 24); this.mnuWakeAll.Text = "Wake all"; this.mnuWakeAll.ToolTipText = "Wake all (Shift+F6)"; this.mnuWakeAll.Click += new System.EventHandler(this.mnuWakeAll_Click); // // mnuApp // this.mnuApp.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.mnuApp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.mnuApp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuAppOptions, this.mnuApp0, this.mnuAppFeedback, this.mnuAppUpgrade, this.mnuApp1, this.mnuAppAbout}); this.mnuApp.Image = global::MagiWol.Properties.Resources.mnuApp_16; this.mnuApp.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuApp.Name = "mnuApp"; this.mnuApp.Size = new System.Drawing.Size(34, 24); this.mnuApp.Text = "About"; // // mnuAppOptions // this.mnuAppOptions.Name = "mnuAppOptions"; this.mnuAppOptions.Size = new System.Drawing.Size(206, 26); this.mnuAppOptions.Text = "&Options"; this.mnuAppOptions.Click += new System.EventHandler(this.mnuAppOptions_Click); // // mnuApp0 // this.mnuApp0.Name = "mnuApp0"; this.mnuApp0.Size = new System.Drawing.Size(203, 6); // // mnuAppFeedback // this.mnuAppFeedback.Name = "mnuAppFeedback"; this.mnuAppFeedback.Size = new System.Drawing.Size(206, 26); this.mnuAppFeedback.Text = "Send &feedback"; this.mnuAppFeedback.Click += new System.EventHandler(this.mnuAppFeedback_Click); // // mnuAppUpgrade // this.mnuAppUpgrade.Name = "mnuAppUpgrade"; this.mnuAppUpgrade.Size = new System.Drawing.Size(206, 26); this.mnuAppUpgrade.Text = "Check for &upgrade"; this.mnuAppUpgrade.Click += new System.EventHandler(this.mnuAppUpgrade_Click); // // mnuApp1 // this.mnuApp1.Name = "mnuApp1"; this.mnuApp1.Size = new System.Drawing.Size(203, 6); // // mnuAppAbout // this.mnuAppAbout.Name = "mnuAppAbout"; this.mnuAppAbout.Size = new System.Drawing.Size(206, 26); this.mnuAppAbout.Text = "&About"; this.mnuAppAbout.Click += new System.EventHandler(this.mnuAppAbout_Click); // // mnuQuickWake // this.mnuQuickWake.Image = global::MagiWol.Properties.Resources.mnuQuickWake_16; this.mnuQuickWake.ImageTransparentColor = System.Drawing.Color.Magenta; this.mnuQuickWake.Name = "mnuQuickWake"; this.mnuQuickWake.Size = new System.Drawing.Size(108, 24); this.mnuQuickWake.Text = "Quick wake"; this.mnuQuickWake.ToolTipText = "Quick wake (Ctrl+W)"; this.mnuQuickWake.Click += new System.EventHandler(this.mnuQuickWake_Click); // // list // this.list.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.list_Name, this.list_MAC, this.list_Notes}); this.list.ContextMenuStrip = this.mnxList; this.list.Dock = System.Windows.Forms.DockStyle.Fill; this.list.FullRowSelect = true; this.list.GridLines = true; this.list.HideSelection = false; this.list.LabelEdit = true; this.list.Location = new System.Drawing.Point(0, 27); this.list.Name = "list"; this.list.ShowGroups = false; this.list.Size = new System.Drawing.Size(742, 326); this.list.TabIndex = 2; this.list.UseCompatibleStateImageBehavior = false; this.list.View = System.Windows.Forms.View.Details; this.list.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.list_AfterLabelEdit); this.list.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.list_ColumnClick); this.list.ItemActivate += new System.EventHandler(this.list_ItemActivate); this.list.KeyUp += new System.Windows.Forms.KeyEventHandler(this.list_KeyUp); // // list_Name // this.list_Name.Tag = "Name"; this.list_Name.Text = "Name"; this.list_Name.Width = 150; // // list_MAC // this.list_MAC.Tag = "MAC"; this.list_MAC.Text = "MAC address"; this.list_MAC.Width = 150; // // list_Notes // this.list_Notes.Tag = "Notes"; this.list_Notes.Text = "Notes"; this.list_Notes.Width = 150; // // mnxList // this.mnxList.ImageScalingSize = new System.Drawing.Size(20, 20); this.mnxList.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnxListCut, this.mnxListCopy, this.mnxListPaste, this.toolStripMenuItem6, this.mnxListEditSelectAll, this.toolStripMenuItem9, this.mnxListAdd, this.mnxListChange, this.mnxListRemove, this.toolStripMenuItem7, this.mnxListActionWake, this.toolStripMenuItem10, this.mnxListQuickWake}); this.mnxList.Name = "mnxListAddress"; this.mnxList.Size = new System.Drawing.Size(216, 262); this.mnxList.Opening += new System.ComponentModel.CancelEventHandler(this.mnxList_Opening); // // mnxListCut // this.mnxListCut.Image = global::MagiWol.Properties.Resources.mnuCut_16; this.mnxListCut.Name = "mnxListCut"; this.mnxListCut.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.mnxListCut.Size = new System.Drawing.Size(215, 26); this.mnxListCut.Tag = "mnuCut"; this.mnxListCut.Text = "Cu&t"; this.mnxListCut.Click += new System.EventHandler(this.mnuCut_Click); // // mnxListCopy // this.mnxListCopy.Image = global::MagiWol.Properties.Resources.mnuCopy_16; this.mnxListCopy.Name = "mnxListCopy"; this.mnxListCopy.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C))); this.mnxListCopy.Size = new System.Drawing.Size(215, 26); this.mnxListCopy.Tag = "mnuCopy"; this.mnxListCopy.Text = "&Copy"; this.mnxListCopy.Click += new System.EventHandler(this.mnuCopy_Click); // // mnxListPaste // this.mnxListPaste.Image = global::MagiWol.Properties.Resources.mnuPaste_16; this.mnxListPaste.Name = "mnxListPaste"; this.mnxListPaste.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V))); this.mnxListPaste.Size = new System.Drawing.Size(215, 26); this.mnxListPaste.Tag = "mnuPaste"; this.mnxListPaste.Text = "&Paste"; this.mnxListPaste.Click += new System.EventHandler(this.mnuPaste_Click); // // toolStripMenuItem6 // this.toolStripMenuItem6.Name = "toolStripMenuItem6"; this.toolStripMenuItem6.Size = new System.Drawing.Size(212, 6); // // mnxListEditSelectAll // this.mnxListEditSelectAll.Name = "mnxListEditSelectAll"; this.mnxListEditSelectAll.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A))); this.mnxListEditSelectAll.Size = new System.Drawing.Size(215, 26); this.mnxListEditSelectAll.Text = "&Select all"; this.mnxListEditSelectAll.Click += new System.EventHandler(this.mnuSelectAll_Click); // // toolStripMenuItem9 // this.toolStripMenuItem9.Name = "toolStripMenuItem9"; this.toolStripMenuItem9.Size = new System.Drawing.Size(212, 6); // // mnxListAdd // this.mnxListAdd.Image = ((System.Drawing.Image)(resources.GetObject("mnxListAdd.Image"))); this.mnxListAdd.Name = "mnxListAdd"; this.mnxListAdd.ShortcutKeys = System.Windows.Forms.Keys.Insert; this.mnxListAdd.Size = new System.Drawing.Size(215, 26); this.mnxListAdd.Tag = "mnuAdd"; this.mnxListAdd.Text = "&Add"; this.mnxListAdd.Click += new System.EventHandler(this.mnuAdd_Click); // // mnxListChange // this.mnxListChange.Image = global::MagiWol.Properties.Resources.mnuEdit_16; this.mnxListChange.Name = "mnxListChange"; this.mnxListChange.ShortcutKeys = System.Windows.Forms.Keys.F4; this.mnxListChange.Size = new System.Drawing.Size(215, 26); this.mnxListChange.Tag = "mnuEdit"; this.mnxListChange.Text = "C&hange"; this.mnxListChange.Click += new System.EventHandler(this.mnuChange_Click); // // mnxListRemove // this.mnxListRemove.Image = global::MagiWol.Properties.Resources.mnuRemove_16; this.mnxListRemove.Name = "mnxListRemove"; this.mnxListRemove.ShortcutKeyDisplayString = "Del"; this.mnxListRemove.Size = new System.Drawing.Size(215, 26); this.mnxListRemove.Tag = "mnuRemove"; this.mnxListRemove.Text = "&Remove"; this.mnxListRemove.Click += new System.EventHandler(this.mnuRemove_Click); // // toolStripMenuItem7 // this.toolStripMenuItem7.Name = "toolStripMenuItem7"; this.toolStripMenuItem7.Size = new System.Drawing.Size(212, 6); // // mnxListActionWake // this.mnxListActionWake.Image = global::MagiWol.Properties.Resources.mnuWake_16; this.mnxListActionWake.Name = "mnxListActionWake"; this.mnxListActionWake.ShortcutKeys = System.Windows.Forms.Keys.F6; this.mnxListActionWake.Size = new System.Drawing.Size(215, 26); this.mnxListActionWake.Tag = "mnuWake"; this.mnxListActionWake.Text = "&Wake selected"; this.mnxListActionWake.Click += new System.EventHandler(this.mnuWake_Click); // // toolStripMenuItem10 // this.toolStripMenuItem10.Name = "toolStripMenuItem10"; this.toolStripMenuItem10.Size = new System.Drawing.Size(212, 6); // // mnxListQuickWake // this.mnxListQuickWake.Name = "mnxListQuickWake"; this.mnxListQuickWake.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.W))); this.mnxListQuickWake.Size = new System.Drawing.Size(215, 26); this.mnxListQuickWake.Text = "&Quick wake"; this.mnxListQuickWake.Click += new System.EventHandler(this.mnxListQuickWake_Click); // // timerEnableDisable // this.timerEnableDisable.Enabled = true; this.timerEnableDisable.Interval = 500; this.timerEnableDisable.Tick += new System.EventHandler(this.timerEnableDisable_Tick); // // tmrReSort // this.tmrReSort.Tick += new System.EventHandler(this.tmrReSortAfterRename_Tick); // // bwCheckForUpgrade // this.bwCheckForUpgrade.WorkerSupportsCancellation = true; this.bwCheckForUpgrade.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bwCheckForUpgrade_DoWork); this.bwCheckForUpgrade.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bwCheckForUpgrade_RunWorkerCompleted); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(742, 353); this.Controls.Add(this.list); this.Controls.Add(this.mnu); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.KeyPreview = true; this.MinimumSize = new System.Drawing.Size(480, 320); this.Name = "MainForm"; this.Text = "MagiWOL"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_FormClosing); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form_FormClosed); this.Load += new System.EventHandler(this.Form_Load); this.Shown += new System.EventHandler(this.Form_Shown); this.mnu.ResumeLayout(false); this.mnu.PerformLayout(); this.mnxList.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip mnu; private System.Windows.Forms.ToolStripButton mnuNew; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton mnuWake; private System.Windows.Forms.ListView list; private System.Windows.Forms.ColumnHeader list_Name; private System.Windows.Forms.ColumnHeader list_MAC; private System.Windows.Forms.ColumnHeader list_Notes; private System.Windows.Forms.ToolStripButton mnuAdd; private System.Windows.Forms.ToolStripButton mnuChange; private System.Windows.Forms.ToolStripButton mnuRemove; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripSplitButton mnuOpenRoot; private System.Windows.Forms.Timer timerEnableDisable; private System.Windows.Forms.ToolStripButton mnuQuickWake; private System.Windows.Forms.ContextMenuStrip mnxList; private System.Windows.Forms.ToolStripMenuItem mnxListCut; private System.Windows.Forms.ToolStripMenuItem mnxListCopy; private System.Windows.Forms.ToolStripMenuItem mnxListPaste; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem6; private System.Windows.Forms.ToolStripMenuItem mnxListAdd; private System.Windows.Forms.ToolStripMenuItem mnxListChange; private System.Windows.Forms.ToolStripMenuItem mnxListRemove; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7; private System.Windows.Forms.ToolStripMenuItem mnxListQuickWake; private System.Windows.Forms.ToolStripButton mnuCut; private System.Windows.Forms.ToolStripButton mnuCopy; private System.Windows.Forms.ToolStripButton mnuPaste; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem mnxListEditSelectAll; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9; private System.Windows.Forms.ToolStripMenuItem mnxListActionWake; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem10; private System.Windows.Forms.ToolStripButton mnuWakeAll; private System.Windows.Forms.Timer tmrReSort; private System.Windows.Forms.ToolStripMenuItem mnuImport; private System.Windows.Forms.ToolStripSeparator mnuImport0; private System.Windows.Forms.ToolStripSplitButton mnuSaveRoot; private System.Windows.Forms.ToolStripMenuItem mnuSave; private System.Windows.Forms.ToolStripMenuItem mnuSaveAs; private System.Windows.Forms.ToolStripDropDownButton mnuApp; private System.Windows.Forms.ToolStripMenuItem mnuAppFeedback; private System.Windows.Forms.ToolStripMenuItem mnuAppUpgrade; private System.Windows.Forms.ToolStripSeparator mnuApp1; private System.Windows.Forms.ToolStripMenuItem mnuAppAbout; private System.Windows.Forms.ToolStripMenuItem mnuOpen; private System.Windows.Forms.ToolStripMenuItem mnuAppOptions; private System.Windows.Forms.ToolStripSeparator mnuApp0; private System.ComponentModel.BackgroundWorker bwCheckForUpgrade; } }
// 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 global::System; using global::System.Reflection; using global::System.Diagnostics; using global::System.Collections.Generic; using global::System.Collections.Concurrent; using global::System.Reflection.Runtime.Types; using global::System.Reflection.Runtime.General; using global::System.Reflection.Runtime.Assemblies; using global::System.Reflection.Runtime.CustomAttributes; using global::Internal.LowLevelLinq; using global::Internal.Reflection.Core.Execution; using global::Internal.Reflection.Core.NonPortable; using global::Internal.Reflection.Tracing; using global::Internal.Metadata.NativeFormat; namespace System.Reflection.Runtime.TypeInfos { // // TypeInfos that represent type definitions (i.e. Foo or Foo<>, but not Foo<int> or arrays/pointers/byrefs.) // // internal sealed partial class RuntimeNamedTypeInfo : RuntimeTypeInfo, IEquatable<RuntimeNamedTypeInfo> { private RuntimeNamedTypeInfo(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle) { _reader = reader; _typeDefinitionHandle = typeDefinitionHandle; _typeDefinition = _typeDefinitionHandle.GetTypeDefinition(reader); } public sealed override Assembly Assembly { get { // If an assembly is split across multiple metadata blobs then the defining scope may // not be the canonical scope representing the assembly. We need to look up the assembly // by name to ensure we get the right one. ScopeDefinitionHandle scopeDefinitionHandle = NamespaceChain.DefiningScope; RuntimeAssemblyName runtimeAssemblyName = scopeDefinitionHandle.ToRuntimeAssemblyName(_reader); return RuntimeAssembly.GetRuntimeAssembly(this.ReflectionDomain, runtimeAssemblyName); } } public sealed override TypeAttributes Attributes { get { TypeAttributes attr = _typeDefinition.Flags; return attr; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_CustomAttributes(this); #endif IEnumerable<CustomAttributeData> customAttributes = RuntimeCustomAttributeData.GetCustomAttributes(this.ReflectionDomain, _reader, _typeDefinition.CustomAttributes); foreach (CustomAttributeData cad in customAttributes) yield return cad; ExecutionDomain executionDomain = this.ReflectionDomain as ExecutionDomain; if (executionDomain != null) { foreach (CustomAttributeData cad in executionDomain.ExecutionEnvironment.GetPsuedoCustomAttributes(_reader, _typeDefinitionHandle)) { yield return cad; } } } } public sealed override IEnumerable<TypeInfo> DeclaredNestedTypes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_DeclaredNestedTypes(this); #endif foreach (TypeDefinitionHandle nestedTypeHandle in _typeDefinition.NestedTypes) { yield return RuntimeNamedTypeInfo.GetRuntimeNamedTypeInfo(_reader, nestedTypeHandle); } } } public sealed override bool Equals(Object obj) { if (Object.ReferenceEquals(this, obj)) return true; RuntimeNamedTypeInfo other = obj as RuntimeNamedTypeInfo; if (!Equals(other)) return false; return true; } public bool Equals(RuntimeNamedTypeInfo other) { if (other == null) return false; if (this._reader != other._reader) return false; if (!(this._typeDefinitionHandle.Equals(other._typeDefinitionHandle))) return false; return true; } public sealed override int GetHashCode() { return _typeDefinitionHandle.GetHashCode(); } public sealed override Guid GUID { get { // // Look for a [Guid] attribute. If found, return that. // foreach (CustomAttributeHandle cah in _typeDefinition.CustomAttributes) { // We can't reference the GuidAttribute class directly as we don't have an official dependency on System.Runtime.InteropServices. // Following age-old CLR tradition, we search for the custom attribute using a name-based search. Since this makes it harder // to be sure we won't run into custom attribute constructors that comply with the GuidAttribute(String) signature, // we'll check that it does and silently skip the CA if it doesn't match the expected pattern. if (cah.IsCustomAttributeOfType(_reader, "System.Runtime.InteropServices", "GuidAttribute")) { CustomAttribute ca = cah.GetCustomAttribute(_reader); IEnumerator<FixedArgumentHandle> fahEnumerator = ca.FixedArguments.GetEnumerator(); if (!fahEnumerator.MoveNext()) continue; FixedArgumentHandle guidStringArgumentHandle = fahEnumerator.Current; if (fahEnumerator.MoveNext()) continue; FixedArgument guidStringArgument = guidStringArgumentHandle.GetFixedArgument(_reader); String guidString = guidStringArgument.Value.ParseConstantValue(this.ReflectionDomain, _reader) as String; if (guidString == null) continue; return new Guid(guidString); } } // // If we got here, there was no [Guid] attribute. // // Ideally, we'd now compute the same GUID the desktop returns - however, that algorithm is complex and has questionable dependencies // (in particular, the GUID changes if the language compilers ever change the way it emits metadata tokens into certain unordered lists. // We don't even retain that order across the Project N toolchain.) // // For now, this is a compromise that satisfies our app-compat goals. We ensure that each unique Type receives a different GUID (at least one app // uses the GUID as a dictionary key to look up types.) It will not be the same GUID on multiple runs of the app but so far, there's // no evidence that's needed. // return _namedTypeToGuidTable.GetOrAdd(this).Item1; } } public sealed override bool IsGenericTypeDefinition { get { return _typeDefinition.GenericParameters.GetEnumerator().MoveNext(); } } public sealed override bool IsGenericType { get { return _typeDefinition.GenericParameters.GetEnumerator().MoveNext(); } } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // baseclass and interfaces based on its constraints. // internal sealed override RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { return this; } } internal sealed override RuntimeType[] RuntimeGenericTypeParameters { get { LowLevelList<RuntimeType> genericTypeParameters = new LowLevelList<RuntimeType>(); foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { RuntimeType genericParameterType = RuntimeTypeUnifierEx.GetRuntimeGenericParameterTypeForTypes(this, genericParameterHandle); genericTypeParameters.Add(genericParameterType); } return genericTypeParameters.ToArray(); } } internal sealed override RuntimeType RuntimeType { get { if (_lazyType == null) { _lazyType = this.ReflectionDomain.ResolveTypeDefinition(_reader, _typeDefinitionHandle); } return _lazyType; } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { Handle baseType = _typeDefinition.BaseType; if (baseType.IsNull(_reader)) return QTypeDefRefOrSpec.Null; return new QTypeDefRefOrSpec(_reader, baseType); } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { LowLevelList<QTypeDefRefOrSpec> directlyImplementedInterfaces = new LowLevelList<QTypeDefRefOrSpec>(); foreach (Handle ifcHandle in _typeDefinition.Interfaces) directlyImplementedInterfaces.Add(new QTypeDefRefOrSpec(_reader, ifcHandle)); return directlyImplementedInterfaces.ToArray(); } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal sealed override TypeContext TypeContext { get { return new TypeContext(this.RuntimeGenericTypeParameters, null); } } internal MetadataReader Reader { get { return _reader; } } internal TypeDefinitionHandle TypeDefinitionHandle { get { return _typeDefinitionHandle; } } internal IEnumerable<MethodHandle> DeclaredConstructorHandles { get { foreach (MethodHandle methodHandle in _typeDefinition.Methods) { if (methodHandle.IsConstructor(_reader)) yield return methodHandle; } } } internal IEnumerable<EventHandle> DeclaredEventHandles { get { return _typeDefinition.Events; } } internal IEnumerable<FieldHandle> DeclaredFieldHandles { get { return _typeDefinition.Fields; } } internal IEnumerable<MethodHandle> DeclaredMethodAndConstructorHandles { get { return _typeDefinition.Methods; } } internal IEnumerable<PropertyHandle> DeclaredPropertyHandles { get { return _typeDefinition.Properties; } } private MetadataReader _reader; private TypeDefinitionHandle _typeDefinitionHandle; private TypeDefinition _typeDefinition; private NamespaceChain NamespaceChain { get { if (_lazyNamespaceChain == null) _lazyNamespaceChain = new NamespaceChain(_reader, _typeDefinition.NamespaceDefinition); return _lazyNamespaceChain; } } private volatile NamespaceChain _lazyNamespaceChain; private volatile RuntimeType _lazyType; private static NamedTypeToGuidTable _namedTypeToGuidTable = new NamedTypeToGuidTable(); private sealed class NamedTypeToGuidTable : ConcurrentUnifier<RuntimeNamedTypeInfo, Tuple<Guid>> { protected sealed override Tuple<Guid> Factory(RuntimeNamedTypeInfo key) { return new Tuple<Guid>(Guid.NewGuid()); } } } }
// // ApiTest.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using Couchbase.Lite; using Sharpen; using Couchbase.Lite.Util; using System.IO; using System.Linq; using System.Text; using System.Threading; using NUnit.Framework; using System.Security.Permissions; using System.Threading.Tasks; namespace Couchbase.Lite { /// <summary>Created by andrey on 12/3/13.</summary> /// <remarks>Created by andrey on 12/3/13.</remarks> public class ApiTest : LiteTestCase { public static Task CreateDocumentsAsync(Database db, int n) { return db.RunAsync((database)=> { database.BeginTransaction(); ApiTest.CreateDocuments(database, n); database.EndTransaction(true); }); } public static void CreateDocuments(Database db, int numberOfDocsToCreate) { //TODO should be changed to use db.runInTransaction for (int i = 0; i < numberOfDocsToCreate; i++) { var properties = new Dictionary<String, Object>(); properties["testName"] = "testDatabase"; properties["sequence"] = i; CreateDocumentWithProperties(db, properties); } } public static Document CreateDocumentWithProperties(Database db, IDictionary<String, Object> properties) { var doc = db.CreateDocument(); Assert.IsNotNull(doc); Assert.IsNull(doc.CurrentRevisionId); Assert.IsNull(doc.CurrentRevision); Assert.IsNotNull("Document has no ID", doc.Id); // 'untitled' docs are no longer untitled (8/10/12) try { doc.PutProperties(properties); } catch (Exception e) { Log.E(Tag, "Error creating document", e); Assert.IsTrue( false, "can't create new document in db:" + db.Name + " with properties:" + properties.Aggregate(new StringBuilder(" >>> "), (str, kvp)=> { str.AppendFormat("'{0}:{1}' ", kvp.Key, kvp.Value); return str; }, str=>str.ToString())); } Assert.IsNotNull(doc.Id); Assert.IsNotNull(doc.CurrentRevisionId); Assert.IsNotNull(doc.UserProperties); Assert.AreEqual(db.GetDocument(doc.Id), doc); return doc; } /// <exception cref="System.Exception"></exception> public void RunLiveQuery(String methodNameToCall) { var db = StartDatabase(); var doneSignal = new CountDownLatch(11); // FIXME.ZJG: Not sure why, but now Changed is only called once. // 11 corresponds to startKey = 23; endKey = 33 // run a live query var view = db.GetView("vu"); view.SetMap((document, emitter) => emitter (document ["sequence"], 1), "1"); var query = view.CreateQuery().ToLiveQuery(); query.StartKey = 23; query.EndKey = 33; Log.I(Tag, "Created " + query); // these are the keys that we expect to see in the livequery change listener callback var expectedKeys = new HashSet<Int64>(); for (var i = 23; i < 34; i++) { expectedKeys.AddItem(i); } // install a change listener which decrements countdown latch when it sees a new // key from the list of expected keys EventHandler<QueryChangeEventArgs> handler = (sender, e) => { var rows = e.Rows; foreach(var row in rows) { if (expectedKeys.Contains((Int64)row.Key)) { Console.WriteLine(Tag + " doneSignal decremented " + doneSignal.Count); doneSignal.CountDown(); } } }; query.Changed += handler; // create the docs that will cause the above change listener to decrement countdown latch var createTask = CreateDocumentsAsync(db, n: 50); createTask.Wait(TimeSpan.FromSeconds(5)); if (methodNameToCall.Equals("start")) { // start the livequery running asynchronously query.Start(); } else { Assert.IsNull(query.Rows); query.Run(); // this will block until the query completes Assert.IsNotNull(query.Rows); } // wait for the doneSignal to be finished var success = doneSignal.Await(TimeSpan.FromSeconds(5)); Assert.IsTrue(success, "Done signal timed out live query never ran"); // stop the livequery since we are done with it query.Changed -= handler; query.Stop(); } //SERVER & DOCUMENTS /// <exception cref="System.IO.IOException"></exception> [Test] public void TestAPIManager() { //StartDatabase(); Manager manager = this.manager; Assert.IsTrue(manager != null); foreach (string dbName in manager.AllDatabaseNames) { Database db = manager.GetDatabase(dbName); Log.I(Tag, "Database '" + dbName + "':" + db.DocumentCount + " documents"); } var options = new ManagerOptions(); options.ReadOnly = true; var roManager = new Manager(new DirectoryInfo(manager.Directory), options); Assert.IsTrue(roManager != null); var nonExistantDatabase = roManager.GetDatabase("foo"); Assert.IsNull(nonExistantDatabase); var dbNames = manager.AllDatabaseNames; Assert.IsFalse(dbNames.Contains<String>("foo")); Assert.IsTrue(dbNames.Contains(DefaultTestDb)); } [Test] public void TestCreateDocument() { var properties = new Dictionary<String, Object>(); properties["testName"] = "testCreateDocument"; properties["tag"] = 1337L; var db = manager.GetExistingDatabase(DefaultTestDb); var doc = CreateDocumentWithProperties(db, properties); var docID = doc.Id; Assert.IsTrue(docID.Length > 10, "Invalid doc ID: " + docID); var currentRevisionID = doc.CurrentRevisionId; Assert.IsTrue(currentRevisionID.Length > 10, "Invalid doc revision: " + docID); Assert.AreEqual(doc.UserProperties, properties); Assert.AreEqual(db.GetDocument(docID), doc); db.DocumentCache.EvictAll(); // so we can load fresh copies var doc2 = db.GetExistingDocument(docID); Assert.AreEqual(doc2.Id, docID); Assert.AreEqual(doc2.CurrentRevisionId, currentRevisionID); Assert.IsNull(db.GetExistingDocument("b0gus")); } /// <exception cref="System.Exception"></exception> [Test] public void TestDatabaseCompaction() { var properties = new Dictionary<String, Object>(); properties["testName"] = "testDatabaseCompaction"; properties["tag"] = 1337; var db = manager.GetExistingDatabase(DefaultTestDb); var doc = CreateDocumentWithProperties(db, properties); var rev1 = doc.CurrentRevision; var properties2 = new Dictionary<String, Object>(properties); properties2["tag"] = 4567; var rev2 = rev1.CreateRevision(properties2); db.Compact(); var fetchedDoc = database.GetDocument(doc.Id); var revisions = fetchedDoc.RevisionHistory; foreach (SavedRevision revision in revisions) { if (revision.Id.Equals(rev1)) { Assert.IsFalse(revision.PropertiesAvailable); } if (revision.Id.Equals(rev2)) { Assert.IsTrue(revision.PropertiesAvailable); } } } /// <exception cref="System.Exception"></exception> [Test] public void TestCreateRevisions() { var properties = new Dictionary<String, Object>(); properties["testName"] = "testCreateRevisions"; properties["tag"] = 1337; var db = StartDatabase(); var doc = CreateDocumentWithProperties(db, properties); var rev1 = doc.CurrentRevision; Assert.IsTrue(rev1.Id.StartsWith("1-")); Assert.AreEqual(1, rev1.Sequence); Assert.AreEqual(0, rev1.Attachments.Count()); // Test -createRevisionWithProperties: var properties2 = new Dictionary<String, Object>(properties); properties2["tag"] = 4567; var rev2 = rev1.CreateRevision(properties2); Assert.IsNotNull(rev2, "Put failed"); Assert.IsTrue(doc.CurrentRevisionId.StartsWith("2-"), "Document revision ID is still " + doc.CurrentRevisionId); Assert.AreEqual(rev2.Id, doc.CurrentRevisionId); Assert.IsNotNull(rev2.PropertiesAvailable); Assert.AreEqual(rev2.UserProperties, properties2); Assert.AreEqual(rev2.Document, doc); Assert.AreEqual(rev2.GetProperty("_id"), doc.Id); Assert.AreEqual(rev2.GetProperty("_rev"), rev2.Id); // Test -createRevision: var newRev = rev2.CreateRevision(); Assert.IsNull(newRev.Id); Assert.AreEqual(newRev.Parent, rev2); Assert.AreEqual(newRev.ParentId, rev2.Id); var listRevs = new AList<SavedRevision>(); listRevs.Add(rev1); listRevs.Add(rev2); Assert.AreEqual(newRev.RevisionHistory, listRevs); Assert.AreEqual(newRev.Properties, rev2.Properties); Assert.AreEqual(newRev.UserProperties, rev2.UserProperties); var userProperties = new Dictionary<String, Object>(); userProperties["because"] = "NoSQL"; newRev.SetUserProperties(userProperties); Assert.AreEqual(newRev.UserProperties, userProperties); var expectProperties = new Dictionary<String, Object>(); expectProperties["because"] = "NoSQL"; expectProperties["_id"] = doc.Id; expectProperties["_rev"] = rev2.Id; Assert.AreEqual(newRev.Properties, expectProperties); var rev3 = newRev.Save(); Assert.IsNotNull(rev3); Assert.AreEqual(rev3.UserProperties, newRev.UserProperties); } /// <exception cref="System.Exception"></exception> [Test] public void TestCreateNewRevisions() { var properties = new Dictionary<String, Object>(); properties["testName"] = "testCreateRevisions"; properties["tag"] = 1337; var db = StartDatabase(); var doc = db.CreateDocument(); var newRev = doc.CreateRevision(); var newRevDocument = newRev.Document; Assert.AreEqual(doc, newRevDocument); Assert.AreEqual(db, newRev.Database); Assert.IsNull(newRev.ParentId); Assert.IsNull(newRev.Parent); var expectProperties = new Dictionary<String, Object>(); expectProperties["_id"] = doc.Id; Assert.AreEqual(expectProperties, newRev.Properties); Assert.IsTrue(!newRev.IsDeletion); Assert.AreEqual(newRev.Sequence, 0); //ios support another approach to set properties:: //newRev.([@"testName"] = @"testCreateRevisions"; //newRev[@"tag"] = @1337; newRev.SetUserProperties(properties); Assert.AreEqual(newRev.UserProperties, properties); var rev1 = newRev.Save(); Assert.IsNotNull(rev1, "Save 1 failed"); Assert.AreEqual(doc.CurrentRevision, rev1); Assert.IsNotNull(rev1.Id.StartsWith("1-")); Assert.AreEqual(1, rev1.Sequence); Assert.IsNull(rev1.ParentId); Assert.IsNull(rev1.Parent); newRev = rev1.CreateRevision(); newRevDocument = newRev.Document; Assert.AreEqual(doc, newRevDocument); Assert.AreEqual(db, newRev.Database); Assert.AreEqual(rev1.Id, newRev.ParentId); Assert.AreEqual(rev1, newRev.Parent); Assert.AreEqual(rev1.Properties, newRev.Properties); Assert.AreEqual(rev1.UserProperties, newRev.UserProperties); Assert.IsTrue(!newRev.IsDeletion); // we can't add/modify one property as on ios. need to add separate method? // newRev[@"tag"] = @4567; properties["tag"] = 4567; newRev.SetUserProperties(properties); var rev2 = newRev.Save(); Assert.IsNotNull(rev2, "Save 2 failed"); Assert.AreEqual(doc.CurrentRevision, rev2); Assert.IsTrue(rev2.Id.StartsWith("2-")); Assert.AreEqual(2, rev2.Sequence); Assert.AreEqual(rev1.Id, rev2.ParentId); Assert.AreEqual(rev1, rev2.Parent); Assert.IsTrue(doc.CurrentRevisionId.StartsWith("2-"), "Document revision ID is still " + doc.CurrentRevisionId); // Add a deletion/tombstone revision: newRev = doc.CreateRevision(); Assert.AreEqual(rev2.Id, newRev.ParentId); Assert.AreEqual(rev2, newRev.Parent); newRev.IsDeletion = true; var rev3 = newRev.Save(); Assert.IsNotNull(rev3, "Save 3 failed"); Assert.AreEqual(doc.CurrentRevision, rev3); Assert.IsTrue (rev3.Id.StartsWith ("3-", StringComparison.Ordinal), "Unexpected revID " + rev3.Id); Assert.AreEqual(3, rev3.Sequence); Assert.IsTrue(rev3.IsDeletion); Assert.IsTrue(doc.Deleted); var doc2 = db.GetDocument(doc.Id); Assert.AreEqual(doc, doc2); Assert.IsNull(db.GetExistingDocument(doc.Id)); } //API_SaveMultipleDocuments on IOS //API_SaveMultipleUnsavedDocuments on IOS //API_DeleteMultipleDocuments commented on IOS /// <exception cref="System.Exception"></exception> [Test] public void TestDeleteDocument() { var properties = new Dictionary<String, Object>(); properties["testName"] = "testDeleteDocument"; var db = manager.GetExistingDatabase(DefaultTestDb); var doc = CreateDocumentWithProperties(db, properties); Assert.IsTrue(!doc.Deleted); Assert.IsTrue(!doc.CurrentRevision.IsDeletion); doc.Delete(); Assert.IsTrue(doc.Deleted); Assert.IsNotNull(doc.CurrentRevision.IsDeletion); } /// <exception cref="System.Exception"></exception> [Test] public void TestPurgeDocument() { var properties = new Dictionary<String, Object>(); properties["testName"] = "testPurgeDocument"; var db = manager.GetExistingDatabase(DefaultTestDb); var doc = CreateDocumentWithProperties(db, properties); Assert.IsNotNull(doc); doc.Purge(); var redoc = db.DocumentCache[doc.Id]; Assert.IsNull(redoc); } /// <exception cref="System.Exception"></exception> [Test] public void TestAllDocuments() { var db = manager.GetExistingDatabase(DefaultTestDb); //StartDatabase(); const int docsCount = 5; CreateDocuments(db, numberOfDocsToCreate: docsCount); // clear the cache so all documents/revisions will be re-fetched: db.DocumentCache.EvictAll(); Log.I(Tag, "----- all documents -----"); var query = db.CreateAllDocumentsQuery(); //query.prefetch = YES; Log.I(Tag, "Getting all documents: " + query); var rows = query.Run(); Assert.AreEqual(docsCount, rows.Count); var n = 0; foreach (var row in rows) { Log.I(Tag, " --> " + row); var doc = row.Document; Assert.IsNotNull(doc, "Couldn't get doc from query"); Assert.IsNotNull(doc.CurrentRevision.PropertiesAvailable, "QueryRow should have preloaded revision contents"); Log.I(Tag, " Properties =" + doc.Properties); Assert.IsNotNull(doc.Properties, "Couldn't get doc properties"); Assert.AreEqual("testDatabase", doc.GetProperty("testName")); n++; } Assert.AreEqual(n, docsCount); } /// <exception cref="System.Exception"></exception> [Test] public void TestLocalDocs() { var db = manager.GetExistingDatabase(DefaultTestDb); var properties = new Dictionary<String, Object>(); properties["foo"] = "bar"; var props = db.GetExistingLocalDocument("dock"); Assert.IsNull(props); db.PutLocalDocument("dock" , properties); props = db.GetExistingLocalDocument("dock"); Assert.AreEqual(props["foo"], "bar"); var newProperties = new Dictionary<String, Object>(); newProperties["FOOO"] = "BARRR"; db.PutLocalDocument("dock", newProperties); props = db.GetExistingLocalDocument("dock"); Assert.IsFalse(props.ContainsKey("foo")); Assert.AreEqual(props["FOOO"], "BARRR"); Assert.IsNotNull(db.DeleteLocalDocument("dock"), "Couldn't delete local doc"); props = db.GetExistingLocalDocument("dock"); Assert.IsNull(props); Assert.IsNotNull(!db.DeleteLocalDocument("dock"),"Second delete should have failed"); } //TODO issue: deleteLocalDocument should return error.code( see ios) // HISTORY /// <exception cref="System.Exception"></exception> [Test] public void TestHistory() { var properties = new Dictionary<String, Object>(); properties["testName"] = "test06_History"; properties["tag"] = 1L; var db = StartDatabase(); var doc = CreateDocumentWithProperties(db, properties); var rev1ID = doc.CurrentRevisionId; Log.I(Tag, "1st revision: " + rev1ID); Assert.IsTrue (rev1ID.StartsWith ("1-", StringComparison.Ordinal), "1st revision looks wrong: " + rev1ID); Assert.AreEqual(doc.UserProperties, properties); properties = new Dictionary<String, Object>(doc.Properties); properties["tag"] = 2; Assert.IsNotNull(!properties.Equals(doc.Properties)); Assert.IsNotNull(doc.PutProperties(properties)); var rev2ID = doc.CurrentRevisionId; Log.I(Tag, "rev2ID" + rev2ID); Assert.IsTrue(rev2ID.StartsWith("2-", StringComparison.Ordinal), "2nd revision looks wrong:" + rev2ID); var revisions = doc.RevisionHistory.ToList(); Log.I(Tag, "Revisions = " + revisions); Assert.AreEqual(revisions.Count, 2); var rev1 = revisions[0]; Assert.AreEqual(rev1.Id, rev1ID); var gotProperties = rev1.Properties; Assert.AreEqual(1, gotProperties["tag"]); var rev2 = revisions[1]; Assert.AreEqual(rev2.Id, rev2ID); Assert.AreEqual(rev2, doc.CurrentRevision); gotProperties = rev2.Properties; Assert.AreEqual(2, gotProperties["tag"]); var tmp = new AList<SavedRevision>(); tmp.Add(rev2); Assert.AreEqual(doc.ConflictingRevisions, tmp); Assert.AreEqual(doc.LeafRevisions, tmp); } /// <exception cref="System.Exception"></exception> [Test] public void TestConflict() { var prop = new Dictionary<String, Object>(); prop["foo"] = "bar"; var db = StartDatabase(); var doc = CreateDocumentWithProperties(db, prop); var rev1 = doc.CurrentRevision; var properties = new Dictionary<String, Object>(doc.Properties); properties["tag"] = 2; var rev2a = doc.PutProperties(properties); properties = new Dictionary<String, Object>(rev1.Properties); properties["tag"] = 3; var newRev = rev1.CreateRevision(); newRev.SetProperties(properties); var rev2b = newRev.Save(allowConflict: true); Assert.IsNotNull(rev2b, "Failed to create a a conflict"); var confRevs = new AList<SavedRevision>(); confRevs.AddItem(rev2b); confRevs.AddItem(rev2a); Assert.AreEqual(doc.ConflictingRevisions, confRevs); Assert.AreEqual(doc.LeafRevisions, confRevs); SavedRevision defaultRev; SavedRevision otherRev; if (String.CompareOrdinal (rev2a.Id, rev2b.Id) > 0) { defaultRev = rev2a; otherRev = rev2b; } else { defaultRev = rev2b; otherRev = rev2a; } Assert.AreEqual(doc.CurrentRevision, defaultRev); var query = db.CreateAllDocumentsQuery(); query.AllDocsMode = AllDocsMode.ShowConflicts; var rows = query.Run(); Assert.AreEqual(rows.Count, 1); var row = rows.GetRow(0); var revs = row.GetConflictingRevisions().ToList(); Assert.AreEqual(2, revs.Count); Assert.AreEqual(revs[0], defaultRev); Assert.AreEqual(revs[1], otherRev); } //ATTACHMENTS /// <exception cref="System.Exception"></exception> /// <exception cref="System.IO.IOException"></exception> [Test] public void TestAttachments() { var properties = new Dictionary<String, Object>(); properties["testName"] = "testAttachments"; var db = manager.GetExistingDatabase(DefaultTestDb); var doc = CreateDocumentWithProperties(db, properties); var rev = doc.CurrentRevision; Assert.AreEqual(rev.Attachments.Count(), 0); Assert.AreEqual(rev.AttachmentNames.Count(), 0); Assert.IsNull(rev.GetAttachment("index.html")); var content = "This is a test attachment!"; var body = new ByteArrayInputStream(Runtime.GetBytesForString(content).ToArray()); var rev2 = doc.CreateRevision(); rev2.SetAttachment("index.html", "text/plain; charset=utf-8", body); var rev3 = rev2.Save(); Assert.IsNotNull(rev3); Assert.AreEqual(rev3.Attachments.Count(), 1); Assert.AreEqual(rev3.AttachmentNames.Count(), 1); var attach = rev3.GetAttachment("index.html"); Assert.IsNotNull(attach); Assert.AreEqual(doc, attach.Document); Assert.AreEqual("index.html", attach.Name); var attNames = new AList<string>(); attNames.AddItem("index.html"); Assert.AreEqual(rev3.AttachmentNames, attNames); Assert.AreEqual("text/plain; charset=utf-8", attach.ContentType); var attachmentContent = Encoding.UTF8.GetString(attach.Content.ToArray()); Assert.AreEqual(content, attachmentContent); Assert.AreEqual(Runtime.GetBytesForString(content).ToArray().Length, attach.Length); var newRev = rev3.CreateRevision(); newRev.RemoveAttachment(attach.Name); var rev4 = newRev.Save(); Assert.IsNotNull(rev4); Assert.AreEqual(0, rev4.AttachmentNames.Count()); } //CHANGE TRACKING /// <exception cref="System.Exception"></exception> [Test] public void TestChangeTracking() { var doneSignal = new CountDownLatch(1); var db = StartDatabase(); db.Changed += (sender, e) => doneSignal.CountDown(); var task = CreateDocumentsAsync(db, 5); // We expect that the changes reported by the server won't be notified, because those revisions // are already cached in memory. var success = doneSignal.Await(TimeSpan.FromSeconds(10)); Assert.IsTrue(success); Assert.AreEqual(5, db.GetLastSequenceNumber()); // Give transaction time to complete. System.Threading.Thread.Sleep(500); Assert.IsTrue(task.Status.HasFlag(TaskStatus.RanToCompletion)); } //VIEWS /// <exception cref="System.Exception"></exception> [Test] public void TestCreateView() { var db = StartDatabase(); var view = db.GetView("vu"); Assert.IsNotNull(view); Assert.AreEqual(db, view.Database); Assert.AreEqual("vu", view.Name); Assert.IsNull(view.Map); Assert.IsNull(view.Reduce); view.SetMap((document, emitter) => emitter (document.Get ("sequence"), null), "1"); Assert.IsNotNull(view.Map != null); CreateDocuments(db, numberOfDocsToCreate: 50); var query = view.CreateQuery(); query.StartKey=23; query.EndKey=33; Assert.AreEqual(db, query.Database); var rows = query.Run(); Assert.IsNotNull(rows); Assert.AreEqual(11, rows.Count); var expectedKey = 23; foreach (var row in rows) { Assert.AreEqual(expectedKey, row.Key); Assert.AreEqual(expectedKey + 1, row.SequenceNumber); ++expectedKey; } } //API_RunSlowView commented on IOS /// <exception cref="System.Exception"></exception> [Test] public void TestValidation() { var db = StartDatabase(); db.SetValidation("uncool", (newRevision, context)=> { { if (newRevision.GetProperty("groovy") == null) { context.Reject("uncool"); return false; } return true; } }); var properties = new Dictionary<String, Object>(); properties["groovy"] = "right on"; properties["foo"] = "bar"; var doc = db.CreateDocument(); Assert.IsNotNull(doc.PutProperties(properties)); properties = new Dictionary<String, Object>(); properties["foo"] = "bar"; doc = db.CreateDocument(); try { Assert.IsNull(doc.PutProperties(properties)); } catch (CouchbaseLiteException e) { //TODO Assert.AreEqual(StatusCode.Forbidden, e.GetCBLStatus().GetCode()); } } // assertEquals(e.getLocalizedMessage(), "forbidden: uncool"); //TODO: Not hooked up yet /// <exception cref="System.Exception"></exception> [Test] public void TestViewWithLinkedDocs() { var db = StartDatabase(); const int numberOfDocs = 50; var docs = new Document[50]; var lastDocID = String.Empty; for (var i = 0; i < numberOfDocs; i++) { var properties = new Dictionary<String, Object>(); properties["sequence"] = i; properties["prev"] = lastDocID; var doc = CreateDocumentWithProperties(db, properties); docs[i] = doc; lastDocID = doc.Id; } var query = db.SlowQuery((document, emitter)=> emitter (document ["sequence"], new object[] { "_id", document ["prev"] })); query.StartKey = 23; query.EndKey = 33; query.Prefetch = true; var rows = query.Run(); Assert.IsNotNull(rows); Assert.AreEqual(rows.Count, 11); var rowNumber = 23; foreach (var row in rows) { Assert.AreEqual(row.Key, rowNumber); var prevDoc = docs[rowNumber]; Assert.AreEqual(row.DocumentId, prevDoc.Id); Assert.AreEqual(row.Document, prevDoc); ++rowNumber; } } /// <exception cref="System.Exception"></exception> [Test] public void TestLiveQueryRun() { RunLiveQuery("run"); } /// <exception cref="System.Exception"></exception> [Test] public void TestLiveQueryStart() { RunLiveQuery("start"); } /// <exception cref="System.Exception"></exception> [Test] public void TestAsyncViewQuery() { var doneSignal = new CountDownLatch(1); var db = StartDatabase(); View view = db.GetView("vu"); view.SetMap((document, emitter) => emitter (document ["sequence"], null), "1"); const int kNDocs = 50; CreateDocuments(db, kNDocs); var query = view.CreateQuery(); query.StartKey=23; query.EndKey=33; var task = query.RunAsync().ContinueWith((resultTask) => { Log.I (LiteTestCase.Tag, "Async query finished!"); var rows = resultTask.Result; Assert.IsNotNull (rows); Assert.AreEqual (rows.Count, 11); var expectedKey = 23; for (IEnumerator<QueryRow> it = rows; it.MoveNext ();) { var row = it.Current; Assert.AreEqual (row.Document.Database, db); Assert.AreEqual (row.Key, expectedKey); ++expectedKey; } doneSignal.CountDown (); }); Log.I(Tag, "Waiting for async query to finish..."); var success = task.Wait(TimeSpan.FromSeconds(10)); Assert.IsTrue(success, "Done signal timed out..StartKey=ry never ran"); } /// <summary> /// Make sure that a database's map/Counte functions are shared with the shadow database instance /// running in the background server. /// </summary> /// <remarks> /// Make sure that a database's map/reduce functionDatabaseared with the shadow database instance /// running in the background server. /// </remarks> /// <exception cref="System.Exception"></exception> [Test] public void TestSharedMapBlocks() { var path = new DirectoryInfo(Path.Combine(GetRootDirectory().FullName, "API_SharedMapBlocks")); var mgr = new Manager(path, Manager.DefaultOptions); var db = mgr.GetDatabase("db"); db.Open(); db.SetFilter("phil", (r, p) => true); db.SetValidation("val", (p1, p2) => true); var view = db.GetView("view"); var ok = view.SetMapReduce((p1, p2)=>{ return; }, (a, b, c) => { return null; }, null); Assert.IsNotNull(ok, "Couldn't set map/reduce"); var map = view.Map; var reduce = view.Reduce; var filter = db.GetFilter("phil"); var validation = db.GetValidation("val"); var result = mgr.RunAsync("db", (database)=> { Assert.IsNotNull(database); View serverView = database.GetExistingView("view"); Assert.IsNotNull(serverView); Assert.AreEqual(database.GetFilter("phil"), filter); Assert.AreEqual(database.GetValidation("val"), validation); Assert.AreEqual(serverView.Map, map); Assert.AreEqual(serverView.Reduce, reduce); return true; }); result.Wait(TimeSpan.FromSeconds(5)); // blocks until async task has run db.Close(); mgr.Close(); } /// <exception cref="System.Exception"></exception> [Test] public void TestChangeUUID() { var mgr = new Manager(new DirectoryInfo(Path.Combine(GetRootDirectory().FullName, "ChangeUUID")), Manager.DefaultOptions); var db = mgr.GetDatabase("db"); db.Open(); var pub = db.PublicUUID(); var priv = db.PrivateUUID(); Assert.IsTrue(pub.Length > 10); Assert.IsTrue(priv.Length > 10); Assert.IsTrue(db.ReplaceUUIDs(), "replaceUUIDs failed"); Assert.IsFalse(pub.Equals(db.PublicUUID())); Assert.IsFalse(priv.Equals(db.PrivateUUID())); mgr.Close(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace sl.web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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: Provides some basic access to some environment ** functionality. ** ** ============================================================*/ namespace System { using System.IO; using System.Security; using System.Resources; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Text; using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Reflection; using System.Diagnostics; using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Threading; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public enum EnvironmentVariableTarget { Process = 0, User = 1, Machine = 2, } public static partial class Environment { // Assume the following constants include the terminating '\0' - use <, not <= private const int MaxEnvVariableValueLength = 32767; // maximum length for environment variable name and value // System environment variables are stored in the registry, and have // a size restriction that is separate from both normal environment // variables and registry value name lengths, according to MSDN. // MSDN doesn't detail whether the name is limited to 1024, or whether // that includes the contents of the environment variable. private const int MaxSystemEnvVariableLength = 1024; private const int MaxUserEnvVariableLength = 255; internal sealed class ResourceHelper { internal ResourceHelper(String name) { m_name = name; } private String m_name; private ResourceManager SystemResMgr; // To avoid infinite loops when calling GetResourceString. See comments // in GetResourceString for this field. private List<string> currentlyLoading; // process-wide state (since this is only used in one domain), // used to avoid the TypeInitialization infinite recusion // in GetResourceStringCode internal bool resourceManagerInited = false; // Is this thread currently doing infinite resource lookups? private int infinitelyRecursingCount; internal String GetResourceString(String key) { if (key == null || key.Length == 0) { Debug.Assert(false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?"); return "[Resource lookup failed - null or empty resource name]"; } // We have a somewhat common potential for infinite // loops with mscorlib's ResourceManager. If "potentially dangerous" // code throws an exception, we will get into an infinite loop // inside the ResourceManager and this "potentially dangerous" code. // Potentially dangerous code includes the IO package, CultureInfo, // parts of the loader, some parts of Reflection, Security (including // custom user-written permissions that may parse an XML file at // class load time), assembly load event handlers, etc. Essentially, // this is not a bounded set of code, and we need to fix the problem. // Fortunately, this is limited to mscorlib's error lookups and is NOT // a general problem for all user code using the ResourceManager. // The solution is to make sure only one thread at a time can call // GetResourceString. Also, since resource lookups can be // reentrant, if the same thread comes into GetResourceString // twice looking for the exact same resource name before // returning, we're going into an infinite loop and we should // return a bogus string. bool lockTaken = false; try { Monitor.Enter(this, ref lockTaken); // Are we recursively looking up the same resource? Note - our backout code will set // the ResourceHelper's currentlyLoading stack to null if an exception occurs. if (currentlyLoading != null && currentlyLoading.Count > 0 && currentlyLoading.LastIndexOf(key) != -1) { // We can start infinitely recursing for one resource lookup, // then during our failure reporting, start infinitely recursing again. // avoid that. if (infinitelyRecursingCount > 0) { return "[Resource lookup failed - infinite recursion or critical failure detected.]"; } infinitelyRecursingCount++; // Note: our infrastructure for reporting this exception will again cause resource lookup. // This is the most direct way of dealing with that problem. string message = $"Infinite recursion during resource lookup within {System.CoreLib.Name}. This may be a bug in {System.CoreLib.Name}, or potentially in certain extensibility points such as assembly resolve events or CultureInfo names. Resource name: {key}"; Assert.Fail("[Recursive resource lookup bug]", message, Assert.COR_E_FAILFAST, System.Diagnostics.StackTrace.TraceFormat.NoResourceLookup); Environment.FailFast(message); } if (currentlyLoading == null) currentlyLoading = new List<string>(); // Call class constructors preemptively, so that we cannot get into an infinite // loop constructing a TypeInitializationException. If this were omitted, // we could get the Infinite recursion assert above by failing type initialization // between the Push and Pop calls below. if (!resourceManagerInited) { RuntimeHelpers.RunClassConstructor(typeof(ResourceManager).TypeHandle); RuntimeHelpers.RunClassConstructor(typeof(ResourceReader).TypeHandle); RuntimeHelpers.RunClassConstructor(typeof(RuntimeResourceSet).TypeHandle); RuntimeHelpers.RunClassConstructor(typeof(BinaryReader).TypeHandle); resourceManagerInited = true; } currentlyLoading.Add(key); // Push if (SystemResMgr == null) { SystemResMgr = new ResourceManager(m_name, typeof(Object).Assembly); } string s = SystemResMgr.GetString(key, null); currentlyLoading.RemoveAt(currentlyLoading.Count - 1); // Pop Debug.Assert(s != null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString. Resource name was: \"" + key + "\""); return s; } catch { if (lockTaken) { // Backout code - throw away potentially corrupt state SystemResMgr = null; currentlyLoading = null; } throw; } finally { if (lockTaken) { Monitor.Exit(this); } } } } private static volatile ResourceHelper m_resHelper; // Doesn't need to be initialized as they're zero-init. private const int MaxMachineNameLength = 256; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } private static volatile OperatingSystem m_os; // Cached OperatingSystem value /*==================================TickCount=================================== **Action: Gets the number of ticks since the system was started. **Returns: The number of ticks since the system was started. **Arguments: None **Exceptions: None ==============================================================================*/ public static extern int TickCount { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } // Terminates this process with the given exit code. [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void _Exit(int exitCode); public static void Exit(int exitCode) { _Exit(exitCode); } public static extern int ExitCode { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } // Note: The CLR's Watson bucketization code looks at the caller of the FCALL method // to assign blame for crashes. Don't mess with this, such as by making it call // another managed helper method, unless you consult with some CLR Watson experts. [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void FailFast(String message); // This overload of FailFast will allow you to specify the exception object // whose bucket details *could* be used when undergoing the failfast process. // To be specific: // // 1) When invoked from within a managed EH clause (fault/finally/catch), // if the exception object is preallocated, the runtime will try to find its buckets // and use them. If the exception object is not preallocated, it will use the bucket // details contained in the object (if any). // // 2) When invoked from outside the managed EH clauses (fault/finally/catch), // if the exception object is preallocated, the runtime will use the callsite's // IP for bucketing. If the exception object is not preallocated, it will use the bucket // details contained in the object (if any). [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void FailFast(String message, Exception exception); /*===============================CurrentDirectory=============================== **Action: Provides a getter and setter for the current directory. The original ** current directory is the one from which the process was started. **Returns: The current directory (from the getter). Void from the setter. **Arguments: The current directory to which to switch to the setter. **Exceptions: ==============================================================================*/ internal static String CurrentDirectory { get { return Directory.GetCurrentDirectory(); } set { Directory.SetCurrentDirectory(value); } } // Returns the system directory (ie, C:\WinNT\System32). internal static String SystemDirectory { get { StringBuilder sb = new StringBuilder(Path.MaxPath); int r = Win32Native.GetSystemDirectory(sb, Path.MaxPath); Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath"); if (r == 0) __Error.WinIOError(); String path = sb.ToString(); return path; } } public static String ExpandEnvironmentVariables(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); if (name.Length == 0) { return name; } if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode()) { // Environment variable accessors are not approved modern API. // Behave as if no variables are defined in this case. return name; } int currentSize = 100; StringBuilder blob = new StringBuilder(currentSize); // A somewhat reasonable default size #if PLATFORM_UNIX // Win32Native.ExpandEnvironmentStrings isn't available int lastPos = 0, pos; while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0) { if (name[lastPos] == '%') { string key = name.Substring(lastPos + 1, pos - lastPos - 1); string value = Environment.GetEnvironmentVariable(key); if (value != null) { blob.Append(value); lastPos = pos + 1; continue; } } blob.Append(name.Substring(lastPos, pos - lastPos)); lastPos = pos; } blob.Append(name.Substring(lastPos)); #else int size; blob.Length = 0; size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize); if (size == 0) Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); while (size > currentSize) { currentSize = size; blob.Capacity = currentSize; blob.Length = 0; size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize); if (size == 0) Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } #endif // PLATFORM_UNIX return blob.ToString(); } public static String MachineName { get { // UWP Debug scenarios if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode()) { // Getting Computer Name is not a supported scenario on Store apps. throw new PlatformNotSupportedException(); } // In future release of operating systems, you might be able to rename a machine without // rebooting. Therefore, don't cache this machine name. StringBuilder buf = new StringBuilder(MaxMachineNameLength); int len = MaxMachineNameLength; if (Win32Native.GetComputerName(buf, ref len) == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ComputerName")); return buf.ToString(); } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern Int32 GetProcessorCount(); public static int ProcessorCount { get { return GetProcessorCount(); } } /*==============================GetCommandLineArgs============================== **Action: Gets the command line and splits it appropriately to deal with whitespace, ** quotes, and escape characters. **Returns: A string array containing your command line arguments. **Arguments: None **Exceptions: None. ==============================================================================*/ public static String[] GetCommandLineArgs() { /* * There are multiple entry points to a hosted app. * The host could use ::ExecuteAssembly() or ::CreateDelegate option * ::ExecuteAssembly() -> In this particular case, the runtime invokes the main method based on the arguments set by the host, and we return those arguments * * ::CreateDelegate() -> In this particular case, the host is asked to create a * delegate based on the appDomain, assembly and methodDesc passed to it. * which the caller uses to invoke the method. In this particular case we do not have * any information on what arguments would be passed to the delegate. * So our best bet is to simply use the commandLine that was used to invoke the process. * in case it is present. */ if (s_CommandLineArgs != null) return (string[])s_CommandLineArgs.Clone(); return GetCommandLineArgsNative(); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String[] GetCommandLineArgsNative(); private static string[] s_CommandLineArgs = null; private static void SetCommandLineArgs(string[] cmdLineArgs) { s_CommandLineArgs = cmdLineArgs; } private unsafe static char[] GetEnvironmentCharArray() { char[] block = null; // Make sure pStrings is not leaked with async exceptions RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { char* pStrings = null; try { pStrings = Win32Native.GetEnvironmentStrings(); if (pStrings == null) { throw new OutOfMemoryException(); } // Format for GetEnvironmentStrings is: // [=HiddenVar=value\0]* [Variable=value\0]* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Search for terminating \0\0 (two unicode \0's). char* p = pStrings; while (!(*p == '\0' && *(p + 1) == '\0')) p++; int len = (int)(p - pStrings + 1); block = new char[len]; fixed (char* pBlock = block) string.wstrcpy(pBlock, pStrings, len); } finally { if (pStrings != null) Win32Native.FreeEnvironmentStrings(pStrings); } } return block; } /*===================================NewLine==================================== **Action: A property which returns the appropriate newline string for the given ** platform. **Returns: \r\n on Win32. **Arguments: None. **Exceptions: None. ==============================================================================*/ public static String NewLine { get { Contract.Ensures(Contract.Result<String>() != null); #if !PLATFORM_UNIX return "\r\n"; #else return "\n"; #endif // !PLATFORM_UNIX } } /*===================================Version==================================== **Action: Returns the COM+ version struct, describing the build number. **Returns: **Arguments: **Exceptions: ==============================================================================*/ public static Version Version { get { // Previously this represented the File version of mscorlib.dll. Many other libraries in the framework and outside took dependencies on the first three parts of this version // remaining constant throughout 4.x. From 4.0 to 4.5.2 this was fine since the file version only incremented the last part.Starting with 4.6 we switched to a file versioning // scheme that matched the product version. In order to preserve compatibility with existing libraries, this needs to be hard-coded. return new Version(4, 0, 30319, 42000); } } /*==================================OSVersion=================================== **Action: **Returns: **Arguments: **Exceptions: ==============================================================================*/ internal static OperatingSystem OSVersion { get { Contract.Ensures(Contract.Result<OperatingSystem>() != null); if (m_os == null) { // We avoid the lock since we don't care if two threads will set this at the same time. Microsoft.Win32.Win32Native.OSVERSIONINFO osvi = new Microsoft.Win32.Win32Native.OSVERSIONINFO(); if (!GetVersion(osvi)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GetVersion")); } Microsoft.Win32.Win32Native.OSVERSIONINFOEX osviEx = new Microsoft.Win32.Win32Native.OSVERSIONINFOEX(); if (!GetVersionEx(osviEx)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GetVersion")); #if PLATFORM_UNIX PlatformID id = PlatformID.Unix; #else PlatformID id = PlatformID.Win32NT; #endif // PLATFORM_UNIX Version v = new Version(osvi.MajorVersion, osvi.MinorVersion, osvi.BuildNumber, (osviEx.ServicePackMajor << 16) | osviEx.ServicePackMinor); m_os = new OperatingSystem(id, v, osvi.CSDVersion); } Debug.Assert(m_os != null, "m_os != null"); return m_os; } } internal static bool IsWindows8OrAbove { get { return true; } } #if FEATURE_COMINTEROP internal static bool IsWinRTSupported { get { return true; } } #endif // FEATURE_COMINTEROP [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool GetVersion(Microsoft.Win32.Win32Native.OSVERSIONINFO osVer); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool GetVersionEx(Microsoft.Win32.Win32Native.OSVERSIONINFOEX osVer); /*==================================StackTrace================================== **Action: **Returns: **Arguments: **Exceptions: ==============================================================================*/ public static String StackTrace { get { Contract.Ensures(Contract.Result<String>() != null); return GetStackTrace(null, true); } } internal static String GetStackTrace(Exception e, bool needFileInfo) { // Note: Setting needFileInfo to true will start up COM and set our // apartment state. Try to not call this when passing "true" // before the EE's ExecuteMainMethod has had a chance to set up the // apartment state. -- StackTrace st; if (e == null) st = new StackTrace(needFileInfo); else st = new StackTrace(e, needFileInfo); // Do no include a trailing newline for backwards compatibility return st.ToString(System.Diagnostics.StackTrace.TraceFormat.Normal); } private static void InitResourceHelper() { // Only the default AppDomain should have a ResourceHelper. All calls to // GetResourceString from any AppDomain delegate to GetResourceStringLocal // in the default AppDomain via the fcall GetResourceFromDefault. bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(Environment.InternalSyncObject, ref tookLock); if (m_resHelper == null) { ResourceHelper rh = new ResourceHelper(System.CoreLib.Name); System.Threading.Thread.MemoryBarrier(); m_resHelper = rh; } } finally { if (tookLock) Monitor.Exit(Environment.InternalSyncObject); } } // Looks up the resource string value for key. // // if you change this method's signature then you must change the code that calls it // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature // as well as metasig.h to create the new signature type internal static String GetResourceStringLocal(String key) { if (m_resHelper == null) InitResourceHelper(); return m_resHelper.GetResourceString(key); } internal static String GetResourceString(String key) { return GetResourceStringLocal(key); } // The reason the following overloads exist are to reduce code bloat. // Since GetResourceString is basically only called when exceptions are // thrown, we want the code size to be as small as possible. // Using the params object[] overload works against this since the // initialization of the array is done inline in the caller at the IL // level. So we have overloads that simply wrap the params one. [MethodImpl(MethodImplOptions.NoInlining)] internal static string GetResourceString(string key, object val0) { return GetResourceStringFormatted(key, new object[] { val0 }); } [MethodImpl(MethodImplOptions.NoInlining)] internal static string GetResourceString(string key, object val0, object val1) { return GetResourceStringFormatted(key, new object[] { val0, val1 }); } [MethodImpl(MethodImplOptions.NoInlining)] internal static string GetResourceString(string key, object val0, object val1, object val2) { return GetResourceStringFormatted(key, new object[] { val0, val1, val2 }); } [MethodImpl(MethodImplOptions.NoInlining)] internal static string GetResourceString(string key, object val0, object val1, object val2, object val3) { return GetResourceStringFormatted(key, new object[] { val0, val1, val2, val3 }); } [MethodImpl(MethodImplOptions.NoInlining)] internal static String GetResourceString(string key, params object[] values) { return GetResourceStringFormatted(key, values); } private static String GetResourceStringFormatted(string key, params object[] values) { string rs = GetResourceString(key); return String.Format(CultureInfo.CurrentCulture, rs, values); } public static extern bool HasShutdownStarted { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } internal static bool UserInteractive { get { return true; } } public static int CurrentManagedThreadId { get { return Thread.CurrentThread.ManagedThreadId; } } internal static extern int CurrentProcessorNumber { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } // The upper bits of t_executionIdCache are the executionId. The lower bits of // the t_executionIdCache are counting down to get it periodically refreshed. // TODO: Consider flushing the executionIdCache on Wait operations or similar // actions that are likely to result in changing the executing core [ThreadStatic] private static int t_executionIdCache; private const int ExecutionIdCacheShift = 16; private const int ExecutionIdCacheCountDownMask = (1 << ExecutionIdCacheShift) - 1; private const int ExecutionIdRefreshRate = 5000; private static int RefreshExecutionId() { int executionId = CurrentProcessorNumber; // On Unix, CurrentProcessorNumber is implemented in terms of sched_getcpu, which // doesn't exist on all platforms. On those it doesn't exist on, GetCurrentProcessorNumber // returns -1. As a fallback in that case and to spread the threads across the buckets // by default, we use the current managed thread ID as a proxy. if (executionId < 0) executionId = Environment.CurrentManagedThreadId; Debug.Assert(ExecutionIdRefreshRate <= ExecutionIdCacheCountDownMask); // Mask with Int32.MaxValue to ensure the execution Id is not negative t_executionIdCache = ((executionId << ExecutionIdCacheShift) & Int32.MaxValue) | ExecutionIdRefreshRate; return executionId; } // Cached processor number used as a hint for which per-core stack to access. It is periodically // refreshed to trail the actual thread core affinity. internal static int CurrentExecutionId { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { int executionIdCache = t_executionIdCache--; if ((executionIdCache & ExecutionIdCacheCountDownMask) == 0) return RefreshExecutionId(); return (executionIdCache >> ExecutionIdCacheShift); } } public static string GetEnvironmentVariable(string variable) { if (variable == null) { throw new ArgumentNullException(nameof(variable)); } // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case return GetEnvironmentVariableCore(variable); } internal static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) { if (variable == null) { throw new ArgumentNullException(nameof(variable)); } ValidateTarget(target); return GetEnvironmentVariableCore(variable, target); } public static IDictionary GetEnvironmentVariables() { // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case return GetEnvironmentVariablesCore(); } internal static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target) { ValidateTarget(target); return GetEnvironmentVariablesCore(target); } public static void SetEnvironmentVariable(string variable, string value) { ValidateVariableAndValue(variable, ref value); // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case SetEnvironmentVariableCore(variable, value); } internal static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) { ValidateVariableAndValue(variable, ref value); ValidateTarget(target); SetEnvironmentVariableCore(variable, value, target); } private static void ValidateVariableAndValue(string variable, ref string value) { const int MaxEnvVariableValueLength = 32767; if (variable == null) { throw new ArgumentNullException(nameof(variable)); } if (variable.Length == 0) { throw new ArgumentException(GetResourceString("Argument_StringZeroLength"), nameof(variable)); } if (variable[0] == '\0') { throw new ArgumentException(GetResourceString("Argument_StringFirstCharIsZero"), nameof(variable)); } if (variable.Length >= MaxEnvVariableValueLength) { throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable)); } if (variable.IndexOf('=') != -1) { throw new ArgumentException(GetResourceString("Argument_IllegalEnvVarName"), nameof(variable)); } if (string.IsNullOrEmpty(value) || value[0] == '\0') { // Explicitly null out value if it's empty value = null; } else if (value.Length >= MaxEnvVariableValueLength) { throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(value)); } } private static void ValidateTarget(EnvironmentVariableTarget target) { if (target != EnvironmentVariableTarget.Process && target != EnvironmentVariableTarget.Machine && target != EnvironmentVariableTarget.User) { throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(GetResourceString("Arg_EnumIllegalVal"), target)); } } private static Dictionary<string, string> GetRawEnvironmentVariables() { // Format for GetEnvironmentStrings is: // (=HiddenVar=value\0 | Variable=value\0)* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Note the =HiddenVar's aren't always at the beginning. // Copy strings out, parsing into pairs and inserting into the table. // The first few environment variable entries start with an '='. // The current working directory of every drive (except for those drives // you haven't cd'ed into in your DOS window) are stored in the // environment block (as =C:=pwd) and the program's exit code is // as well (=ExitCode=00000000). var results = new Dictionary<string, string>(); char[] block = GetEnvironmentCharArray(); for (int i = 0; i < block.Length; i++) { int startKey = i; // Skip to key. On some old OS, the environment block can be corrupted. // Some will not have '=', so we need to check for '\0'. while (block[i] != '=' && block[i] != '\0') i++; if (block[i] == '\0') continue; // Skip over environment variables starting with '=' if (i - startKey == 0) { while (block[i] != 0) i++; continue; } string key = new string(block, startKey, i - startKey); i++; // skip over '=' int startValue = i; while (block[i] != 0) i++; // Read to end of this entry string value = new string(block, startValue, i - startValue); // skip over 0 handled by for loop's i++ results[key] = value; } return results; } private static string GetEnvironmentVariableCore(string variable) { if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode()) { // Environment variable accessors are not approved modern API. // Behave as if the variable was not found in this case. return null; } StringBuilder sb = StringBuilderCache.Acquire(128); // A somewhat reasonable default size int requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity); if (requiredSize == 0 && Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND) { StringBuilderCache.Release(sb); return null; } while (requiredSize > sb.Capacity) { sb.Capacity = requiredSize; sb.Length = 0; requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity); } return StringBuilderCache.GetStringAndRelease(sb); } private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariableCore(variable); #if !FEATURE_WIN32_REGISTRY return null; #else RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { Debug.Assert(target == EnvironmentVariableTarget.User); baseKey = Registry.CurrentUser; keyName = "Environment"; } else { throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false)) { return environmentKey?.GetValue(variable) as string; } #endif } private static IDictionary GetEnvironmentVariablesCore() { if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode()) { // Environment variable accessors are not approved modern API. // Behave as if no environment variables are defined in this case. return new Dictionary<string, string>(0); } return GetRawEnvironmentVariables(); } private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariablesCore(); #if !FEATURE_WIN32_REGISTRY // Without registry support we have nothing to return return new Dictionary<string, string>(0); #else RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { Debug.Assert(target == EnvironmentVariableTarget.User); baseKey = Registry.CurrentUser; keyName = @"Environment"; } else { throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false)) { var table = new Dictionary<string, string>(); if (environmentKey != null) { foreach (string name in environmentKey.GetValueNames()) { table.Add(name, environmentKey.GetValue(name, "").ToString()); } } return table; } #endif // FEATURE_WIN32_REGISTRY } private static void SetEnvironmentVariableCore(string variable, string value) { // explicitly null out value if is the empty string. if (string.IsNullOrEmpty(value) || value[0] == '\0') value = null; if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode()) { // Environment variable accessors are not approved modern API. // so we throw PlatformNotSupportedException. throw new PlatformNotSupportedException(); } if (!Win32Native.SetEnvironmentVariable(variable, value)) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case Win32Native.ERROR_ENVVAR_NOT_FOUND: // Allow user to try to clear a environment variable return; case Win32Native.ERROR_FILENAME_EXCED_RANGE: // The error message from Win32 is "The filename or extension is too long", // which is not accurate. throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue")); default: throw new ArgumentException(Win32Native.GetMessage(errorCode)); } } } private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { SetEnvironmentVariableCore(variable, value); return; } #if !FEATURE_WIN32_REGISTRY // other targets ignored return; #else // explicitly null out value if is the empty string. if (string.IsNullOrEmpty(value) || value[0] == '\0') value = null; RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { Debug.Assert(target == EnvironmentVariableTarget.User); // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name. const int MaxUserEnvVariableLength = 255; if (variable.Length >= MaxUserEnvVariableLength) { throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable)); } baseKey = Registry.CurrentUser; keyName = "Environment"; } else { throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true)) { if (environmentKey != null) { if (value == null) { environmentKey.DeleteValue(variable, throwOnMissingValue: false); } else { environmentKey.SetValue(variable, value); } } } // send a WM_SETTINGCHANGE message to all windows IntPtr r = Win32Native.SendMessageTimeout(new IntPtr(Win32Native.HWND_BROADCAST), Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero); if (r == IntPtr.Zero) Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error()); #endif // FEATURE_WIN32_REGISTRY } } }
using Aspose.Email.Live.Demos.UI.Helpers; using Aspose.Email; using Aspose.Email.Mapi; using Aspose.Html; using Aspose.Imaging; using Aspose.Imaging.Brushes; using Aspose.Imaging.ImageOptions; using Aspose.Imaging.Sources; using System; using System.IO; using Graphics = Aspose.Imaging.Graphics; using Image = Aspose.Imaging.Image; using System.Linq; namespace Aspose.Email.Live.Demos.UI.Services.Email { public partial class EmailService { public void AddTextWatermark(Stream input, string inputFileNameWithExtension, string watermarkText, string fontFamily, string watermarkColor, IOutputHandler handler) { using (var mail = MapiHelper.GetMapiMessageFromStream(input, out FileFormatInfo formatInfo)) { var html = mail.BodyHtml; var htmlDocument = new Aspose.Html.HTMLDocument(mail.BodyHtml, ""); var options = new PngOptions(); options.Source = new StreamSource(new MemoryStream(), true); var width = watermarkText.Length * 17; var height = 120; using (Image image = Image.Create(options, width, height)) { // Create graphics object to perform draw operations. var graphics = new Graphics(image); // Create font to draw watermark with. var font = new Aspose.Imaging.Font(fontFamily, 20.0f); // Create a solid brush with color alpha set near to 0 to use watermarking effect. using (SolidBrush backgroundBrush = new SolidBrush(Color.White)) { using (SolidBrush brush = new SolidBrush(GetColor(watermarkColor))) { // Specify string alignment to put watermark at the image center. StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; graphics.FillRectangle(backgroundBrush, new Rectangle(0, 0, image.Width, image.Height)); // Draw watermark using font, partly-transparent brush and rotation matrix at the image center. graphics.DrawString(watermarkText, font, brush, new RectangleF(0, 0, image.Width, image.Height), sf); } } var ms = new MemoryStream(); image.Save(ms); mail.Attachments.Add("watermark", ms.ToArray()); } var attachment = mail.Attachments.Find(x => x.LongFileName == "watermark"); attachment.SetContentId("watermark"); var bodyHtml = htmlDocument.Body.InnerHTML; var watermarkHtml = $@"<table role=""presentation"" style=""width:100%; height:1200px; background-image:url(cid:watermark); background-repeat:repeat; table-layout: fixed;"" cellpadding=""0"" cellspacing=""0"" border=""0""> <tr> <td valign=""top"" style=""width:100%; height:1200px; background-size:cover; background-image:url(cid:watermark); background-repeat:repeat; word-break: normal; border-collapse : collapse !important;""> <!--[if gte mso 9]> <v:rect xmlns:v=""urn:schemas-microsoft-com:vml"" fill=""true"" filltype=""tile"" stroke=""false"" style=""height:1200px; width:640px; border: 0;display: inline-block;position: absolute; background-image:url(cid:watermark); background-repeat:repeat; word-break: normal; border-collapse : collapse !important; mso-position-vertical-relative:text;""> <v:fill type=""tile"" opacity=""100%"" src=""cid:watermark"" /> <v:textbox inset=""0,0,0,0""> <![endif]--> <div> {bodyHtml} </div> <!--[if gte mso 9]>\ </v:textbox> </v:fill> </v:rect> <![endif]--> </td> </tr> </table>"; htmlDocument.Body.InnerHTML = watermarkHtml; var content = htmlDocument.ToHTMLContentString(); mail.SetBodyContent(content, BodyContentType.Html); if (formatInfo.FileFormatType == FileFormatType.Msg) { using (var output = handler.CreateOutputStream(Path.ChangeExtension(inputFileNameWithExtension, ".marked.msg"))) mail.Save(output, SaveOptions.DefaultMsgUnicode); } else { using (var output = handler.CreateOutputStream(Path.ChangeExtension(inputFileNameWithExtension, ".marked.eml"))) mail.Save(output, SaveOptions.DefaultEml); } } } public void AddImageWatermark(Stream input, string inputFileNameWithExtension, byte[] imageBytes, IOutputHandler handler) { using (var mail = MapiHelper.GetMapiMessageFromStream(input, out FileFormatInfo formatInfo)) { mail.Attachments.Add("watermark", imageBytes); var html = mail.BodyHtml; var htmlDocument = new Aspose.Html.HTMLDocument(mail.BodyHtml, ""); var attachment = mail.Attachments.Find(x => x.LongFileName == "watermark"); attachment.SetContentId("watermark"); var bodyHtml = htmlDocument.Body.InnerHTML; var watermarkHtml = $@"<table role=""presentation"" style=""width:100%; height:1200px; background-image:url(cid:watermark); background-repeat:repeat; table-layout: fixed;"" cellpadding=""0"" cellspacing=""0"" border=""0""> <tr> <td valign=""top"" style=""width:100%; height:1200px; background-size:cover; background-image:url(cid:watermark); background-repeat:repeat; word-break: normal; border-collapse : collapse !important;""> <!--[if gte mso 9]> <v:rect xmlns:v=""urn:schemas-microsoft-com:vml"" fill=""true"" filltype=""tile"" stroke=""false"" style=""height:1200px; width:640px; border: 0;display: inline-block;position: absolute; background-image:url(cid:watermark); background-repeat:repeat; word-break: normal; border-collapse : collapse !important; mso-position-vertical-relative:text;""> <v:fill type=""tile"" opacity=""100%"" src=""cid:watermark"" /> <v:textbox inset=""0,0,0,0""> <![endif]--> <div> {bodyHtml} </div> <!--[if gte mso 9]>\ </v:textbox> </v:fill> </v:rect> <![endif]--> </td> </tr> </table>"; htmlDocument.Body.InnerHTML = watermarkHtml; var content = htmlDocument.ToHTMLContentString(); mail.SetBodyContent(content, BodyContentType.Html); if (formatInfo.FileFormatType == FileFormatType.Msg) { using (var output = handler.CreateOutputStream(Path.ChangeExtension(inputFileNameWithExtension, ".marked.msg"))) mail.Save(output, SaveOptions.DefaultMsgUnicode); } else { using (var output = handler.CreateOutputStream(Path.ChangeExtension(inputFileNameWithExtension, ".marked.eml"))) mail.Save(output, SaveOptions.DefaultEml); } } } public void RemoveWatermark(Stream input, string inputFileNameWithExtension, IOutputHandler handler) { using (var mail = MapiHelper.GetMapiMessageFromStream(input, out FileFormatInfo formatInfo)) { var html = mail.BodyHtml; var htmlDocument = new Aspose.Html.HTMLDocument(mail.BodyHtml, ""); var attachment = mail.Attachments.Find(x => x.LongFileName.Equals("watermark", StringComparison.OrdinalIgnoreCase)); if (attachment != null) mail.Attachments.Remove(attachment); // Remove body backgrounds htmlDocument.Body.RemoveAttribute("background"); htmlDocument.Body.Style.Background = string.Empty; htmlDocument.Body.Style.BackgroundImage = string.Empty; HTMLElement element = htmlDocument.Body; // Remove background from all single elements. do { // Skip unnecessary elements element = (HTMLElement)element.Children.Where(x => !(x is HTMLTitleElement) && !(x is HTMLStyleElement)).ElementAt(0); // Process only default tags for watermark if (element.NodeName != "TABLE" && element.NodeName != "TITLE" && element.NodeName != "TR" && element.NodeName != "TD" && element.NodeName != "TBODY") { // If reached div, content starting here if (element.NodeName == "DIV") htmlDocument.Body.InnerHTML = element.InnerHTML; break; } // Remove comments for (int i = 0; i < element.ChildNodes.Length; i++) { var node = element.ChildNodes[i]; if (node.NodeType == Html.Dom.Node.COMMENT_NODE && node.NodeValue != null && node.NodeValue.StartsWith("[if gte mso 9]", StringComparison.OrdinalIgnoreCase)) { element.RemoveChild(node); i--; } } element.Style.Background = string.Empty; element.Style.BackgroundImage = string.Empty; } while (element.ChildElementCount == 1); var content = htmlDocument.ToHTMLContentString(); mail.SetBodyContent(content, BodyContentType.Html); if (formatInfo.FileFormatType == FileFormatType.Msg) { using (var output = handler.CreateOutputStream(Path.ChangeExtension(inputFileNameWithExtension, ".unmarked.msg"))) mail.Save(output, SaveOptions.DefaultMsgUnicode); } else { using (var output = handler.CreateOutputStream(Path.ChangeExtension(inputFileNameWithExtension, ".unmarked.eml"))) mail.Save(output, SaveOptions.DefaultEml); } } } private Color GetColor(string watermarkColor) { Color color; if (!watermarkColor.IsNullOrWhiteSpace()) { if (!watermarkColor.StartsWith("#")) { watermarkColor = "#" + watermarkColor; } System.Drawing.Color sColor = System.Drawing.ColorTranslator.FromHtml(watermarkColor); color = Color.FromArgb(sColor.A, sColor.R, sColor.G, sColor.B); } else { color = Color.FromArgb(50, 128, 128, 128); } return color; } } }
// SampSharp // Copyright 2017 Tim Potze // // 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 SampSharp.GameMode.Helpers; namespace SampSharp.GameMode { /// <summary> /// Represents a 2D vector. /// </summary> public struct Vector2 : IEquatable<Vector2> { /// <summary> /// Initializes a new instance of the <see cref="Vector2" /> struct. /// </summary> /// <param name="x">Value of the x component.</param> /// <param name="y">Value of the y component.</param> public Vector2(float x, float y) : this() { X = x; Y = y; } /// <summary> /// Initializes a new instance of the <see cref="Vector2" /> struct. /// </summary> /// <param name="x">Value of the x component.</param> /// <param name="y">Value of the y component.</param> public Vector2(double x, double y) : this((float) x, (float) y) { } /// <summary> /// Initializes a new instance of the <see cref="Vector2" /> struct with same values for x and y components. /// </summary> /// <param name="xy">Value of x and y components.</param> public Vector2(float xy) : this(xy, xy) { } /// <summary> /// Initializes a new instance of the <see cref="Vector2" /> struct with same values for x and y components. /// </summary> /// <param name="xy">Value of x and y components.</param> public Vector2(double xy) : this((float) xy) { } /// <summary> /// Gets the X component of this <see cref="Vector2" />. /// </summary> public float X { get; } /// <summary> /// Gets the Y component of this <see cref="Vector2" />. /// </summary> public float Y { get; } /// <summary> /// Returns an empty <see cref="Vector2" />. /// </summary> public static Vector2 Zero { get; } = new Vector2(0); /// <summary> /// Returns a <see cref="Vector2" /> with each component set to 1. /// </summary> public static Vector2 One { get; } = new Vector2(1); /// <summary> /// Returns a <see cref="Vector2" /> with components 1, 0. /// </summary> public static Vector2 UnitX { get; } = new Vector2(1, 0); /// <summary> /// Returns a <see cref="Vector2" /> with components 0, 1. /// </summary> public static Vector2 UnitY { get; } = new Vector2(0, 1); /// <summary> /// Gets the length of this <see cref="Vector2" />. /// </summary> public float Length => Distance(this, Zero); /// <summary> /// Gets the squared length of this <see cref="Vector2" />. /// </summary> public float SquaredLength => DistanceSquared(this, Zero); /// <summary> /// Gets whether this <see cref="Vector2" /> is empty. /// </summary> public bool IsEmpty => X.Equals(0.0f) && Y.Equals(0.0f); /// <summary> /// Gets the distance to another <see cref="Vector2" />. /// </summary> /// <param name="other">The <see cref="Vector2" /> to calculate the distance to.</param> /// <returns>The distance between the vectors.</returns> public float DistanceTo(Vector2 other) { return Distance(this, other); } /// <summary> /// Creates a new <see cref="Vector2" /> instance with the components normalized to a single unit. /// </summary> public Vector2 Normalized() { return Normalize(this); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains the cartesian coordinates of a vector specified in barycentric /// coordinates and relative to 2d-triangle. /// </summary> /// <param name="value1">The first vector of 2d-triangle.</param> /// <param name="value2">The second vector of 2d-triangle.</param> /// <param name="value3">The third vector of 2d-triangle.</param> /// <param name="amount1"> /// Barycentric scalar <c>b2</c> which represents a weighting factor towards second vector of /// 2d-triangle. /// </param> /// <param name="amount2"> /// Barycentric scalar <c>b3</c> which represents a weighting factor towards third vector of /// 2d-triangle. /// </param> /// <returns>The cartesian translation of barycentric coordinates.</returns> public static Vector2 Barycentric(Vector2 value1, Vector2 value2, Vector2 value3, float amount1, float amount2) { return new Vector2( MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2)); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains CatmullRom interpolation of the specified vectors. /// </summary> /// <param name="value1">The first vector in interpolation.</param> /// <param name="value2">The second vector in interpolation.</param> /// <param name="value3">The third vector in interpolation.</param> /// <param name="value4">The fourth vector in interpolation.</param> /// <param name="amount">Weighting factor.</param> /// <returns>The result of CatmullRom interpolation.</returns> public static Vector2 CatmullRom(Vector2 value1, Vector2 value2, Vector2 value3, Vector2 value4, float amount) { return new Vector2( MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount)); } /// <summary> /// Clamps the specified value within a range. /// </summary> /// <param name="value1">The value to clamp.</param> /// <param name="min">The min value.</param> /// <param name="max">The max value.</param> /// <returns>The clamped value.</returns> public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { return new Vector2( MathHelper.Clamp(value1.X, min.X, max.X), MathHelper.Clamp(value1.Y, min.Y, max.Y)); } /// <summary> /// Returns the distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The distance between two vectors.</returns> public static float Distance(Vector2 value1, Vector2 value2) { float v1 = value1.X - value2.X, v2 = value1.Y - value2.Y; return (float) Math.Sqrt(v1*v1 + v2*v2); } /// <summary> /// Returns the squared distance between two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The squared distance between two vectors.</returns> public static float DistanceSquared(Vector2 value1, Vector2 value2) { float v1 = value1.X - value2.X, v2 = value1.Y - value2.Y; return v1*v1 + v2*v2; } /// <summary> /// Returns a dot product of two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The dot product of two vectors.</returns> public static float Dot(Vector2 value1, Vector2 value2) { return value1.X*value2.X + value1.Y*value2.Y; } /// <summary> /// Creates a new <see cref="Vector2" /> that contains hermite spline interpolation. /// </summary> /// <param name="value1">The first position vector.</param> /// <param name="tangent1">The first tangent vector.</param> /// <param name="value2">The second position vector.</param> /// <param name="tangent2">The second tangent vector.</param> /// <param name="amount">Weighting factor.</param> /// <returns>The hermite spline interpolation vector.</returns> public static Vector2 Hermite(Vector2 value1, Vector2 tangent1, Vector2 value2, Vector2 tangent2, float amount) { return new Vector2(MathHelper.Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount), MathHelper.Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount)); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains linear interpolation of the specified vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <param name="amount">Weighting value(between 0.0 and 1.0).</param> /// <returns>The result of linear interpolation of the specified vectors.</returns> public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) { return new Vector2( MathHelper.Lerp(value1.X, value2.X, amount), MathHelper.Lerp(value1.Y, value2.Y, amount)); } /// <summary> /// Adds the left <see cref="Vector2" />'s components to the right <see cref="Vector2" />'s components and stores it in /// a /// new <see cref="Vector2" />. /// </summary> /// <param name="left">A <see cref="Vector2" />.</param> /// <param name="right">A <see cref="Vector2" />.</param> /// <returns>A new <see cref="Vector2" />.</returns> public static Vector2 operator +(Vector2 left, Vector2 right) { return new Vector2(left.X + right.X, left.Y + right.Y); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains a maximal values from the two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The <see cref="Vector2" /> with maximal values from the two vectors.</returns> public static Vector2 Max(Vector2 value1, Vector2 value2) { return new Vector2(value1.X > value2.X ? value1.X : value2.X, value1.Y > value2.Y ? value1.Y : value2.Y); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains a minimal values from the two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The <see cref="Vector2" /> with minimal values from the two vectors.</returns> public static Vector2 Min(Vector2 value1, Vector2 value2) { return new Vector2(value1.X < value2.X ? value1.X : value2.X, value1.Y < value2.Y ? value1.Y : value2.Y); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains a normalized values from another vector. /// </summary> /// <param name="value">Source <see cref="Vector2" />.</param> /// <returns>Unit vector.</returns> public static Vector2 Normalize(Vector2 value) { var val = 1.0f/(float) Math.Sqrt(value.X*value.X + value.Y*value.Y); return new Vector2(value.X*val, value.Y*val); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains reflect vector of the given vector and normal. /// </summary> /// <param name="vector">Source <see cref="Vector2" />.</param> /// <param name="normal">Reflection normal.</param> /// <returns>Reflected vector.</returns> public static Vector2 Reflect(Vector2 vector, Vector2 normal) { var val = 2.0f*(vector.X*normal.X + vector.Y*normal.Y); return new Vector2(vector.X - normal.X*val, vector.Y - normal.Y*val); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains cubic interpolation of the specified vectors. /// </summary> /// <param name="value1">Source <see cref="Vector2" />.</param> /// <param name="value2">Source <see cref="Vector2" />.</param> /// <param name="amount">Weighting value.</param> /// <returns>Cubic interpolation of the specified vectors.</returns> public static Vector2 SmoothStep(Vector2 value1, Vector2 value2, float amount) { return new Vector2( MathHelper.SmoothStep(value1.X, value2.X, amount), MathHelper.SmoothStep(value1.Y, value2.Y, amount)); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains a transformation of 2d-vector by the specified /// <see cref="Matrix" />. /// </summary> /// <param name="position">Source <see cref="Vector2" />.</param> /// <param name="matrix">The transformation <see cref="Matrix" />.</param> /// <returns>Transformed <see cref="Vector2" />.</returns> public static Vector2 Transform(Vector2 position, Matrix matrix) { return new Vector2(position.X*matrix.M11 + position.Y*matrix.M21 + matrix.M41, position.X*matrix.M12 + position.Y*matrix.M22 + matrix.M42); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains a transformation of 2d-vector by the specified /// <see cref="Quaternion" />, representing the rotation. /// </summary> /// <param name="value">Source <see cref="Vector2" />.</param> /// <param name="rotation">The <see cref="Quaternion" /> which contains rotation transformation.</param> /// <returns>Transformed <see cref="Vector2" />.</returns> public static Vector2 Transform(Vector2 value, Quaternion rotation) { var rot1 = new Vector3(-rotation.X - rotation.X, -rotation.Y - rotation.Y, -rotation.Z - rotation.Z); var rot2 = new Vector3(-rotation.X, -rotation.X, rotation.W); var rot3 = new Vector3(1, -rotation.Y, -rotation.Z); var rot4 = rot1*rot2; var rot5 = rot1*rot3; return new Vector2( (float) (value.X*(1.0 - rot5.Y - rot5.Z) + value.Y*((double) rot4.Y - rot4.Z)), (float) (value.X*((double) rot4.Y + rot4.Z) + value.Y*(1.0 - rot4.X - rot5.Z)) ); } /// <summary> /// Creates a new <see cref="Vector2" /> that contains a transformation of the specified normal by the specified /// <see cref="Matrix" />. /// </summary> /// <param name="normal">Source <see cref="Vector2" /> which represents a normal vector.</param> /// <param name="matrix">The transformation <see cref="Matrix" />.</param> /// <returns>Transformed normal.</returns> public static Vector2 TransformNormal(Vector2 normal, Matrix matrix) { return new Vector2(normal.X*matrix.M11 + normal.Y*matrix.M21, normal.X*matrix.M12 + normal.Y*matrix.M22); } /// <summary> /// Subtracts the right <see cref="Vector2" />'s components from the left <see cref="Vector2" />'s components and /// stores /// it in a new <see cref="Vector2" />. /// </summary> /// <param name="left">A <see cref="Vector2" />.</param> /// <param name="right">A <see cref="Vector2" />.</param> /// <returns>A new <see cref="Vector2" />.</returns> public static Vector2 operator -(Vector2 left, Vector2 right) { return new Vector2(left.X - right.X, left.Y - right.Y); } /// <summary> /// Creates a <see cref="Vector2" /> with the components set to the negative values of the given /// <paramref name="vector" />'s components. /// </summary> /// <param name="vector">The vector to invert.</param> /// <returns>The new <see cref="Vector2" />.</returns> public static Vector2 operator -(Vector2 vector) { return new Vector2(-vector.X, -vector.Y); } /// <summary> /// Multiplies the components <see cref="Vector2" /> by the given scalar and stores them in a new /// <see cref="Vector2" />. /// </summary> /// <param name="scalar">The scalar.</param> /// <param name="vector">The <see cref="Vector2" />.</param> /// <returns>The new <see cref="Vector2" />.</returns> public static Vector2 operator *(float scalar, Vector2 vector) { return new Vector2(vector.X*scalar, vector.Y*scalar); } /// <summary> /// Multiplies the components <see cref="Vector2" /> by the given scalar and stores them in a new /// <see cref="Vector2" />. /// </summary> /// <param name="vector">The <see cref="Vector2" />.</param> /// <param name="scalar">The scalar.</param> /// <returns>The new <see cref="Vector2" />.</returns> public static Vector2 operator *(Vector2 vector, float scalar) { return new Vector2(vector.X*scalar, vector.Y*scalar); } /// <summary> /// Multiplies the components <see cref="Vector2" /> by the components of the right <see cref="Vector2" /> and stores /// them in a new <see cref="Vector2" />. /// </summary> /// <param name="left">A <see cref="Vector2" />.</param> /// <param name="right">A <see cref="Vector2" />.</param> /// <returns>The new <see cref="Vector2" />.</returns> public static Vector2 operator *(Vector2 left, Vector2 right) { return new Vector2(left.X*right.X, left.Y*right.Y); } /// <summary> /// Divides the components <see cref="Vector2" /> by the given scalar and stores them in a new <see cref="Vector2" />. /// </summary> /// <param name="vector">The <see cref="Vector2" />.</param> /// <param name="scalar">The scalar.</param> /// <returns>The new <see cref="Vector2" />.</returns> public static Vector2 operator /(Vector2 vector, float scalar) { return new Vector2(vector.X/scalar, vector.Y/scalar); } /// <summary> /// Divides the components <see cref="Vector2" /> by the components of the right <see cref="Vector2" /> and stores them /// in a new <see cref="Vector2" />. /// </summary> /// <param name="left">The numerator.</param> /// <param name="right">The denominator.</param> /// <returns>The new <see cref="Vector2" />.</returns> public static Vector2 operator /(Vector2 left, Vector2 right) { return new Vector2(left.X/right.X, left.Y/right.Y); } /// <summary> /// Tests whether all components of both <see cref="Vector2" /> are equivalent. /// </summary> /// <param name="left">Instance of <see cref="Vector2" /> to compare.</param> /// <param name="right">Instance of <see cref="Vector2" /> to compare.</param> /// <returns>true if all components of both <see cref="Vector2" /> are equivalent; otherwise, false.</returns> public static bool operator ==(Vector2 left, Vector2 right) { return left.Equals(right); } /// <summary> /// Tests whether any component of both <see cref="Vector2" /> are not equivalent. /// </summary> /// <param name="left">Instance of <see cref="Vector2" /> to compare.</param> /// <param name="right">Instance of <see cref="Vector2" /> to compare.</param> /// <returns>true if any component of both <see cref="Vector2" /> are not equivalent; otherwise, false.</returns> public static bool operator !=(Vector2 left, Vector2 right) { return !left.Equals(right); } #region Equality members /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <returns> /// true if <paramref name="obj" /> and this instance are the same type and represent the same value; otherwise, false. /// </returns> /// <param name="obj">The object to compare with the current instance. </param> public bool Equals(Vector2 obj) { return X.Equals(obj.X) && Y.Equals(obj.Y); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <returns> /// true if <paramref name="obj" /> and this instance are the same type and represent the same value; otherwise, false. /// </returns> /// <param name="obj">The object to compare with the current instance. </param> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is Vector2 vector && Equals(vector); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns> /// A 32-bit signed integer that is the hash code for this instance. /// </returns> public override int GetHashCode() { unchecked { return (X.GetHashCode()*397) ^ Y.GetHashCode(); } } #endregion /// <summary> /// Returns the fully qualified type name of this instance. /// </summary> /// <returns> /// A <see cref="T:System.String" /> containing a fully qualified type name. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() { return $"({X}, {Y})"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // #define StressTest // set to raise the amount of time spent in concurrency tests that stress the collections using System; using System.Collections.Generic; using System.Collections.Tests; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public abstract class ProducerConsumerCollectionTests : IEnumerable_Generic_Tests<int> { protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>(); protected override int CreateT(int seed) => new Random(seed).Next(); protected override EnumerableOrder Order => EnumerableOrder.Unspecified; protected override IEnumerable<int> GenericIEnumerableFactory(int count) => CreateProducerConsumerCollection(count); protected IProducerConsumerCollection<int> CreateProducerConsumerCollection() => CreateProducerConsumerCollection<int>(); protected IProducerConsumerCollection<int> CreateProducerConsumerCollection(int count) => CreateProducerConsumerCollection(Enumerable.Range(0, count)); protected abstract IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>(); protected abstract IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection); protected abstract bool IsEmpty(IProducerConsumerCollection<int> pcc); protected abstract bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result); protected virtual IProducerConsumerCollection<int> CreateOracle() => CreateOracle(Enumerable.Empty<int>()); protected abstract IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection); protected static TaskFactory ThreadFactory { get; } = new TaskFactory( CancellationToken.None, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default); private const double ConcurrencyTestSeconds = #if StressTest 8.0; #else 1.0; #endif protected virtual string CopyToNoLengthParamName => "destinationArray"; [Fact] public void Ctor_InvalidArgs_Throws() { AssertExtensions.Throws<ArgumentNullException>("collection", () => CreateProducerConsumerCollection(null)); } [Fact] public void Ctor_NoArg_ItemsAndCountMatch() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Equal(0, c.Count); Assert.True(IsEmpty(c)); Assert.Equal(Enumerable.Empty<int>(), c); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(1000)] public void Ctor_Collection_ItemsAndCountMatch(int count) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, count)); IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(1, count)); Assert.Equal(oracle.Count == 0, IsEmpty(c)); Assert.Equal(oracle.Count, c.Count); Assert.Equal<int>(oracle, c); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(3)] [InlineData(1000)] public void Ctor_InitializeFromCollection_ContainsExpectedItems(int numItems) { var expected = new HashSet<int>(Enumerable.Range(0, numItems)); IProducerConsumerCollection<int> pcc = CreateProducerConsumerCollection(expected); Assert.Equal(expected.Count, pcc.Count); int item; var actual = new HashSet<int>(); for (int i = 0; i < expected.Count; i++) { Assert.Equal(expected.Count - i, pcc.Count); Assert.True(pcc.TryTake(out item)); actual.Add(item); } Assert.False(pcc.TryTake(out item)); Assert.Equal(0, item); AssertSetsEqual(expected, actual); } [Fact] public void Add_TakeFromAnotherThread_ExpectedItemsTaken() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.True(IsEmpty(c)); Assert.Equal(0, c.Count); const int NumItems = 100000; Task producer = Task.Run(() => Parallel.For(1, NumItems + 1, i => Assert.True(c.TryAdd(i)))); var hs = new HashSet<int>(); while (hs.Count < NumItems) { int item; if (c.TryTake(out item)) hs.Add(item); } producer.GetAwaiter().GetResult(); Assert.True(IsEmpty(c)); Assert.Equal(0, c.Count); AssertSetsEqual(new HashSet<int>(Enumerable.Range(1, NumItems)), hs); } [Fact] public void AddSome_ThenInterleaveAddsAndTakes_MatchesOracle() { IProducerConsumerCollection<int> c = CreateOracle(); IProducerConsumerCollection<int> oracle = CreateProducerConsumerCollection(); Action take = () => { int item1; Assert.True(c.TryTake(out item1)); int item2; Assert.True(oracle.TryTake(out item2)); Assert.Equal(item1, item2); Assert.Equal(c.Count, oracle.Count); Assert.Equal<int>(c, oracle); }; for (int i = 0; i < 100; i++) { Assert.True(oracle.TryAdd(i)); Assert.True(c.TryAdd(i)); Assert.Equal(c.Count, oracle.Count); Assert.Equal<int>(c, oracle); // Start taking some after we've added some if (i > 50) { take(); } } // Take the rest while (c.Count > 0) { take(); } } [Fact] public void AddTake_RandomChangesMatchOracle() { const int Iters = 1000; var r = new Random(42); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IProducerConsumerCollection<int> oracle = CreateOracle(); for (int i = 0; i < Iters; i++) { if (r.NextDouble() < .5) { Assert.Equal(oracle.TryAdd(i), c.TryAdd(i)); } else { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); } } Assert.Equal(oracle.Count, c.Count); } [Theory] [InlineData(100, 1, 100, true)] [InlineData(100, 4, 10, false)] [InlineData(1000, 11, 100, true)] [InlineData(100000, 2, 50000, true)] public void Initialize_ThenTakeOrPeekInParallel_ItemsObtainedAsExpected(int numStartingItems, int threadsCount, int itemsPerThread, bool take) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, numStartingItems)); int successes = 0; using (var b = new Barrier(threadsCount)) { WaitAllOrAnyFailed(Enumerable.Range(0, threadsCount).Select(threadNum => ThreadFactory.StartNew(() => { b.SignalAndWait(); for (int j = 0; j < itemsPerThread; j++) { int data; if (take ? c.TryTake(out data) : TryPeek(c, out data)) { Interlocked.Increment(ref successes); Assert.NotEqual(0, data); // shouldn't be default(T) } } })).ToArray()); } Assert.Equal( take ? numStartingItems : threadsCount * itemsPerThread, successes); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(1000)] public void ToArray_AddAllItemsThenEnumerate_ItemsAndCountMatch(int count) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IProducerConsumerCollection<int> oracle = CreateOracle(); for (int i = 0; i < count; i++) { Assert.Equal(oracle.TryAdd(i + count), c.TryAdd(i + count)); } Assert.Equal(oracle.ToArray(), c.ToArray()); if (count > 0) { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); Assert.Equal(oracle.ToArray(), c.ToArray()); } } [Theory] [InlineData(1, 10)] [InlineData(2, 10)] [InlineData(10, 10)] [InlineData(100, 10)] public void ToArray_AddAndTakeItemsIntermixedWithEnumeration_ItemsAndCountMatch(int initialCount, int iters) { IEnumerable<int> initialItems = Enumerable.Range(1, initialCount); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems); IProducerConsumerCollection<int> oracle = CreateOracle(initialItems); for (int i = 0; i < iters; i++) { Assert.Equal<int>(oracle, c); Assert.Equal(oracle.TryAdd(initialCount + i), c.TryAdd(initialCount + i)); Assert.Equal<int>(oracle, c); int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); Assert.Equal<int>(oracle, c); } } [Fact] public void AddFromMultipleThreads_ItemsRemainAfterThreadsGoAway() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); for (int i = 0; i < 1000; i += 100) { // Create a thread that adds items to the collection ThreadFactory.StartNew(() => { for (int j = i; j < i + 100; j++) { Assert.True(c.TryAdd(j)); } }).GetAwaiter().GetResult(); // Allow threads to be collected GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } AssertSetsEqual(new HashSet<int>(Enumerable.Range(0, 1000)), new HashSet<int>(c)); } [Fact] public void AddManyItems_ThenTakeOnSameThread_ItemsOutputInExpectedOrder() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 100000)); IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(0, 100000)); for (int i = 99999; i >= 0; --i) { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); } } [Fact] public void TryPeek_SucceedsOnEmptyCollectionThatWasOnceNonEmpty() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); int item; for (int i = 0; i < 2; i++) { Assert.False(TryPeek(c, out item)); Assert.Equal(0, item); } Assert.True(c.TryAdd(42)); for (int i = 0; i < 2; i++) { Assert.True(TryPeek(c, out item)); Assert.Equal(42, item); } Assert.True(c.TryTake(out item)); Assert.Equal(42, item); Assert.False(TryPeek(c, out item)); Assert.Equal(0, item); Assert.False(c.TryTake(out item)); Assert.Equal(0, item); } [Fact] public void AddTakeWithAtLeastOneElementInCollection_IsEmpty_AlwaysFalse() { int items = 1000; IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.True(c.TryAdd(0)); // make sure it's never empty var cts = new CancellationTokenSource(); // Consumer repeatedly calls IsEmpty until it's told to stop Task consumer = Task.Run(() => { while (!cts.IsCancellationRequested) Assert.False(IsEmpty(c)); }); // Producer adds/takes a bunch of items, then tells the consumer to stop Task producer = Task.Run(() => { int ignored; for (int i = 1; i <= items; i++) { Assert.True(c.TryAdd(i)); Assert.True(c.TryTake(out ignored)); } cts.Cancel(); }); Task.WaitAll(producer, consumer); } [Fact] public void CopyTo_Empty_NothingCopied() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); c.CopyTo(new int[0], 0); c.CopyTo(new int[10], 10); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void CopyTo_SzArray_ZeroIndex_ExpectedElementsCopied(int size) { IEnumerable<int> initialItems = Enumerable.Range(1, size); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems); int[] actual = new int[size]; c.CopyTo(actual, 0); IProducerConsumerCollection<int> oracle = CreateOracle(initialItems); int[] expected = new int[size]; oracle.CopyTo(expected, 0); Assert.Equal(expected, actual); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void CopyTo_SzArray_NonZeroIndex_ExpectedElementsCopied(int size) { IEnumerable<int> initialItems = Enumerable.Range(1, size); IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems); int[] actual = new int[size + 2]; c.CopyTo(actual, 1); IProducerConsumerCollection<int> oracle = CreateOracle(initialItems); int[] expected = new int[size + 2]; oracle.CopyTo(expected, 1); Assert.Equal(expected, actual); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public void CopyTo_ArrayZeroLowerBound_ZeroIndex_ExpectedElementsCopied(int size) { IEnumerable<int> initialItems = Enumerable.Range(1, size); ICollection c = CreateProducerConsumerCollection(initialItems); Array actual = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 }); c.CopyTo(actual, 0); ICollection oracle = CreateOracle(initialItems); Array expected = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 }); oracle.CopyTo(expected, 0); Assert.Equal(expected.Cast<int>(), actual.Cast<int>()); } [Fact] public void CopyTo_ArrayNonZeroLowerBound_ExpectedElementsCopied() { if (!PlatformDetection.IsNonZeroLowerBoundArraySupported) return; int[] initialItems = Enumerable.Range(1, 10).ToArray(); const int LowerBound = 1; ICollection c = CreateProducerConsumerCollection(initialItems); Array actual = Array.CreateInstance(typeof(int), new int[] { initialItems.Length }, new int[] { LowerBound }); c.CopyTo(actual, LowerBound); ICollection oracle = CreateOracle(initialItems); int[] expected = new int[initialItems.Length]; oracle.CopyTo(expected, 0); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual.GetValue(i + LowerBound)); } } [Fact] public void CopyTo_InvalidArgs_Throws() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 10)); int[] dest = new int[10]; AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1)); AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length)); AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length - 2)); AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new int[7, 7], 0)); } [Fact] public void ICollectionCopyTo_InvalidArgs_Throws() { ICollection c = CreateProducerConsumerCollection(Enumerable.Range(0, 10)); Array dest = new int[10]; AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1)); AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length)); AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length - 2)); } [Theory] [InlineData(100, 1, 10)] [InlineData(4, 100000, 10)] public void BlockingCollection_WrappingCollection_ExpectedElementsTransferred(int numThreadsPerConsumerProducer, int numItemsPerThread, int producerSpin) { var bc = new BlockingCollection<int>(CreateProducerConsumerCollection()); long dummy = 0; Task[] producers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() => { for (int i = 1; i <= numItemsPerThread; i++) { for (int j = 0; j < producerSpin; j++) dummy *= j; // spin a little bc.Add(i); } })).ToArray(); Task[] consumers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() => { for (int i = 0; i < numItemsPerThread; i++) { const int TimeoutMs = 100000; int item; Assert.True(bc.TryTake(out item, TimeoutMs), $"Couldn't get {i}th item after {TimeoutMs}ms"); Assert.NotEqual(0, item); } })).ToArray(); WaitAllOrAnyFailed(producers); WaitAllOrAnyFailed(consumers); } [Fact] public void GetEnumerator_NonGeneric() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IEnumerable e = c; Assert.False(e.GetEnumerator().MoveNext()); Assert.True(c.TryAdd(42)); Assert.True(c.TryAdd(84)); var hs = new HashSet<int>(e.Cast<int>()); Assert.Equal(2, hs.Count); Assert.Contains(42, hs); Assert.Contains(84, hs); } [Fact] public void GetEnumerator_EnumerationsAreSnapshots() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Empty(c); using (IEnumerator<int> e1 = c.GetEnumerator()) { Assert.True(c.TryAdd(1)); using (IEnumerator<int> e2 = c.GetEnumerator()) { Assert.True(c.TryAdd(2)); using (IEnumerator<int> e3 = c.GetEnumerator()) { int item; Assert.True(c.TryTake(out item)); using (IEnumerator<int> e4 = c.GetEnumerator()) { Assert.False(e1.MoveNext()); Assert.True(e2.MoveNext()); Assert.False(e2.MoveNext()); Assert.True(e3.MoveNext()); Assert.True(e3.MoveNext()); Assert.False(e3.MoveNext()); Assert.True(e4.MoveNext()); Assert.False(e4.MoveNext()); } } } } } [Theory] [InlineData(0, true)] [InlineData(1, true)] [InlineData(1, false)] [InlineData(10, true)] [InlineData(100, true)] [InlineData(100, false)] public async Task GetEnumerator_Generic_ExpectedElementsYielded(int numItems, bool consumeFromSameThread) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); using (var e = c.GetEnumerator()) { Assert.False(e.MoveNext()); } // Add, and validate enumeration after each item added for (int i = 1; i <= numItems; i++) { Assert.True(c.TryAdd(i)); Assert.Equal(i, c.Count); Assert.Equal(i, c.Distinct().Count()); } // Take, and validate enumerate after each item removed. Action consume = () => { for (int i = 1; i <= numItems; i++) { int item; Assert.True(c.TryTake(out item)); Assert.Equal(numItems - i, c.Count); Assert.Equal(numItems - i, c.Distinct().Count()); } }; if (consumeFromSameThread) { consume(); } else { await ThreadFactory.StartNew(consume); } } [Fact] public void TryAdd_TryTake_ToArray() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.True(c.TryAdd(42)); Assert.Equal(new[] { 42 }, c.ToArray()); Assert.True(c.TryAdd(84)); Assert.Equal(new[] { 42, 84 }, c.ToArray().OrderBy(i => i)); int item; Assert.True(c.TryTake(out item)); int remainingItem = item == 42 ? 84 : 42; Assert.Equal(new[] { remainingItem }, c.ToArray()); Assert.True(c.TryTake(out item)); Assert.Equal(remainingItem, item); Assert.Empty(c.ToArray()); } [Fact] public void ICollection_IsSynchronized_SyncRoot() { ICollection c = CreateProducerConsumerCollection(); Assert.False(c.IsSynchronized); Assert.Throws<NotSupportedException>(() => c.SyncRoot); } [Fact] public void ToArray_ParallelInvocations_Succeed() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Empty(c.ToArray()); const int NumItems = 10000; Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i))); Assert.Equal(NumItems, c.Count); Parallel.For(0, 10, i => { var hs = new HashSet<int>(c.ToArray()); Assert.Equal(NumItems, hs.Count); }); } [Fact] public void ToArray_AddTakeSameThread_ExpectedResultsAfterAddsAndTakes() { const int Items = 20; IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); IProducerConsumerCollection<int> oracle = CreateOracle(); for (int i = 0; i < Items; i++) { Assert.True(c.TryAdd(i)); Assert.True(oracle.TryAdd(i)); Assert.Equal(oracle.ToArray(), c.ToArray()); } for (int i = Items - 1; i >= 0; i--) { int expected, actual; Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual)); Assert.Equal(expected, actual); Assert.Equal(oracle.ToArray(), c.ToArray()); } } [Fact] public void GetEnumerator_ParallelInvocations_Succeed() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Assert.Empty(c.ToArray()); const int NumItems = 10000; Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i))); Assert.Equal(NumItems, c.Count); Parallel.For(0, 10, i => { var hs = new HashSet<int>(c); Assert.Equal(NumItems, hs.Count); }); } [Theory] [InlineData(1, ConcurrencyTestSeconds / 2)] [InlineData(4, ConcurrencyTestSeconds / 2)] public void ManyConcurrentAddsTakes_EnsureTrackedCountsMatchResultingCollection(int threadsPerProc, double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); DateTime end = default(DateTime); using (var b = new Barrier(Environment.ProcessorCount * threadsPerProc, _ => end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds))) { Task<int>[] tasks = Enumerable.Range(0, b.ParticipantCount).Select(_ => ThreadFactory.StartNew(() => { b.SignalAndWait(); int count = 0; var rand = new Random(); while (DateTime.UtcNow < end) { if (rand.NextDouble() < .5) { Assert.True(c.TryAdd(rand.Next())); count++; } else { int item; if (c.TryTake(out item)) count--; } } return count; })).ToArray(); Task.WaitAll(tasks); Assert.Equal(tasks.Sum(t => t.Result), c.Count); } } [Fact] [OuterLoop] public void ManyConcurrentAddsTakes_CollectionRemainsConsistent() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); const int operations = 30000; Action addAndRemove = () => { for (int i = 1; i < operations; i++) { int addCount = new Random(12354).Next(1, 100); int item; for (int j = 0; j < addCount; j++) Assert.True(c.TryAdd(i)); for (int j = 0; j < addCount; j++) Assert.True(c.TryTake(out item)); } }; const int numberOfThreads = 3; var tasks = new Task[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) tasks[i] = ThreadFactory.StartNew(addAndRemove); // Wait for them all to finish WaitAllOrAnyFailed(tasks); Assert.Empty(c); } [Theory] [InlineData(ConcurrencyTestSeconds)] public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsTaking(double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task<long> addsTakes = ThreadFactory.StartNew(() => { long total = 0; while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(i)); total++; } int item; if (TryPeek(c, out item)) { Assert.InRange(item, 1, MaxCount); } for (int i = 1; i <= MaxCount; i++) { if (c.TryTake(out item)) { total--; Assert.InRange(item, 1, MaxCount); } } } return total; }); Task<long> takesFromOtherThread = ThreadFactory.StartNew(() => { long total = 0; int item; while (DateTime.UtcNow < end) { if (c.TryTake(out item)) { total++; Assert.InRange(item, 1, MaxCount); } } return total; }); WaitAllOrAnyFailed(addsTakes, takesFromOtherThread); long remaining = addsTakes.Result - takesFromOtherThread.Result; Assert.InRange(remaining, 0, long.MaxValue); Assert.Equal(remaining, c.Count); } [Theory] [InlineData(ConcurrencyTestSeconds)] public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsPeeking(double seconds) { IProducerConsumerCollection<LargeStruct> c = CreateProducerConsumerCollection<LargeStruct>(); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task<long> addsTakes = ThreadFactory.StartNew(() => { long total = 0; while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(new LargeStruct(i))); total++; } LargeStruct item; Assert.True(TryPeek(c, out item)); Assert.InRange(item.Value, 1, MaxCount); for (int i = 1; i <= MaxCount; i++) { if (c.TryTake(out item)) { total--; Assert.InRange(item.Value, 1, MaxCount); } } } return total; }); Task peeksFromOtherThread = ThreadFactory.StartNew(() => { LargeStruct item; while (DateTime.UtcNow < end) { if (TryPeek(c, out item)) { Assert.InRange(item.Value, 1, MaxCount); } } }); WaitAllOrAnyFailed(addsTakes, peeksFromOtherThread); Assert.Equal(0, addsTakes.Result); Assert.Equal(0, c.Count); } [Theory] [InlineData(ConcurrencyTestSeconds)] public void ManyConcurrentAddsTakes_ForceContentionWithToArray(double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task addsTakes = ThreadFactory.StartNew(() => { while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(i)); } for (int i = 1; i <= MaxCount; i++) { int item; Assert.True(c.TryTake(out item)); Assert.InRange(item, 1, MaxCount); } } }); while (DateTime.UtcNow < end) { int[] arr = c.ToArray(); Assert.InRange(arr.Length, 0, MaxCount); Assert.DoesNotContain(0, arr); // make sure we didn't get default(T) } addsTakes.GetAwaiter().GetResult(); Assert.Equal(0, c.Count); } [Theory] [InlineData(0, ConcurrencyTestSeconds / 2)] [InlineData(1, ConcurrencyTestSeconds / 2)] public void ManyConcurrentAddsTakes_ForceContentionWithGetEnumerator(int initialCount, double seconds) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, initialCount)); const int MaxCount = 4; DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds); Task addsTakes = ThreadFactory.StartNew(() => { while (DateTime.UtcNow < end) { for (int i = 1; i <= MaxCount; i++) { Assert.True(c.TryAdd(i)); } for (int i = 1; i <= MaxCount; i++) { int item; Assert.True(c.TryTake(out item)); Assert.InRange(item, 1, MaxCount); } } }); while (DateTime.UtcNow < end) { int[] arr = c.Select(i => i).ToArray(); Assert.InRange(arr.Length, initialCount, MaxCount + initialCount); Assert.DoesNotContain(0, arr); // make sure we didn't get default(T) } addsTakes.GetAwaiter().GetResult(); Assert.Equal(initialCount, c.Count); } [Theory] [InlineData(0)] [InlineData(10)] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributes_Success(int count) { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(count); DebuggerAttributes.ValidateDebuggerDisplayReferences(c); DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(c); PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden); Array items = itemProperty.GetValue(info.Instance) as Array; Assert.Equal(c, items.Cast<int>()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerTypeProxy_Ctor_NullArgument_Throws() { IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(); Type proxyType = DebuggerAttributes.GetProxyType(c); var tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, new object[] { null })); Assert.IsType<ArgumentNullException>(tie.InnerException); } protected static void AssertSetsEqual<T>(HashSet<T> expected, HashSet<T> actual) { Assert.Equal(expected.Count, actual.Count); Assert.Subset(expected, actual); Assert.Subset(actual, expected); } protected static void WaitAllOrAnyFailed(params Task[] tasks) { if (tasks.Length == 0) { return; } int remaining = tasks.Length; var mres = new ManualResetEventSlim(); foreach (Task task in tasks) { task.ContinueWith(t => { if (Interlocked.Decrement(ref remaining) == 0 || t.IsFaulted) { mres.Set(); } }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } mres.Wait(); // Either all tasks are completed or at least one failed foreach (Task t in tasks) { if (t.IsFaulted) { t.GetAwaiter().GetResult(); // propagate for the first one that failed } } } private struct LargeStruct // used to help validate that values aren't torn while being read { private readonly long _a, _b, _c, _d, _e, _f, _g, _h; public LargeStruct(long value) { _a = _b = _c = _d = _e = _f = _g = _h = value; } public long Value { get { if (_a != _b || _a != _c || _a != _d || _a != _e || _a != _f || _a != _g || _a != _h) { throw new Exception($"Inconsistent {nameof(LargeStruct)}: {_a} {_b} {_c} {_d} {_e} {_f} {_g} {_h}"); } return _a; } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.ApiApps; using Microsoft.Azure.Management.ApiApps.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiApps { /// <summary> /// Operations for generating deployment templates /// </summary> internal partial class TemplateOperations : IServiceOperations<ApiAppManagementClient>, ITemplateOperations { /// <summary> /// Initializes a new instance of the TemplateOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal TemplateOperations(ApiAppManagementClient client) { this._client = client; } private ApiAppManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiApps.ApiAppManagementClient. /// </summary> public ApiAppManagementClient Client { get { return this._client; } } /// <summary> /// Get metadata for deploying a package to the given resource group /// </summary> /// <param name='parameters'> /// Required. Parameters for operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<GetDeploymentTemplateMetadataResponse> GetMetadataAsync(GetDeploymentMetadataRequest parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "GetMetadataAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.AppService/deploymenttemplates/"; if (parameters.MicroserviceId != null) { url = url + Uri.EscapeDataString(parameters.MicroserviceId); } url = url + "/listmetadata"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-03-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GetDeploymentTemplateMetadataResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GetDeploymentTemplateMetadataResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DeploymentTemplateMetadata metadataInstance = new DeploymentTemplateMetadata(); result.Metadata = metadataInstance; JToken valueValue = responseDoc["value"]; if (valueValue != null && valueValue.Type != JTokenType.Null) { JToken microserviceIdValue = valueValue["microserviceId"]; if (microserviceIdValue != null && microserviceIdValue.Type != JTokenType.Null) { string microserviceIdInstance = ((string)microserviceIdValue); metadataInstance.MicroserviceId = microserviceIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); metadataInstance.DisplayName = displayNameInstance; } JToken appSettingsArray = valueValue["appSettings"]; if (appSettingsArray != null && appSettingsArray.Type != JTokenType.Null) { foreach (JToken appSettingsValue in ((JArray)appSettingsArray)) { ParameterMetadata parameterMetadataInstance = new ParameterMetadata(); metadataInstance.Parameters.Add(parameterMetadataInstance); JToken nameValue = appSettingsValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); parameterMetadataInstance.Name = nameInstance; } JToken typeValue = appSettingsValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); parameterMetadataInstance.Type = typeInstance; } JToken displayNameValue2 = appSettingsValue["displayName"]; if (displayNameValue2 != null && displayNameValue2.Type != JTokenType.Null) { string displayNameInstance2 = ((string)displayNameValue2); parameterMetadataInstance.DisplayName = displayNameInstance2; } JToken descriptionValue = appSettingsValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); parameterMetadataInstance.Description = descriptionInstance; } JToken tooltipValue = appSettingsValue["tooltip"]; if (tooltipValue != null && tooltipValue.Type != JTokenType.Null) { string tooltipInstance = ((string)tooltipValue); parameterMetadataInstance.Tooltip = tooltipInstance; } JToken uiHintValue = appSettingsValue["uiHint"]; if (uiHintValue != null && uiHintValue.Type != JTokenType.Null) { string uiHintInstance = ((string)uiHintValue); parameterMetadataInstance.UIHint = uiHintInstance; } JToken defaultValueValue = appSettingsValue["defaultValue"]; if (defaultValueValue != null && defaultValueValue.Type != JTokenType.Null) { string defaultValueInstance = ((string)defaultValueValue); parameterMetadataInstance.DefaultValue = defaultValueInstance; } JToken constraintsValue = appSettingsValue["constraints"]; if (constraintsValue != null && constraintsValue.Type != JTokenType.Null) { ParameterConstraints constraintsInstance = new ParameterConstraints(); parameterMetadataInstance.Constraints = constraintsInstance; JToken requiredValue = constraintsValue["required"]; if (requiredValue != null && requiredValue.Type != JTokenType.Null) { bool requiredInstance = ((bool)requiredValue); constraintsInstance.Required = requiredInstance; } JToken hiddenValue = constraintsValue["hidden"]; if (hiddenValue != null && hiddenValue.Type != JTokenType.Null) { bool hiddenInstance = ((bool)hiddenValue); constraintsInstance.Hidden = hiddenInstance; } JToken allowedValuesArray = constraintsValue["allowedValues"]; if (allowedValuesArray != null && allowedValuesArray.Type != JTokenType.Null) { foreach (JToken allowedValuesValue in ((JArray)allowedValuesArray)) { constraintsInstance.AllowedValues.Add(((string)allowedValuesValue)); } } JToken rangeValue = constraintsValue["range"]; if (rangeValue != null && rangeValue.Type != JTokenType.Null) { RangeConstraint rangeInstance = new RangeConstraint(); constraintsInstance.Range = rangeInstance; JToken lowerBoundValue = rangeValue["lowerBound"]; if (lowerBoundValue != null && lowerBoundValue.Type != JTokenType.Null) { int lowerBoundInstance = ((int)lowerBoundValue); rangeInstance.LowerBound = lowerBoundInstance; } JToken upperBoundValue = rangeValue["upperBound"]; if (upperBoundValue != null && upperBoundValue.Type != JTokenType.Null) { int upperBoundInstance = ((int)upperBoundValue); rangeInstance.UpperBound = upperBoundInstance; } } JToken lengthValue = constraintsValue["length"]; if (lengthValue != null && lengthValue.Type != JTokenType.Null) { LengthConstraint lengthInstance = new LengthConstraint(); constraintsInstance.Length = lengthInstance; JToken minValue = lengthValue["min"]; if (minValue != null && minValue.Type != JTokenType.Null) { int minInstance = ((int)minValue); lengthInstance.Min = minInstance; } JToken maxValue = lengthValue["max"]; if (maxValue != null && maxValue.Type != JTokenType.Null) { int maxInstance = ((int)maxValue); lengthInstance.Max = maxInstance; } } JToken containsCharactersValue = constraintsValue["containsCharacters"]; if (containsCharactersValue != null && containsCharactersValue.Type != JTokenType.Null) { string containsCharactersInstance = ((string)containsCharactersValue); constraintsInstance.ContainsCharacters = containsCharactersInstance; } JToken notContainsCharactersValue = constraintsValue["notContainsCharacters"]; if (notContainsCharactersValue != null && notContainsCharactersValue.Type != JTokenType.Null) { string notContainsCharactersInstance = ((string)notContainsCharactersValue); constraintsInstance.NotContainsCharacters = notContainsCharactersInstance; } JToken hasDigitValue = constraintsValue["hasDigit"]; if (hasDigitValue != null && hasDigitValue.Type != JTokenType.Null) { bool hasDigitInstance = ((bool)hasDigitValue); constraintsInstance.HasDigit = hasDigitInstance; } JToken hasLetterValue = constraintsValue["hasLetter"]; if (hasLetterValue != null && hasLetterValue.Type != JTokenType.Null) { bool hasLetterInstance = ((bool)hasLetterValue); constraintsInstance.HasLetter = hasLetterInstance; } JToken hasPunctuationValue = constraintsValue["hasPunctuation"]; if (hasPunctuationValue != null && hasPunctuationValue.Type != JTokenType.Null) { bool hasPunctuationInstance = ((bool)hasPunctuationValue); constraintsInstance.HasPunctuation = hasPunctuationInstance; } JToken numericValue = constraintsValue["numeric"]; if (numericValue != null && numericValue.Type != JTokenType.Null) { bool numericInstance = ((bool)numericValue); constraintsInstance.Numeric = numericInstance; } } } } JToken dependsOnArray = valueValue["dependsOn"]; if (dependsOnArray != null && dependsOnArray.Type != JTokenType.Null) { foreach (JToken dependsOnValue in ((JArray)dependsOnArray)) { MicroserviceMetadata microserviceMetadataInstance = new MicroserviceMetadata(); metadataInstance.DependsOn.Add(microserviceMetadataInstance); JToken microserviceIdValue2 = dependsOnValue["microserviceId"]; if (microserviceIdValue2 != null && microserviceIdValue2.Type != JTokenType.Null) { string microserviceIdInstance2 = ((string)microserviceIdValue2); microserviceMetadataInstance.MicroserviceId = microserviceIdInstance2; } JToken displayNameValue3 = dependsOnValue["displayName"]; if (displayNameValue3 != null && displayNameValue3.Type != JTokenType.Null) { string displayNameInstance3 = ((string)displayNameValue3); microserviceMetadataInstance.DisplayName = displayNameInstance3; } JToken appSettingsArray2 = dependsOnValue["appSettings"]; if (appSettingsArray2 != null && appSettingsArray2.Type != JTokenType.Null) { foreach (JToken appSettingsValue2 in ((JArray)appSettingsArray2)) { ParameterMetadata parameterMetadataInstance2 = new ParameterMetadata(); microserviceMetadataInstance.Parameters.Add(parameterMetadataInstance2); JToken nameValue2 = appSettingsValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); parameterMetadataInstance2.Name = nameInstance2; } JToken typeValue2 = appSettingsValue2["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); parameterMetadataInstance2.Type = typeInstance2; } JToken displayNameValue4 = appSettingsValue2["displayName"]; if (displayNameValue4 != null && displayNameValue4.Type != JTokenType.Null) { string displayNameInstance4 = ((string)displayNameValue4); parameterMetadataInstance2.DisplayName = displayNameInstance4; } JToken descriptionValue2 = appSettingsValue2["description"]; if (descriptionValue2 != null && descriptionValue2.Type != JTokenType.Null) { string descriptionInstance2 = ((string)descriptionValue2); parameterMetadataInstance2.Description = descriptionInstance2; } JToken tooltipValue2 = appSettingsValue2["tooltip"]; if (tooltipValue2 != null && tooltipValue2.Type != JTokenType.Null) { string tooltipInstance2 = ((string)tooltipValue2); parameterMetadataInstance2.Tooltip = tooltipInstance2; } JToken uiHintValue2 = appSettingsValue2["uiHint"]; if (uiHintValue2 != null && uiHintValue2.Type != JTokenType.Null) { string uiHintInstance2 = ((string)uiHintValue2); parameterMetadataInstance2.UIHint = uiHintInstance2; } JToken defaultValueValue2 = appSettingsValue2["defaultValue"]; if (defaultValueValue2 != null && defaultValueValue2.Type != JTokenType.Null) { string defaultValueInstance2 = ((string)defaultValueValue2); parameterMetadataInstance2.DefaultValue = defaultValueInstance2; } JToken constraintsValue2 = appSettingsValue2["constraints"]; if (constraintsValue2 != null && constraintsValue2.Type != JTokenType.Null) { ParameterConstraints constraintsInstance2 = new ParameterConstraints(); parameterMetadataInstance2.Constraints = constraintsInstance2; JToken requiredValue2 = constraintsValue2["required"]; if (requiredValue2 != null && requiredValue2.Type != JTokenType.Null) { bool requiredInstance2 = ((bool)requiredValue2); constraintsInstance2.Required = requiredInstance2; } JToken hiddenValue2 = constraintsValue2["hidden"]; if (hiddenValue2 != null && hiddenValue2.Type != JTokenType.Null) { bool hiddenInstance2 = ((bool)hiddenValue2); constraintsInstance2.Hidden = hiddenInstance2; } JToken allowedValuesArray2 = constraintsValue2["allowedValues"]; if (allowedValuesArray2 != null && allowedValuesArray2.Type != JTokenType.Null) { foreach (JToken allowedValuesValue2 in ((JArray)allowedValuesArray2)) { constraintsInstance2.AllowedValues.Add(((string)allowedValuesValue2)); } } JToken rangeValue2 = constraintsValue2["range"]; if (rangeValue2 != null && rangeValue2.Type != JTokenType.Null) { RangeConstraint rangeInstance2 = new RangeConstraint(); constraintsInstance2.Range = rangeInstance2; JToken lowerBoundValue2 = rangeValue2["lowerBound"]; if (lowerBoundValue2 != null && lowerBoundValue2.Type != JTokenType.Null) { int lowerBoundInstance2 = ((int)lowerBoundValue2); rangeInstance2.LowerBound = lowerBoundInstance2; } JToken upperBoundValue2 = rangeValue2["upperBound"]; if (upperBoundValue2 != null && upperBoundValue2.Type != JTokenType.Null) { int upperBoundInstance2 = ((int)upperBoundValue2); rangeInstance2.UpperBound = upperBoundInstance2; } } JToken lengthValue2 = constraintsValue2["length"]; if (lengthValue2 != null && lengthValue2.Type != JTokenType.Null) { LengthConstraint lengthInstance2 = new LengthConstraint(); constraintsInstance2.Length = lengthInstance2; JToken minValue2 = lengthValue2["min"]; if (minValue2 != null && minValue2.Type != JTokenType.Null) { int minInstance2 = ((int)minValue2); lengthInstance2.Min = minInstance2; } JToken maxValue2 = lengthValue2["max"]; if (maxValue2 != null && maxValue2.Type != JTokenType.Null) { int maxInstance2 = ((int)maxValue2); lengthInstance2.Max = maxInstance2; } } JToken containsCharactersValue2 = constraintsValue2["containsCharacters"]; if (containsCharactersValue2 != null && containsCharactersValue2.Type != JTokenType.Null) { string containsCharactersInstance2 = ((string)containsCharactersValue2); constraintsInstance2.ContainsCharacters = containsCharactersInstance2; } JToken notContainsCharactersValue2 = constraintsValue2["notContainsCharacters"]; if (notContainsCharactersValue2 != null && notContainsCharactersValue2.Type != JTokenType.Null) { string notContainsCharactersInstance2 = ((string)notContainsCharactersValue2); constraintsInstance2.NotContainsCharacters = notContainsCharactersInstance2; } JToken hasDigitValue2 = constraintsValue2["hasDigit"]; if (hasDigitValue2 != null && hasDigitValue2.Type != JTokenType.Null) { bool hasDigitInstance2 = ((bool)hasDigitValue2); constraintsInstance2.HasDigit = hasDigitInstance2; } JToken hasLetterValue2 = constraintsValue2["hasLetter"]; if (hasLetterValue2 != null && hasLetterValue2.Type != JTokenType.Null) { bool hasLetterInstance2 = ((bool)hasLetterValue2); constraintsInstance2.HasLetter = hasLetterInstance2; } JToken hasPunctuationValue2 = constraintsValue2["hasPunctuation"]; if (hasPunctuationValue2 != null && hasPunctuationValue2.Type != JTokenType.Null) { bool hasPunctuationInstance2 = ((bool)hasPunctuationValue2); constraintsInstance2.HasPunctuation = hasPunctuationInstance2; } JToken numericValue2 = constraintsValue2["numeric"]; if (numericValue2 != null && numericValue2.Type != JTokenType.Null) { bool numericInstance2 = ((bool)numericValue2); constraintsInstance2.Numeric = numericInstance2; } } } } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.ArmProcessor { using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; public static class SymDef { public class SymbolToAddressMap : Dictionary< string, uint > { } public class AddressToSymbolMap : Dictionary< uint, string > { class AddressComparer : IComparer< KeyValuePair< uint, string > > { public int Compare( KeyValuePair< uint, string > x , KeyValuePair< uint, string > y ) { return x.Key.CompareTo( y.Key ); } } // // State // AddressComparer m_comparer; KeyValuePair< uint, string >[] m_sorted; //--/// public bool FindClosestAddress( uint address , out uint context ) { if(m_comparer == null) { m_comparer = new AddressComparer(); } if(m_sorted == null) { m_sorted = new KeyValuePair<uint,string>[this.Count]; int pos = 0; foreach(KeyValuePair< uint, string> kvp in this) { m_sorted[pos++] = kvp; } Array.Sort( m_sorted, m_comparer ); } if(m_sorted.Length > 0) { int i = Array.BinarySearch( m_sorted, new KeyValuePair< uint, string >( address, null ), m_comparer ); if(i >= 0) { context = address; return true; } i = ~i - 1; if(i >= 0 && i < m_sorted.Length) { context = m_sorted[i].Key; return true; } } context = 0; return false; } } //--// public static void Parse( string file , SymDef.SymbolToAddressMap symdef , SymDef.AddressToSymbolMap symdef_Inverse ) { if(System.IO.File.Exists( file ) == false) { throw new System.IO.FileNotFoundException( String.Format( "Cannot find {0}", file ) ); } using(System.IO.StreamReader reader = new StreamReader( file )) { Regex reMatch1 = new Regex( "^0x([0-9a-fA-F]*) ([A-D]) (.*)" ); Regex reMatch2 = new Regex( "^ 0x([0-9a-fA-F]*): ([0-9a-fA-F]*) " ); Regex reMatch3 = new Regex( "^ ([^ ]+)$" ); string lastName = null; string line; while((line = reader.ReadLine()) != null) { if(reMatch1.IsMatch( line )) { GroupCollection group = reMatch1.Match( line ).Groups; uint address = UInt32.Parse( group[1].Value, System.Globalization.NumberStyles.HexNumber ); string symbol = group[3].Value; symdef [symbol ] = address; symdef_Inverse[address] = symbol; } else if(reMatch2.IsMatch( line )) { GroupCollection group = reMatch2.Match( line ).Groups; if(lastName != null) { uint address = UInt32.Parse( group[1].Value, System.Globalization.NumberStyles.HexNumber ); symdef [lastName] = address; symdef_Inverse[address ] = lastName; lastName = null; } } else if(reMatch3.IsMatch( line )) { GroupCollection group = reMatch3.Match( line ).Groups; string name = group[1].Value; switch(name) { case ".text": case "$a": case "$d": case "$p": break; default: if(name.StartsWith( "i." )) { name = name.Substring( 2 ); } lastName = name; break; } } } } } //--// private static bool Unmangle_ClassName( string symbol , ref int index , StringBuilder name ) { if(symbol[index] == 'Q' && char.IsDigit( symbol, index+1 )) { int times = symbol[index+1] - '0'; index += 2; while(times-- > 0) { if(Unmangle_ClassName( symbol, ref index, name ) == false) return false; if(times > 0) { name.Append( "::" ); } } } else if(char.IsDigit( symbol, index )) { int len = 0; while(index < symbol.Length && char.IsDigit( symbol, index )) { len = len * 10 + symbol[index] - '0'; index++; } if(len == 0 || len + index > symbol.Length) return false; name.Append( symbol, index, len ); index += len; } return true; } private static bool Unmangle_Parameter( string symbol , ref int index , List<string> parameters ) { int len = parameters.Count; switch(symbol[index++]) { case 'i': parameters.Add( "int" ); return true; case 's': parameters.Add( "short" ); return true; case 'l': parameters.Add( "long" ); return true; case 'x': parameters.Add( "long long" ); return true; case 'c': parameters.Add( "char" ); return true; case 'b': parameters.Add( "bool" ); return true; case 'f': parameters.Add( "float" ); return true; case 'd': parameters.Add( "double" ); return true; case 'v': parameters.Add( "void" ); return true; case 'e': parameters.Add( "..." ); return true; //--// case 'N': // N<digit><pos> = Repeat parameter <pos> <digit> times. if(char.IsDigit( symbol, index )) { int num = symbol[index++] - '0'; if(char.IsDigit( symbol, index )) { int pos = symbol[index++] - '0' - 1; if(pos < len) { while(num-- > 0) { parameters.Add( parameters[pos] ); } return true; } } } break; case 'T': // T<pos> = Repeat parameter <pos> if(char.IsDigit( symbol, index )) { int pos = symbol[index++] - '0' - 1; if(pos < len) { parameters.Add( parameters[pos] ); return true; } } break; case 'P': // P = pointer if(Unmangle_Parameter( symbol, ref index, parameters )) { parameters[len] += "*"; return true; } break; case 'R': // R = reference if(Unmangle_Parameter( symbol, ref index, parameters )) { parameters[len] += "&"; return true; } break; case 'C': // C = const // // CP => <type> * const // PC => const <type> * // if(Unmangle_Parameter( symbol, ref index, parameters )) { parameters[len] = "const " + parameters[len]; return true; } break; case 'U': // U = unsigned if(Unmangle_Parameter( symbol, ref index, parameters )) { parameters[len] = "unsigned " + parameters[len]; return true; } break; case 'Q': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { StringBuilder sb = new StringBuilder(); index--; if(Unmangle_ClassName( symbol, ref index, sb )) { parameters.Add( sb.ToString() ); return true; } } break; } return false; } private static void Unmangle_SkipPrefix( string symbol , ref int index , ref string dst , string prefix , string substitute ) { if(index + prefix.Length <= symbol.Length) { if(symbol.Substring( index, prefix.Length ) == prefix) { index += prefix.Length; dst += substitute; } } } public static void Unmangle( string name , out string strClass , out string strFunction , out string strModifier ) { int index = 0; StringBuilder functionName = new StringBuilder(); StringBuilder className = new StringBuilder(); strClass = string.Empty; strFunction = string.Empty; strModifier = string.Empty; Unmangle_SkipPrefix( name, ref index, ref strModifier, "$Ven$AA$L$$", "veneer " ); Unmangle_SkipPrefix( name, ref index, ref strModifier, "i." , "inline " ); name = name.Substring( index ); index = 0; if(name.Contains( "::" )) { strClass = "C# function"; strFunction = name; return; } if(name.Contains( "Jitter#" )) { strClass = "Jitter"; strFunction = name.Substring( "Jitter#".Length ); return; } while(index < name.Length) { if(name[index] == '_' && index + 1 < name.Length && name[index+1] == '_') { int index2 = index + 2; className.Length = 0; if(Unmangle_ClassName( name, ref index2, className )) { //// bool fStatic = false; bool fConst = false; while(index2 < name.Length) { if(name[index2] == 'S') { index2++; //// fStatic = true; continue; } if(name[index2] == 'C') { index2++; fConst = true; continue; } break; } if(index2 < name.Length && name[index2++] == 'F') { List<string> parameters = new List<string>(); bool fOk = true; while(fOk && index2 < name.Length) { fOk = Unmangle_Parameter( name, ref index2, parameters ); } if(fOk) { if(className.Length > 0) { strClass = className.ToString(); } else { strClass = "C++ function"; } functionName.Append( "( " ); for(int i = 0; i < parameters.Count; i++) { if(i != 0) functionName.Append( ", " ); functionName.Append( parameters[i] ); } functionName.Append( " )" ); if(fConst ) functionName.Append( " const" ); //// if(fStatic) functionName.Append( " static" ); strFunction = functionName.ToString(); return; } } } } functionName.Append( name[index++] ); } strClass = "C function"; strFunction = functionName.ToString(); } } }
// <copyright file="EdgeDriverService.cs" company="Microsoft"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Globalization; using System.Text; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Edge { /// <summary> /// Exposes the service provided by the native MicrosoftWebDriver executable. /// </summary> public sealed class EdgeDriverService : DriverService { private const string MicrosoftWebDriverServiceFileName = "MicrosoftWebDriver.exe"; private static readonly Uri MicrosoftWebDriverDownloadUrl = new Uri("http://go.microsoft.com/fwlink/?LinkId=619687"); private string host; private string package; private bool useVerboseLogging; private bool? useSpecCompliantProtocol; /// <summary> /// Initializes a new instance of the <see cref="EdgeDriverService"/> class. /// </summary> /// <param name="executablePath">The full path to the EdgeDriver executable.</param> /// <param name="executableFileName">The file name of the EdgeDriver executable.</param> /// <param name="port">The port on which the EdgeDriver executable should listen.</param> private EdgeDriverService(string executablePath, string executableFileName, int port) : base(executablePath, port, executableFileName, MicrosoftWebDriverDownloadUrl) { } /// <summary> /// Gets or sets the value of the host adapter on which the Edge driver service should listen for connections. /// </summary> public string Host { get { return this.host; } set { this.host = value; } } /// <summary> /// Gets or sets the value of the package the Edge driver service will launch and automate. /// </summary> public string Package { get { return this.package; } set { this.package = value; } } /// <summary> /// Gets or sets a value indicating whether the service should use verbose logging. /// </summary> public bool UseVerboseLogging { get { return this.useVerboseLogging; } set { this.useVerboseLogging = value; } } /// <summary> /// Gets or sets a value indicating whether the <see cref="EdgeDriverService"/> instance /// should use the a protocol dialect compliant with the W3C WebDriver Specification. /// </summary> /// <remarks> /// Setting this property to a non-<see langword="null"/> value for driver /// executables matched to versions of Windows before the 2018 Fall Creators /// Update will result in a the driver executable shutting down without /// execution, and all commands will fail. Do not set this property unless /// you are certain your version of the MicrosoftWebDriver.exe supports the /// --w3c and --jwp command-line arguments. /// </remarks> public bool? UseSpecCompliantProtocol { get { return this.useSpecCompliantProtocol; } set { this.useSpecCompliantProtocol = value; } } /// <summary> /// Gets a value indicating whether the service has a shutdown API that can be called to terminate /// it gracefully before forcing a termination. /// </summary> protected override bool HasShutdown { get { if (this.useSpecCompliantProtocol.HasValue && this.useSpecCompliantProtocol.Value) { return false; } return base.HasShutdown; } } /// <summary> /// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate. /// </summary> protected override TimeSpan TerminationTimeout { // Use a very small timeout for terminating the Firefox driver, // because the executable does not have a clean shutdown command, // which means we have to kill the process. Using a short timeout // gets us to the termination point much faster. get { if (this.useSpecCompliantProtocol.HasValue && this.useSpecCompliantProtocol.Value) { return TimeSpan.FromMilliseconds(100); } return base.TerminationTimeout; } } /// <summary> /// Gets the command-line arguments for the driver service. /// </summary> protected override string CommandLineArguments { get { StringBuilder argsBuilder = new StringBuilder(base.CommandLineArguments); if (!string.IsNullOrEmpty(this.host)) { argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " --host={0}", this.host)); } if (!string.IsNullOrEmpty(this.package)) { argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " --package={0}", this.package)); } if (this.useVerboseLogging) { argsBuilder.Append(" --verbose"); } if (this.SuppressInitialDiagnosticInformation) { argsBuilder.Append(" --silent"); } if (this.useSpecCompliantProtocol.HasValue) { if (this.useSpecCompliantProtocol.Value) { argsBuilder.Append(" --w3c"); } else { argsBuilder.Append(" --jwp"); } } return argsBuilder.ToString(); } } /// <summary> /// Creates a default instance of the EdgeDriverService. /// </summary> /// <returns>A EdgeDriverService that implements default settings.</returns> public static EdgeDriverService CreateDefaultService() { string serviceDirectory = DriverService.FindDriverServiceExecutable(MicrosoftWebDriverServiceFileName, MicrosoftWebDriverDownloadUrl); EdgeDriverService service = CreateDefaultService(serviceDirectory); return service; } /// <summary> /// Creates a default instance of the EdgeDriverService using a specified path to the EdgeDriver executable. /// </summary> /// <param name="driverPath">The directory containing the EdgeDriver executable.</param> /// <returns>A EdgeDriverService using a random port.</returns> public static EdgeDriverService CreateDefaultService(string driverPath) { return CreateDefaultService(driverPath, MicrosoftWebDriverServiceFileName); } /// <summary> /// Creates a default instance of the EdgeDriverService using a specified path to the EdgeDriver executable with the given name. /// </summary> /// <param name="driverPath">The directory containing the EdgeDriver executable.</param> /// <param name="driverExecutableFileName">The name of the EdgeDriver executable file.</param> /// <returns>A EdgeDriverService using a random port.</returns> public static EdgeDriverService CreateDefaultService(string driverPath, string driverExecutableFileName) { return CreateDefaultService(driverPath, driverExecutableFileName, PortUtilities.FindFreePort()); } /// <summary> /// Creates a default instance of the EdgeDriverService using a specified path to the EdgeDriver executable with the given name and listening port. /// </summary> /// <param name="driverPath">The directory containing the EdgeDriver executable.</param> /// <param name="driverExecutableFileName">The name of the EdgeDriver executable file</param> /// <param name="port">The port number on which the driver will listen</param> /// <returns>A EdgeDriverService using the specified port.</returns> public static EdgeDriverService CreateDefaultService(string driverPath, string driverExecutableFileName, int port) { return new EdgeDriverService(driverPath, driverExecutableFileName, port); } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using DCalcCore.Algorithm; using DCalc.Algorithms; using DCalcCore.LoadBalancers; namespace DCalc.Communication { /// <summary> /// Xml based workspace. /// </summary> public class XmlStoredWorkSpace : IWorkSpace { #region Private Fields private String m_XmlFileName; private List<IServer> m_Servers; private IAlgorithmProvider m_Provider; private IAlgorithmCollection m_Algorithms; private Int32 m_QueueSize = 1024; private Int32 m_NumberOfThreads = 1; private Type m_LocalBalancer = typeof(FairLoadBalancer); private Type m_RemoteBalancer = typeof(FairLoadBalancer); #endregion #region Private Fields /// <summary> /// Checks for local server. /// </summary> /// <param name="servers">The servers.</param> /// <returns></returns> private List<IServer> CheckForLocalServer(List<IServer> servers) { List<IServer> result = new List<IServer>(); IServer localServer = null; foreach(IServer server in servers) { if (server is LocalServer) { if (localServer == null) { localServer = server; } } else result.Add(server); } /* Do we have the one local server? */ if (localServer == null) localServer = new LocalServer(false); result.Add(localServer); return result; } /// <summary> /// Get Type from name. /// </summary> /// <param name="balancerType">Type of the balancer.</param> /// <returns></returns> private Type TypeFromName(String balancerType) { Type typeOfFairLoadBalancer = typeof(FairLoadBalancer); Type typeOfRRLoadBalancer = typeof(RRLoadBalancer); Type typeOfPredictiveLoadBalancer = typeof(PredictiveLoadBalancer); if (balancerType.Equals(typeOfFairLoadBalancer.FullName)) return typeOfFairLoadBalancer; else if (balancerType.Equals(typeOfRRLoadBalancer.FullName)) return typeOfRRLoadBalancer; else if (balancerType.Equals(typeOfPredictiveLoadBalancer.FullName)) return typeOfPredictiveLoadBalancer; return null; } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="XmlStoredWorkSpace"/> class. /// </summary> /// <param name="xmlFileName">Name of the XML file.</param> public XmlStoredWorkSpace(String xmlFileName) { m_XmlFileName = xmlFileName; m_Servers = CheckForLocalServer(new List<IServer>()); } /// <summary> /// Initializes a new instance of the <see cref="XmlStoredWorkSpace"/> class. /// </summary> public XmlStoredWorkSpace() { m_XmlFileName = null; m_Servers = CheckForLocalServer(new List<IServer>()); } #endregion #region XmlStoredWorkSpace Public Properties /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value>The name of the file.</value> public String FileName { get { return m_XmlFileName; } set { m_XmlFileName = value; } } /// <summary> /// Gets or sets the algorithms. /// </summary> /// <value>The algorithms.</value> public IAlgorithmCollection Algorithms { get { return m_Algorithms; } set { m_Algorithms = value; } } #endregion #region IWorkSpace Members /// <summary> /// Gets all the registered servers. /// </summary> /// <value>The servers.</value> public IEnumerable<IServer> Servers { get { return m_Servers; } } /// <summary> /// Adds a new server. /// </summary> /// <param name="server">The server.</param> public void AddServer(IServer server) { if (server == null) throw new ArgumentNullException("server"); if (!m_Servers.Contains(server)) m_Servers.Add(server); } /// <summary> /// Removes a server. /// </summary> /// <param name="server">The server.</param> /// <returns></returns> public IServer RemoveServer(IServer server) { if (server == null) throw new ArgumentNullException("server"); m_Servers.Remove(server); return server; } /// <summary> /// Clears all the servers. /// </summary> public void ClearServers() { m_Servers.Clear(); } /// <summary> /// Gets the count of servers. /// </summary> /// <value>The count of servers.</value> public Int32 CountOfServers { get { return m_Servers.Count; } } /// <summary> /// Loads this instance. /// </summary> /// <returns></returns> public Boolean Load() { try { /* Try to load the XML document that contains the server list */ XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(m_XmlFileName); /* Get root node */ XmlElement root = xmlDoc.DocumentElement; if (!root.Name.Equals("configuration")) return false; /* Load setting */ try { Int32 qsize = Convert.ToInt32(root.Attributes["qsize"].Value); Int32 thc = Convert.ToInt32(root.Attributes["thc"].Value); Type lbt = TypeFromName(root.Attributes["lbid"].Value); Type rbt = TypeFromName(root.Attributes["rbid"].Value); if (qsize < 1 || thc < 0 || lbt == null || rbt == null) return false; m_QueueSize = qsize; m_NumberOfThreads = thc; m_LocalBalancer = lbt; m_RemoteBalancer = rbt; } catch { return false; } XmlNode xmlServerList; try { xmlServerList = root.GetElementsByTagName("servers")[0]; } catch { return false; } List<IServer> servers = new List<IServer>(); /* Circle in each node */ foreach (XmlNode xmlServerNode in xmlServerList.ChildNodes) { IServer server = null; if (xmlServerNode.Name.Equals("remote")) { String _name = xmlServerNode.Attributes["name"].Value; String _host = xmlServerNode.Attributes["host"].Value; String _key = xmlServerNode.Attributes["key"].Value; Int32 _port = Convert.ToInt32(xmlServerNode.Attributes["port"].Value); ConnectionType _ctype = ConnectionType.Http; try { _ctype = (ConnectionType)(Convert.ToInt32(xmlServerNode.Attributes["ctype"].Value)); } catch { } Boolean _enabled = (Convert.ToInt32(xmlServerNode.Attributes["enabled"].Value) != 0); server = new RemoteServer(_name, _host, _port, _key, _ctype, _enabled); } else if (xmlServerNode.Name.Equals("local")) { Boolean _enabled = (Convert.ToInt32(xmlServerNode.Attributes["enabled"].Value) != 0); server = new LocalServer(_enabled); } else return false; servers.Add(server); } /* Check if we have the local server and that it's only once opy of it */ m_Servers = CheckForLocalServer(servers); /* Load provider */ XmlNode xmlProvider; try { xmlProvider = root.GetElementsByTagName("provider")[0]; String _id = xmlProvider.Attributes["id"].Value; Dictionary<String, String> settings = new Dictionary<String, String>(); /* Circle in each node */ foreach (XmlNode xmlOptionNode in xmlProvider.ChildNodes) { if (xmlOptionNode.Name.Equals("option")) { String _key = xmlOptionNode.Attributes["key"].Value; String _value = xmlOptionNode.Attributes["value"].Value; if (!settings.ContainsKey(_key)) settings.Add(_key, _value); } } /* Find the algorithm */ foreach(IAlgorithmProvider provider in m_Algorithms.Providers) { if (provider.GetType().FullName.Equals(_id)) { provider.SetSettings(settings); m_Provider = provider; break; } } } catch { } } catch { return false; } return true; } /// <summary> /// Saves this instance. /// </summary> /// <returns></returns> public Boolean Save() { try { /* Create new XmlDocument */ XmlDocument xmlDoc = new XmlDocument(); /* Add root */ XmlElement root = xmlDoc.CreateElement("configuration"); xmlDoc.AppendChild(root); XmlAttribute _localBalancer = xmlDoc.CreateAttribute("lbid"); _localBalancer.Value = m_LocalBalancer.FullName; root.Attributes.Append(_localBalancer); XmlAttribute _remoteBalancer = xmlDoc.CreateAttribute("rbid"); _remoteBalancer.Value = m_RemoteBalancer.FullName; root.Attributes.Append(_remoteBalancer); XmlAttribute _queueSize = xmlDoc.CreateAttribute("qsize"); _queueSize.Value = m_QueueSize.ToString(); root.Attributes.Append(_queueSize); XmlAttribute _numberOfThreads = xmlDoc.CreateAttribute("thc"); _numberOfThreads.Value = m_NumberOfThreads.ToString(); root.Attributes.Append(_numberOfThreads); XmlElement serverListElement = xmlDoc.CreateElement("servers"); root.AppendChild(serverListElement); /* Append all servers form the list */ foreach (IServer server in m_Servers) { XmlElement srvElement = null; if (server is LocalServer) { srvElement = xmlDoc.CreateElement("local"); XmlAttribute _enabled = xmlDoc.CreateAttribute("enabled"); _enabled.Value = Convert.ToString(server.Enabled ? 1 : 0); srvElement.Attributes.Append(_enabled); } else if (server is RemoteServer) { RemoteServer rServer = (RemoteServer)server; srvElement = xmlDoc.CreateElement("remote"); XmlAttribute _enabled = xmlDoc.CreateAttribute("enabled"); _enabled.Value = Convert.ToString(server.Enabled ? 1 : 0); srvElement.Attributes.Append(_enabled); XmlAttribute _name = xmlDoc.CreateAttribute("name"); _name.Value = rServer.Name ?? String.Empty; srvElement.Attributes.Append(_name); XmlAttribute _host = xmlDoc.CreateAttribute("host"); _host.Value = rServer.Host ?? String.Empty; srvElement.Attributes.Append(_host); XmlAttribute _secKey = xmlDoc.CreateAttribute("key"); _secKey.Value = rServer.SecurityKey ?? String.Empty; srvElement.Attributes.Append(_secKey); XmlAttribute _port = xmlDoc.CreateAttribute("port"); _port.Value = Convert.ToString(rServer.Port); srvElement.Attributes.Append(_port); XmlAttribute _ctype = xmlDoc.CreateAttribute("ctype"); _ctype.Value = Convert.ToString((Int32)rServer.ConnectionType); srvElement.Attributes.Append(_ctype); } if (srvElement != null) serverListElement.AppendChild(srvElement); } /* Append configuration option and plugins */ if (m_Provider != null) { XmlElement providerElement = xmlDoc.CreateElement("provider"); /* Name/Assembly */ XmlAttribute _name = xmlDoc.CreateAttribute("id"); _name.Value = m_Provider.GetType().FullName; providerElement.Attributes.Append(_name); /* Options */ Dictionary<String, String> options = m_Provider.GetSettings(); foreach (String key in options.Keys) { XmlElement optionElement = xmlDoc.CreateElement("option"); XmlAttribute _optionName = xmlDoc.CreateAttribute("key"); _optionName.Value = key; optionElement.Attributes.Append(_optionName); XmlAttribute _optionValue = xmlDoc.CreateAttribute("value"); _optionValue.Value = options[key]; optionElement.Attributes.Append(_optionValue); providerElement.AppendChild(optionElement); } root.AppendChild(providerElement); } xmlDoc.Save(m_XmlFileName); } catch { return false; } return true; } /// <summary> /// Gets or sets the algorithm provider. /// </summary> /// <value>The provider.</value> public IAlgorithmProvider Provider { get { return m_Provider; } set { m_Provider = value; } } /// <summary> /// Gets or sets the local balancer. /// </summary> /// <value>The local balancer.</value> public Type LocalBalancer { get { return m_LocalBalancer; } set { if (value != typeof(FairLoadBalancer) && value != typeof(RRLoadBalancer) && value != typeof(PredictiveLoadBalancer)) throw new ArgumentException("value"); m_LocalBalancer = value; } } /// <summary> /// Gets or sets the remote balancer. /// </summary> /// <value>The remote balancer.</value> public Type RemoteBalancer { get { return m_RemoteBalancer; } set { if (value != typeof(FairLoadBalancer) && value != typeof(RRLoadBalancer) && value != typeof(PredictiveLoadBalancer)) throw new ArgumentException("value"); m_RemoteBalancer = value; } } /// <summary> /// Gets or sets the size of the queue. /// </summary> /// <value>The size of the queue.</value> public Int32 QueueSize { get { return m_QueueSize; } set { m_QueueSize = value; } } /// <summary> /// Gets or sets the number of threads. /// </summary> /// <value>The number of threads.</value> public Int32 NumberOfThreads { get { return m_NumberOfThreads; } set { m_NumberOfThreads = value; } } #endregion #region ICloneable Members public Object Clone() { XmlStoredWorkSpace newCopy = new XmlStoredWorkSpace(m_XmlFileName); foreach(IServer server in m_Servers) { newCopy.m_Servers.Add((IServer)server.Clone()); } return newCopy; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; using SplitAndMerge; using Syncfusion.SfDataGrid; namespace SplitAndMerge { public class DataModel : INotifyPropertyChanged { public enum COL_TYPE { STRING, INT, DOUBLE, CURRENCY, DATE }; public static List<string> ColNames = new List<string>(); public static List<COL_TYPE> ColTypes = new List<COL_TYPE>(); ObservableCollection<DataPoint> m_data = new ObservableCollection<DataPoint>(); SfDataGrid m_grid; public DataModel(SfDataGrid grid) { m_grid = grid; } public ObservableCollection<DataPoint> DataPoints { get { return m_data; } set { m_data = value; OnPropertyChanged("DataPoints"); } } public void SwapRows(int from, int to) { if (from == to) { return; } //if (from < to - 1) { // to--; //} Console.WriteLine("Old: " + ToString()); ObservableCollection<DataPoint> newData = new ObservableCollection<DataPoint>(); int min = Math.Min(from, to); int max = Math.Max(from, to); for (int i = 0; i < min; i++) { newData.Add(new DataPoint(m_data[i])); } if (from < to) { for (int i = min; i < max; i++) { newData.Add(new DataPoint(m_data[i + 1])); } newData.Add(new DataPoint(m_data[from])); } else { newData.Add(new DataPoint(m_data[from])); for (int i = min; i < max; i++) { newData.Add(new DataPoint(m_data[i])); } } for (int i = max + 1; i < m_data.Count; i++) { DataPoint pt = new DataPoint(m_data[i]); newData.Add(new DataPoint(m_data[i])); } m_data = newData; Console.WriteLine("New: " + ToString()); } public void Reload() { List<DataPoint> points = new List<DataPoint>(m_data); m_data = new ObservableCollection<DataPoint>(points); OnPropertyChanged("DataPoints"); } public void Sort(string colName, bool ascending) { int colId = ColName2Id(colName); List<DataPoint> points = new List<DataPoint>(m_data); if (ColTypes[colId] == COL_TYPE.STRING) { points.Sort((a, b) => a.GetStringValue(colId).CompareTo(b.GetStringValue(colId))); } else { points.Sort((a, b) => a.GetNumValue(colId).CompareTo(b.GetNumValue(colId))); } if (!ascending) { points.Reverse(); } m_data = new ObservableCollection<DataPoint>(points); } public int ColName2Id(string colName) { string idStr = colName.Substring(3); int id = (int)Utils.ConvertToDouble(idStr); return id; } public void SetColumnWidths(List<string> data) { var totalAdjusted = 0.0; List<double> widths = new List<double>(data.Count); for (int i = 0; i < data.Count && i < m_grid.Columns.Count; i++) { var width = Double.Parse(data[i]); totalAdjusted += width; widths.Add(width); } if (totalAdjusted <= 0.0) { return; } #if __ANDROID__ var total = m_grid.LayoutParameters.Width; return; #elif __IOS__ var total = m_grid.Frame.Width; #endif for (int i = 0; i < widths.Count; i++) { var width = widths[i]; var column = m_grid.Columns[i]; column.Width = (width / totalAdjusted) * total; } } public void AddColumns(List<string> data) { for (int i = 0; i < data.Count - 1; i += 2) { GridTextColumn column = new GridTextColumn(); column.HeaderText = data[i]; ColNames.Add(data[i]); switch (data[i + 1]) { case "string": column.MappingName = "Str" + i / 2; ColTypes.Add(COL_TYPE.STRING); break; case "currency": column.MappingName = "Num" + i / 2; ColTypes.Add(COL_TYPE.CURRENCY); column.Format = "C"; break; case "number": column.MappingName = "Num" + i / 2; ColTypes.Add(COL_TYPE.DOUBLE); break; default: column.MappingName = "Str" + i / 2; ColTypes.Add(COL_TYPE.STRING); break; } m_grid.Columns.Add(column); } } public void AddPoint(List<string> values) { DataPoint dataPoint = new DataPoint(values); m_data.Add(dataPoint); dataPoint.PropertyChanged += (sender, e) => { OnPropertyChanged(e.PropertyName); }; OnPropertyChanged("DataPoints"); } public void RemovePoint(int rowIndex) { m_data.RemoveAt(rowIndex); OnPropertyChanged("DataPoints"); } public void Clear() { m_data.Clear(); OnPropertyChanged("DataPoints"); } public DataPoint GetPoint(int rowIndex) { if (rowIndex < 0 || rowIndex >= m_data.Count) { return null; } return m_data[rowIndex]; } public override string ToString() { StringBuilder result = new StringBuilder(); for (int i = 0; i < m_data.Count; i++) { result.Append(m_data[i].ToString() + ", "); } return result.ToString(); } void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } public class DataPoint : INotifyPropertyChanged { const int MAX_COLS = 10; IComparable xValue; List<string> m_str = new List<string>(new string[MAX_COLS]); List<int> m_int = new List<int>(new int[MAX_COLS]); List<double> m_num = new List<double>(new double[MAX_COLS]); public string Title { get; set; } public IComparable XValue { get { return xValue; } set { xValue = value; OnPropertyChanged("XValue"); } } double yValue; public double YValue { get { return yValue; } set { yValue = value; OnPropertyChanged("YValue"); } } public string Str0 { get { return m_str[0]; } set { m_str[0] = value; OnPropertyChanged("Str0"); } } public string Str1 { get { return m_str[1]; } set { m_str[1] = value; OnPropertyChanged("Str1"); } } public string Str2 { get { return m_str[2]; } set { m_str[2] = value; OnPropertyChanged("Str2"); } } public string Str3 { get { return m_str[3]; } set { m_str[3] = value; OnPropertyChanged("Str3"); } } public string Str4 { get { return m_str[4]; } set { m_str[4] = value; OnPropertyChanged("Str4"); } } public string Str5 { get { return m_str[5]; } set { m_str[5] = value; OnPropertyChanged("Str5"); } } public string Str6 { get { return m_str[6]; } set { m_str[6] = value; OnPropertyChanged("Str6"); } } public string Str7 { get { return m_str[7]; } set { m_str[7] = value; OnPropertyChanged("Str7"); } } public string Str8 { get { return m_str[8]; } set { m_str[8] = value; OnPropertyChanged("Str8"); } } public string Str9 { get { return m_str[9]; } set { m_str[9] = value; OnPropertyChanged("Str9"); } } public double Num0 { get { return m_num[0]; } set { m_num[0] = value; OnPropertyChanged("Num0"); } } public double Num1 { get { return m_num[1]; } set { m_num[1] = value; OnPropertyChanged("Num1"); } } public double Num2 { get { return m_num[2]; } set { m_num[2] = value; OnPropertyChanged("Num2"); } } public double Num3 { get { return m_num[3]; } set { m_num[3] = value; OnPropertyChanged("Num3"); } } public double Num4 { get { return m_num[4]; } set { m_num[4] = value; OnPropertyChanged("Num4"); } } public double Num5 { get { return m_num[5]; } set { m_num[5] = value; OnPropertyChanged("Num5"); } } public double Num6 { get { return m_num[6]; } set { m_num[6] = value; OnPropertyChanged("Num6"); } } public double Num7 { get { return m_num[7]; } set { m_num[7] = value; OnPropertyChanged("Num7"); } } public double Num8 { get { return m_num[8]; } set { m_num[8] = value; OnPropertyChanged("Num8"); } } public double Num9 { get { return m_num[9]; } set { m_num[9] = value; OnPropertyChanged("Num9"); } } public DataPoint() { } public DataPoint(IComparable xValue, double yValue, string title = "") { XValue = xValue; YValue = yValue; Title = title; } public DataPoint(List<string> values, string title = "") { Title = title; for (int i = 0; i < values.Count; i++) { Set(i, values[i]); } } public DataPoint(DataPoint other) { SetDataPoint(other); } public void SetDataPoint(DataPoint other) { Title = other.Title; for (int i = 0; i < DataModel.ColNames.Count; i++) { Set(i, other.GetStringValue(i)); } } public void Set(int index, string value) { if (DataModel.ColTypes[index] == DataModel.COL_TYPE.STRING) { m_str[index] = value; } else { m_num[index] = Utils.ConvertToDouble(value); } } public void Assign(int index, string value) { if (index == 0) { Str0 = value; return; } if (index == 1) { Str1 = value; return; } if (index == 2) { Str2 = value; return; } if (index == 3) { Str3 = value; return; } if (index == 4) { Str4 = value; return; } if (index == 5) { Str5 = value; return; } if (index == 6) { Str6 = value; return; } if (index == 7) { Str7 = value; return; } if (index == 8) { Str8 = value; return; } if (index == 9) { Str9 = value; return; } } public void Assign(int index, double value) { if (index == 0) { Num0 = value; return; } if (index == 1) { Num1 = value; return; } if (index == 2) { Num2 = value; return; } if (index == 3) { Num3 = value; return; } if (index == 4) { Num4 = value; return; } if (index == 5) { Num5 = value; return; } if (index == 6) { Num6 = value; return; } if (index == 7) { Num7 = value; return; } if (index == 8) { Num8 = value; return; } if (index == 9) { Num9 = value; return; } } public string GetStringValue(int index) { if (DataModel.ColTypes.Count <= index) { return ""; } else if (DataModel.ColTypes[index] == DataModel.COL_TYPE.STRING) { return m_str[index]; } else { return "" + m_num[index]; } } public double GetNumValue(int index) { return m_num[index]; } public override string ToString() { StringBuilder result = new StringBuilder(); #pragma warning disable CS0162 // Unreachable code detected for (int i = 0; i < MAX_COLS; i++) #pragma warning restore CS0162 // Unreachable code detected { var part = GetStringValue(i); if (string.IsNullOrEmpty(part)) { break; } result.Append(GetStringValue(i) + " "); break; } return result.ToString(); } void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } }
// 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 Debug = System.Diagnostics.Debug; namespace System.Xml.Linq { internal class XNodeReader : XmlReader, IXmlLineInfo { private static readonly char[] s_WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; // The reader position is encoded by the tuple (source, parent). // Lazy text uses (instance, parent element). Attribute value // uses (instance, parent attribute). End element uses (instance, // instance). Common XObject uses (instance, null). private object _source; private object _parent; private ReadState _state; private XNode _root; private XmlNameTable _nameTable; private bool _omitDuplicateNamespaces; internal XNodeReader(XNode node, XmlNameTable nameTable, ReaderOptions options) { _source = node; _root = node; _nameTable = nameTable != null ? nameTable : CreateNameTable(); _omitDuplicateNamespaces = (options & ReaderOptions.OmitDuplicateNamespaces) != 0 ? true : false; } internal XNodeReader(XNode node, XmlNameTable nameTable) : this(node, nameTable, (node.GetSaveOptionsFromAnnotations() & SaveOptions.OmitDuplicateNamespaces) != 0 ? ReaderOptions.OmitDuplicateNamespaces : ReaderOptions.None) { } public override int AttributeCount { get { if (!IsInteractive) { return 0; } int count = 0; XElement e = GetElementInAttributeScope(); if (e != null) { XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { count++; } } while (a != e.lastAttr); } } return count; } } public override string BaseURI { get { XObject o = _source as XObject; if (o != null) { return o.BaseUri; } o = _parent as XObject; if (o != null) { return o.BaseUri; } return string.Empty; } } public override int Depth { get { if (!IsInteractive) { return 0; } XObject o = _source as XObject; if (o != null) { return GetDepth(o); } o = _parent as XObject; if (o != null) { return GetDepth(o) + 1; } return 0; } } private static int GetDepth(XObject o) { int depth = 0; while (o.parent != null) { depth++; o = o.parent; } if (o is XDocument) { depth--; } return depth; } public override bool EOF { get { return _state == ReadState.EndOfFile; } } public override bool HasAttributes { get { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null && e.lastAttr != null) { if (_omitDuplicateNamespaces) { return GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next) != null; } else { return true; } } else { return false; } } } public override bool HasValue { get { if (!IsInteractive) { return false; } XObject o = _source as XObject; if (o != null) { switch (o.NodeType) { case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: return true; default: return false; } } return true; } } public override bool IsEmptyElement { get { if (!IsInteractive) { return false; } XElement e = _source as XElement; return e != null && e.IsEmpty; } } public override string LocalName { get { return _nameTable.Add(GetLocalName()); } } private string GetLocalName() { if (!IsInteractive) { return string.Empty; } XElement e = _source as XElement; if (e != null) { return e.Name.LocalName; } XAttribute a = _source as XAttribute; if (a != null) { return a.Name.LocalName; } XProcessingInstruction p = _source as XProcessingInstruction; if (p != null) { return p.Target; } XDocumentType n = _source as XDocumentType; if (n != null) { return n.Name; } return string.Empty; } public override string Name { get { string prefix = GetPrefix(); if (prefix.Length == 0) { return _nameTable.Add(GetLocalName()); } return _nameTable.Add(string.Concat(prefix, ":", GetLocalName())); } } public override string NamespaceURI { get { return _nameTable.Add(GetNamespaceURI()); } } private string GetNamespaceURI() { if (!IsInteractive) { return string.Empty; } XElement e = _source as XElement; if (e != null) { return e.Name.NamespaceName; } XAttribute a = _source as XAttribute; if (a != null) { string namespaceName = a.Name.NamespaceName; if (namespaceName.Length == 0 && a.Name.LocalName == "xmlns") { return XNamespace.xmlnsPrefixNamespace; } return namespaceName; } return string.Empty; } public override XmlNameTable NameTable { get { return _nameTable; } } public override XmlNodeType NodeType { get { if (!IsInteractive) { return XmlNodeType.None; } XObject o = _source as XObject; if (o != null) { if (IsEndElement) { return XmlNodeType.EndElement; } XmlNodeType nt = o.NodeType; if (nt != XmlNodeType.Text) { return nt; } if (o.parent != null && o.parent.parent == null && o.parent is XDocument) { return XmlNodeType.Whitespace; } return XmlNodeType.Text; } if (_parent is XDocument) { return XmlNodeType.Whitespace; } return XmlNodeType.Text; } } public override string Prefix { get { return _nameTable.Add(GetPrefix()); } } private string GetPrefix() { if (!IsInteractive) { return string.Empty; } XElement e = _source as XElement; if (e != null) { string prefix = e.GetPrefixOfNamespace(e.Name.Namespace); if (prefix != null) { return prefix; } return string.Empty; } XAttribute a = _source as XAttribute; if (a != null) { string prefix = a.GetPrefixOfNamespace(a.Name.Namespace); if (prefix != null) { return prefix; } } return string.Empty; } public override ReadState ReadState { get { return _state; } } public override XmlReaderSettings Settings { get { XmlReaderSettings settings = new XmlReaderSettings(); settings.CheckCharacters = false; return settings; } } public override string Value { get { if (!IsInteractive) { return string.Empty; } XObject o = _source as XObject; if (o != null) { switch (o.NodeType) { case XmlNodeType.Attribute: return ((XAttribute)o).Value; case XmlNodeType.Text: case XmlNodeType.CDATA: return ((XText)o).Value; case XmlNodeType.Comment: return ((XComment)o).Value; case XmlNodeType.ProcessingInstruction: return ((XProcessingInstruction)o).Data; case XmlNodeType.DocumentType: return ((XDocumentType)o).InternalSubset; default: return string.Empty; } } return (string)_source; } } public override string XmlLang { get { if (!IsInteractive) { return string.Empty; } XElement e = GetElementInScope(); if (e != null) { XName name = XNamespace.Xml.GetName("lang"); do { XAttribute a = e.Attribute(name); if (a != null) { return a.Value; } e = e.parent as XElement; } while (e != null); } return string.Empty; } } public override XmlSpace XmlSpace { get { if (!IsInteractive) { return XmlSpace.None; } XElement e = GetElementInScope(); if (e != null) { XName name = XNamespace.Xml.GetName("space"); do { XAttribute a = e.Attribute(name); if (a != null) { switch (a.Value.Trim(s_WhitespaceChars)) { case "preserve": return XmlSpace.Preserve; case "default": return XmlSpace.Default; default: break; } } e = e.parent as XElement; } while (e != null); } return XmlSpace.None; } } protected override void Dispose(bool disposing) { if (disposing && ReadState != ReadState.Closed) { Close(); } } private void Close() { _source = null; _parent = null; _root = null; _state = ReadState.Closed; } public override string GetAttribute(string name) { if (!IsInteractive) { return null; } XElement e = GetElementInAttributeScope(); if (e != null) { string localName, namespaceName; GetNameInAttributeScope(name, e, out localName, out namespaceName); XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { return null; } else { return a.Value; } } } while (a != e.lastAttr); } return null; } XDocumentType n = _source as XDocumentType; if (n != null) { switch (name) { case "PUBLIC": return n.PublicId; case "SYSTEM": return n.SystemId; } } return null; } public override string GetAttribute(string localName, string namespaceName) { if (!IsInteractive) { return null; } XElement e = GetElementInAttributeScope(); if (e != null) { if (localName == "xmlns") { if (namespaceName != null && namespaceName.Length == 0) { return null; } if (namespaceName == XNamespace.xmlnsPrefixNamespace) { namespaceName = string.Empty; } } XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { return null; } else { return a.Value; } } } while (a != e.lastAttr); } } return null; } public override string GetAttribute(int index) { if (!IsInteractive) { return null; } if (index < 0) { return null; } XElement e = GetElementInAttributeScope(); if (e != null) { XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { if (index-- == 0) { return a.Value; } } } while (a != e.lastAttr); } } return null; } public override string LookupNamespace(string prefix) { if (!IsInteractive) { return null; } if (prefix == null) { return null; } XElement e = GetElementInScope(); if (e != null) { XNamespace ns = prefix.Length == 0 ? e.GetDefaultNamespace() : e.GetNamespaceOfPrefix(prefix); if (ns != null) { return _nameTable.Add(ns.NamespaceName); } } return null; } public override bool MoveToAttribute(string name) { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null) { string localName, namespaceName; GetNameInAttributeScope(name, e, out localName, out namespaceName); XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { // If it's a duplicate namespace attribute just act as if it doesn't exist return false; } else { _source = a; _parent = null; return true; } } } while (a != e.lastAttr); } } return false; } public override bool MoveToAttribute(string localName, string namespaceName) { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null) { if (localName == "xmlns") { if (namespaceName != null && namespaceName.Length == 0) { return false; } if (namespaceName == XNamespace.xmlnsPrefixNamespace) { namespaceName = string.Empty; } } XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { // If it's a duplicate namespace attribute just act as if it doesn't exist return false; } else { _source = a; _parent = null; return true; } } } while (a != e.lastAttr); } } return false; } public override void MoveToAttribute(int index) { if (!IsInteractive) { return; } if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); XElement e = GetElementInAttributeScope(); if (e != null) { XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { // Only count those which are non-duplicates if we're asked to if (index-- == 0) { _source = a; _parent = null; return; } } } while (a != e.lastAttr); } } throw new ArgumentOutOfRangeException(nameof(index)); } public override bool MoveToElement() { if (!IsInteractive) { return false; } XAttribute a = _source as XAttribute; if (a == null) { a = _parent as XAttribute; } if (a != null) { if (a.parent != null) { _source = a.parent; _parent = null; return true; } } return false; } public override bool MoveToFirstAttribute() { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null) { if (e.lastAttr != null) { if (_omitDuplicateNamespaces) { object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next); if (na == null) { return false; } _source = na; } else { _source = e.lastAttr.next; } return true; } } return false; } public override bool MoveToNextAttribute() { if (!IsInteractive) { return false; } XElement e = _source as XElement; if (e != null) { if (IsEndElement) { return false; } if (e.lastAttr != null) { if (_omitDuplicateNamespaces) { // Skip duplicate namespace attributes // We must NOT modify the this.source until we find the one we're looking for // because if we don't find anything, we need to stay positioned where we're now object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next); if (na == null) { return false; } _source = na; } else { _source = e.lastAttr.next; } return true; } return false; } XAttribute a = _source as XAttribute; if (a == null) { a = _parent as XAttribute; } if (a != null) { if (a.parent != null && ((XElement)a.parent).lastAttr != a) { if (_omitDuplicateNamespaces) { // Skip duplicate namespace attributes // We must NOT modify the this.source until we find the one we're looking for // because if we don't find anything, we need to stay positioned where we're now object na = GetFirstNonDuplicateNamespaceAttribute(a.next); if (na == null) { return false; } _source = na; } else { _source = a.next; } _parent = null; return true; } } return false; } public override bool Read() { switch (_state) { case ReadState.Initial: _state = ReadState.Interactive; XDocument d = _source as XDocument; if (d != null) { return ReadIntoDocument(d); } return true; case ReadState.Interactive: return Read(false); default: return false; } } public override bool ReadAttributeValue() { if (!IsInteractive) { return false; } XAttribute a = _source as XAttribute; if (a != null) { return ReadIntoAttribute(a); } return false; } public override bool ReadToDescendant(string localName, string namespaceName) { if (!IsInteractive) { return false; } MoveToElement(); XElement c = _source as XElement; if (c != null && !c.IsEmpty) { if (IsEndElement) { return false; } foreach (XElement e in c.Descendants()) { if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { _source = e; return true; } } IsEndElement = true; } return false; } public override bool ReadToFollowing(string localName, string namespaceName) { while (Read()) { XElement e = _source as XElement; if (e != null) { if (IsEndElement) continue; if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { return true; } } } return false; } public override bool ReadToNextSibling(string localName, string namespaceName) { if (!IsInteractive) { return false; } MoveToElement(); if (_source != _root) { XNode n = _source as XNode; if (n != null) { foreach (XElement e in n.ElementsAfterSelf()) { if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { _source = e; IsEndElement = false; return true; } } if (n.parent is XElement) { _source = n.parent; IsEndElement = true; return false; } } else { if (_parent is XElement) { _source = _parent; _parent = null; IsEndElement = true; return false; } } } return ReadToEnd(); } public override void ResolveEntity() { } public override void Skip() { if (!IsInteractive) { return; } Read(true); } bool IXmlLineInfo.HasLineInfo() { if (IsEndElement) { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement XElement e = _source as XElement; if (e != null) { return e.Annotation<LineInfoEndElementAnnotation>() != null; } } else { IXmlLineInfo li = _source as IXmlLineInfo; if (li != null) { return li.HasLineInfo(); } } return false; } int IXmlLineInfo.LineNumber { get { if (IsEndElement) { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement XElement e = _source as XElement; if (e != null) { LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>(); if (a != null) { return a.lineNumber; } } } else { IXmlLineInfo li = _source as IXmlLineInfo; if (li != null) { return li.LineNumber; } } return 0; } } int IXmlLineInfo.LinePosition { get { if (IsEndElement) { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement XElement e = _source as XElement; if (e != null) { LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>(); if (a != null) { return a.linePosition; } } } else { IXmlLineInfo li = _source as IXmlLineInfo; if (li != null) { return li.LinePosition; } } return 0; } } private bool IsEndElement { get { return _parent == _source; } set { _parent = value ? _source : null; } } private bool IsInteractive { get { return _state == ReadState.Interactive; } } private static XmlNameTable CreateNameTable() { XmlNameTable nameTable = new NameTable(); nameTable.Add(string.Empty); nameTable.Add(XNamespace.xmlnsPrefixNamespace); nameTable.Add(XNamespace.xmlPrefixNamespace); return nameTable; } private XElement GetElementInAttributeScope() { XElement e = _source as XElement; if (e != null) { if (IsEndElement) { return null; } return e; } XAttribute a = _source as XAttribute; if (a != null) { return (XElement)a.parent; } a = _parent as XAttribute; if (a != null) { return (XElement)a.parent; } return null; } private XElement GetElementInScope() { XElement e = _source as XElement; if (e != null) { return e; } XNode n = _source as XNode; if (n != null) { return n.parent as XElement; } XAttribute a = _source as XAttribute; if (a != null) { return (XElement)a.parent; } e = _parent as XElement; if (e != null) { return e; } a = _parent as XAttribute; if (a != null) { return (XElement)a.parent; } return null; } private static void GetNameInAttributeScope(string qualifiedName, XElement e, out string localName, out string namespaceName) { if (!string.IsNullOrEmpty(qualifiedName)) { int i = qualifiedName.IndexOf(':'); if (i != 0 && i != qualifiedName.Length - 1) { if (i == -1) { localName = qualifiedName; namespaceName = string.Empty; return; } XNamespace ns = e.GetNamespaceOfPrefix(qualifiedName.Substring(0, i)); if (ns != null) { localName = qualifiedName.Substring(i + 1, qualifiedName.Length - i - 1); namespaceName = ns.NamespaceName; return; } } } localName = null; namespaceName = null; } private bool Read(bool skipContent) { XElement e = _source as XElement; if (e != null) { if (e.IsEmpty || IsEndElement || skipContent) { return ReadOverNode(e); } return ReadIntoElement(e); } XNode n = _source as XNode; if (n != null) { return ReadOverNode(n); } XAttribute a = _source as XAttribute; if (a != null) { return ReadOverAttribute(a, skipContent); } return ReadOverText(skipContent); } private bool ReadIntoDocument(XDocument d) { XNode n = d.content as XNode; if (n != null) { _source = n.next; return true; } string s = d.content as string; if (s != null) { if (s.Length > 0) { _source = s; _parent = d; return true; } } return ReadToEnd(); } private bool ReadIntoElement(XElement e) { XNode n = e.content as XNode; if (n != null) { _source = n.next; return true; } string s = e.content as string; if (s != null) { if (s.Length > 0) { _source = s; _parent = e; } else { _source = e; IsEndElement = true; } return true; } return ReadToEnd(); } private bool ReadIntoAttribute(XAttribute a) { _source = a.value; _parent = a; return true; } private bool ReadOverAttribute(XAttribute a, bool skipContent) { XElement e = (XElement)a.parent; if (e != null) { if (e.IsEmpty || skipContent) { return ReadOverNode(e); } return ReadIntoElement(e); } return ReadToEnd(); } private bool ReadOverNode(XNode n) { if (n == _root) { return ReadToEnd(); } XNode next = n.next; if (null == next || next == n || n == n.parent.content) { if (n.parent == null || (n.parent.parent == null && n.parent is XDocument)) { return ReadToEnd(); } _source = n.parent; IsEndElement = true; } else { _source = next; IsEndElement = false; } return true; } private bool ReadOverText(bool skipContent) { if (_parent is XElement) { _source = _parent; _parent = null; IsEndElement = true; return true; } XAttribute parent = _parent as XAttribute; if (parent != null) { _parent = null; return ReadOverAttribute(parent, skipContent); } return ReadToEnd(); } private bool ReadToEnd() { _state = ReadState.EndOfFile; return false; } /// <summary> /// Determines if the specified attribute would be a duplicate namespace declaration /// - one which we already reported on some ancestor, so it's not necessary to report it here /// </summary> /// <param name="candidateAttribute">The attribute to test.</param> /// <returns>true if the attribute is a duplicate namespace declaration attribute</returns> private bool IsDuplicateNamespaceAttribute(XAttribute candidateAttribute) { if (!candidateAttribute.IsNamespaceDeclaration) { return false; } else { // Split the method in two to enable inlining of this piece (Which will work for 95% of cases) return IsDuplicateNamespaceAttributeInner(candidateAttribute); } } private bool IsDuplicateNamespaceAttributeInner(XAttribute candidateAttribute) { // First of all - if this is an xmlns:xml declaration then it's a duplicate // since xml prefix can't be redeclared and it's declared by default always. if (candidateAttribute.Name.LocalName == "xml") { return true; } // The algorithm we use is: // Go up the tree (but don't go higher than the root of this reader) // and find the closest namespace declaration attribute which declares the same prefix // If it declares that prefix to the exact same URI as ours does then ours is a duplicate // Note that if we find a namespace declaration for the same prefix but with a different URI, then we don't have a dupe! XElement element = candidateAttribute.parent as XElement; if (element == _root || element == null) { // If there's only the parent element of our attribute, there can be no duplicates return false; } element = element.parent as XElement; while (element != null) { // Search all attributes of this element for the same prefix declaration // Trick - a declaration for the same prefix will have the exact same XName - so we can do a quick ref comparison of names // (The default ns decl is represented by an XName "xmlns{}", even if you try to create // an attribute with XName "xmlns{http://www.w3.org/2000/xmlns/}" it will fail, // because it's treated as a declaration of prefix "xmlns" which is invalid) XAttribute a = element.lastAttr; if (a != null) { do { if (a.name == candidateAttribute.name) { // Found the same prefix decl if (a.Value == candidateAttribute.Value) { // And it's for the same namespace URI as well - so ours is a duplicate return true; } else { // It's not for the same namespace URI - which means we have to keep ours // (no need to continue the search as this one overrides anything above it) return false; } } a = a.next; } while (a != element.lastAttr); } if (element == _root) { return false; } element = element.parent as XElement; } return false; } /// <summary> /// Finds a first attribute (starting with the parameter) which is not a duplicate namespace attribute /// </summary> /// <param name="candidate">The attribute to start with</param> /// <returns>The first attribute which is not a namespace attribute or null if the end of attributes has bean reached</returns> private XAttribute GetFirstNonDuplicateNamespaceAttribute(XAttribute candidate) { Debug.Assert(_omitDuplicateNamespaces, "This method should only be called if we're omitting duplicate namespace attribute." + "For perf reason it's better to test this flag in the caller method."); if (!IsDuplicateNamespaceAttribute(candidate)) { return candidate; } XElement e = candidate.parent as XElement; if (e != null && candidate != e.lastAttr) { do { candidate = candidate.next; if (!IsDuplicateNamespaceAttribute(candidate)) { return candidate; } } while (candidate != e.lastAttr); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_FULL_CONSOLE using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using Microsoft.Scripting.Hosting.Shell; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace IronPython.Hosting { public sealed class PythonOptionsParser : OptionsParser<PythonConsoleOptions> { private List<string> _warningFilters; public PythonOptionsParser() { } /// <exception cref="Exception">On error.</exception> protected override void ParseArgument(string/*!*/ arg) { ContractUtils.RequiresNotNull(arg, "arg"); switch (arg) { case "-B": break; // dont_write_bytecode always true in IronPython case "-U": break; // unicode always true in IronPython case "-d": break; // debug output from parser, always False in IronPython case "-b": // Not shown in help on CPython LanguageSetup.Options["BytesWarning"] = ScriptingRuntimeHelpers.True; break; case "-c": ConsoleOptions.Command = PeekNextArg(); string[] arguments = PopRemainingArgs(); arguments[0] = arg; LanguageSetup.Options["Arguments"] = arguments; break; case "-?": ConsoleOptions.PrintUsage = true; ConsoleOptions.Exit = true; break; case "-i": ConsoleOptions.Introspection = true; LanguageSetup.Options["Inspect"] = ScriptingRuntimeHelpers.True; break; case "-m": ConsoleOptions.ModuleToRun = PeekNextArg(); LanguageSetup.Options["Arguments"] = PopRemainingArgs(); break; case "-x": ConsoleOptions.SkipFirstSourceLine = true; break; // TODO: unbuffered stdout? case "-u": break; // TODO: create a trace listener? case "-v": LanguageSetup.Options["Verbose"] = ScriptingRuntimeHelpers.True; break; case "-S": ConsoleOptions.SkipImportSite = true; LanguageSetup.Options["NoSite"] = ScriptingRuntimeHelpers.True; break; case "-s": LanguageSetup.Options["NoUserSite"] = ScriptingRuntimeHelpers.True; break; case "-E": ConsoleOptions.IgnoreEnvironmentVariables = true; LanguageSetup.Options["IgnoreEnvironment"] = ScriptingRuntimeHelpers.True; break; case "-t": LanguageSetup.Options["IndentationInconsistencySeverity"] = Severity.Warning; break; case "-tt": LanguageSetup.Options["IndentationInconsistencySeverity"] = Severity.Error; break; case "-O": LanguageSetup.Options["Optimize"] = ScriptingRuntimeHelpers.True; break; case "-OO": LanguageSetup.Options["Optimize"] = ScriptingRuntimeHelpers.True; LanguageSetup.Options["StripDocStrings"] = ScriptingRuntimeHelpers.True; break; case "-Q": LanguageSetup.Options["DivisionOptions"] = ToDivisionOptions(PopNextArg()); break; case "-Qold": case "-Qnew": case "-Qwarn": case "-Qwarnall": LanguageSetup.Options["DivisionOptions"] = ToDivisionOptions(arg.Substring(2)); break; case "-V": ConsoleOptions.PrintVersion = true; ConsoleOptions.Exit = true; IgnoreRemainingArgs(); break; case "-W": if (_warningFilters == null) { _warningFilters = new List<string>(); } _warningFilters.Add(PopNextArg()); break; case "-3": LanguageSetup.Options["WarnPy3k"] = ScriptingRuntimeHelpers.True; break; case "-": PushArgBack(); LanguageSetup.Options["Arguments"] = PopRemainingArgs(); break; case "-X:NoFrames": if(LanguageSetup.Options.ContainsKey("Frames") && LanguageSetup.Options["Frames"] != ScriptingRuntimeHelpers.False) { throw new InvalidOptionException("Only one of -X:[Full]Frames/-X:NoFrames may be specified"); } LanguageSetup.Options["Frames"] = ScriptingRuntimeHelpers.False; break; case "-X:Frames": if (LanguageSetup.Options.ContainsKey("Frames") && LanguageSetup.Options["Frames"] != ScriptingRuntimeHelpers.True) { throw new InvalidOptionException("Only one of -X:[Full]Frames/-X:NoFrames may be specified"); } LanguageSetup.Options["Frames"] = ScriptingRuntimeHelpers.True; break; case "-X:FullFrames": if(LanguageSetup.Options.ContainsKey("Frames") && LanguageSetup.Options["Frames"] != ScriptingRuntimeHelpers.True) { throw new InvalidOptionException("Only one of -X:[Full]Frames/-X:NoFrames may be specified"); } LanguageSetup.Options["Frames"] = LanguageSetup.Options["FullFrames"] = ScriptingRuntimeHelpers.True; break; case "-X:Tracing": LanguageSetup.Options["Tracing"] = ScriptingRuntimeHelpers.True; break; case "-X:GCStress": int gcStress; if (!int.TryParse(PopNextArg(), out gcStress) || (gcStress < 0 || gcStress > GC.MaxGeneration)) { throw new InvalidOptionException(String.Format("The argument for the {0} option must be between 0 and {1}.", arg, GC.MaxGeneration)); } LanguageSetup.Options["GCStress"] = gcStress; break; case "-X:MaxRecursion": // we need about 6 frames for starting up, so 10 is a nice round number. int limit; if (!int.TryParse(PopNextArg(), out limit) || limit < 10) { throw new InvalidOptionException(String.Format("The argument for the {0} option must be an integer >= 10.", arg)); } LanguageSetup.Options["RecursionLimit"] = limit; break; case "-X:EnableProfiler": LanguageSetup.Options["EnableProfiler"] = ScriptingRuntimeHelpers.True; break; case "-X:LightweightScopes": LanguageSetup.Options["LightweightScopes"] = ScriptingRuntimeHelpers.True; break; case "-X:MTA": ConsoleOptions.IsMta = true; break; case "-X:Python30": LanguageSetup.Options["PythonVersion"] = new Version(3, 0); break; case "-X:Debug": RuntimeSetup.DebugMode = true; LanguageSetup.Options["Debug"] = ScriptingRuntimeHelpers.True; break; case "-X:NoDebug": string regex = PopNextArg(); try { LanguageSetup.Options["NoDebug"] = new Regex(regex); } catch { throw InvalidOptionValue("-X:NoDebug", regex); } break; case "-X:BasicConsole": ConsoleOptions.BasicConsole = true; break; default: if(arg.StartsWith("-W")) { if (_warningFilters == null) { _warningFilters = new List<string>(); } _warningFilters.Add(arg.Substring(2)); break; } if(arg.StartsWith("-m")) { ConsoleOptions.ModuleToRun = arg.Substring(2); LanguageSetup.Options["Arguments"] = PopRemainingArgs(); break; } base.ParseArgument(arg); if (ConsoleOptions.FileName != null) { PushArgBack(); LanguageSetup.Options["Arguments"] = PopRemainingArgs(); } break; } } protected override void AfterParse() { if (_warningFilters != null) { LanguageSetup.Options["WarningFilters"] = _warningFilters.ToArray(); } } private static PythonDivisionOptions ToDivisionOptions(string/*!*/ value) { switch (value) { case "old": return PythonDivisionOptions.Old; case "new": return PythonDivisionOptions.New; case "warn": return PythonDivisionOptions.Warn; case "warnall": return PythonDivisionOptions.WarnAll; default: throw InvalidOptionValue("-Q", value); } } public override void GetHelp(out string commandLine, out string[,] options, out string[,] environmentVariables, out string comments) { string[,] standardOptions; base.GetHelp(out commandLine, out standardOptions, out environmentVariables, out comments); #if !IRONPYTHON_WINDOW commandLine = "Usage: ipy [options] [file.py|- [arguments]]"; #else commandLine = "Usage: ipyw [options] [file.py|- [arguments]]"; #endif string[,] pythonOptions = new string[,] { #if !IRONPYTHON_WINDOW { "-v", "Verbose (trace import statements) (also PYTHONVERBOSE=x)" }, #endif { "-m module", "run library module as a script"}, { "-x", "Skip first line of the source" }, { "-u", "Unbuffered stdout & stderr" }, { "-O", "generate optimized code" }, { "-OO", "remove doc strings and apply -O optimizations" }, { "-E", "Ignore environment variables" }, { "-Q arg", "Division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew" }, { "-S", "Don't imply 'import site' on initialization" }, { "-s", "Don't add user site directory to sys.path" }, { "-t", "Issue warnings about inconsistent tab usage" }, { "-tt", "Issue errors for inconsistent tab usage" }, { "-W arg", "Warning control (arg is action:message:category:module:lineno) also IRONPYTHONWARNINGS=arg" }, { "-3", "Warn about Python 3.x incompatibilities" }, { "-X:NoFrames", "Disable sys._getframe support, can improve execution speed" }, { "-X:Frames", "Enable basic sys._getframe support" }, { "-X:FullFrames", "Enable sys._getframe with access to locals" }, { "-X:Tracing", "Enable support for tracing all methods even before sys.settrace is called" }, { "-X:GCStress", "Specifies the GC stress level (the generation to collect each statement)" }, { "-X:MaxRecursion", "Set the maximum recursion level" }, { "-X:Debug", "Enable application debugging (preferred over -D)" }, { "-X:NoDebug <regex>", "Provides a regular expression of files which should not be emitted in debug mode"}, { "-X:MTA", "Run in multithreaded apartment" }, { "-X:Python30", "Enable available Python 3.0 features" }, { "-X:EnableProfiler", "Enables profiling support in the compiler" }, { "-X:LightweightScopes", "Generate optimized scopes that can be garbage collected" }, { "-X:BasicConsole", "Use only the basic console features" }, }; // Ensure the combined options come out sorted string[,] allOptions = ArrayUtils.Concatenate(pythonOptions, standardOptions); List<string> optName = new List<string>(); List<int> indiciesList = new List<int>(); for (int i = 0; i < allOptions.Length / 2; i++) { optName.Add(allOptions[i, 0]); indiciesList.Add(i); } int[] indicies = indiciesList.ToArray(); Array.Sort(optName.ToArray(), indicies, StringComparer.OrdinalIgnoreCase); options = new string[allOptions.Length / 2, 2]; for (int i = 0; i < indicies.Length; i++) { options[i, 0] = allOptions[indicies[i], 0]; options[i, 1] = allOptions[indicies[i], 1]; } Debug.Assert(environmentVariables.GetLength(0) == 0); // No need to append if the default is empty environmentVariables = new string[,] { { "IRONPYTHONPATH", "Path to search for module" }, { "IRONPYTHONSTARTUP", "Startup module" } }; } } } #endif
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudioTools.Project; using VSConstants = Microsoft.VisualStudio.VSConstants; namespace Microsoft.VisualStudioTools.Navigation { class HierarchyEventArgs : EventArgs { private uint _itemId; private string _fileName; private IVsTextLines _buffer; public HierarchyEventArgs(uint itemId, string canonicalName) { _itemId = itemId; _fileName = canonicalName; } public string CanonicalName { get { return _fileName; } } public uint ItemID { get { return _itemId; } } public IVsTextLines TextBuffer { get { return _buffer; } set { _buffer = value; } } } internal abstract partial class LibraryManager : IDisposable, IVsRunningDocTableEvents { internal class HierarchyListener : IVsHierarchyEvents, IDisposable { private IVsHierarchy _hierarchy; private uint _cookie; private LibraryManager _manager; public HierarchyListener(IVsHierarchy hierarchy, LibraryManager manager) { Utilities.ArgumentNotNull("hierarchy", hierarchy); Utilities.ArgumentNotNull("manager", manager); _hierarchy = hierarchy; _manager = manager; } protected IVsHierarchy Hierarchy { get { return _hierarchy; } } #region Public Methods public bool IsListening { get { return (0 != _cookie); } } public void StartListening(bool doInitialScan) { if (0 != _cookie) { return; } ErrorHandler.ThrowOnFailure( _hierarchy.AdviseHierarchyEvents(this, out _cookie)); if (doInitialScan) { InternalScanHierarchy(VSConstants.VSITEMID_ROOT); } } public void StopListening() { InternalStopListening(true); } #endregion #region IDisposable Members public void Dispose() { InternalStopListening(false); _cookie = 0; _hierarchy = null; } #endregion #region IVsHierarchyEvents Members public int OnInvalidateIcon(IntPtr hicon) { // Do Nothing. return VSConstants.S_OK; } public int OnInvalidateItems(uint itemidParent) { // TODO: Find out if this event is needed. return VSConstants.S_OK; } public int OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) { // Check if the item is my language file. string name; if (!IsAnalyzableSource(itemidAdded, out name)) { return VSConstants.S_OK; } // This item is a my language file, so we can notify that it is added to the hierarchy. HierarchyEventArgs args = new HierarchyEventArgs(itemidAdded, name); _manager.OnNewFile(_hierarchy, args); return VSConstants.S_OK; } public int OnItemDeleted(uint itemid) { // Notify that the item is deleted only if it is my language file. string name; if (!IsAnalyzableSource(itemid, out name)) { return VSConstants.S_OK; } HierarchyEventArgs args = new HierarchyEventArgs(itemid, name); _manager.OnDeleteFile(_hierarchy, args); return VSConstants.S_OK; } public int OnItemsAppended(uint itemidParent) { // TODO: Find out what this event is about. return VSConstants.S_OK; } public int OnPropertyChanged(uint itemid, int propid, uint flags) { if ((null == _hierarchy) || (0 == _cookie)) { return VSConstants.S_OK; } string name; if (!IsAnalyzableSource(itemid, out name)) { return VSConstants.S_OK; } if (propid == (int)__VSHPROPID.VSHPROPID_IsNonMemberItem) { _manager.IsNonMemberItemChanged(_hierarchy, new HierarchyEventArgs(itemid, name)); } return VSConstants.S_OK; } #endregion private bool InternalStopListening(bool throwOnError) { if ((null == _hierarchy) || (0 == _cookie)) { return false; } int hr = _hierarchy.UnadviseHierarchyEvents(_cookie); if (throwOnError) { ErrorHandler.ThrowOnFailure(hr); } _cookie = 0; return ErrorHandler.Succeeded(hr); } /// <summary> /// Do a recursive walk on the hierarchy to find all this language files in it. /// It will generate an event for every file found. /// </summary> private void InternalScanHierarchy(uint itemId) { uint currentItem = itemId; while (VSConstants.VSITEMID_NIL != currentItem) { // If this item is a my language file, then send the add item event. string itemName; if (IsAnalyzableSource(currentItem, out itemName)) { HierarchyEventArgs args = new HierarchyEventArgs(currentItem, itemName); _manager.OnNewFile(_hierarchy, args); } // NOTE: At the moment we skip the nested hierarchies, so here we look for the // children of this node. // Before looking at the children we have to make sure that the enumeration has not // side effects to avoid unexpected behavior. object propertyValue; bool canScanSubitems = true; int hr = _hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_HasEnumerationSideEffects, out propertyValue); if ((VSConstants.S_OK == hr) && (propertyValue is bool)) { canScanSubitems = !(bool)propertyValue; } // If it is allow to look at the sub-items of the current one, lets do it. if (canScanSubitems) { object child; hr = _hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_FirstChild, out child); if (VSConstants.S_OK == hr) { // There is a sub-item, call this same function on it. InternalScanHierarchy(GetItemId(child)); } } // Move the current item to its first visible sibling. object sibling; hr = _hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_NextSibling, out sibling); if (VSConstants.S_OK != hr) { currentItem = VSConstants.VSITEMID_NIL; } else { currentItem = GetItemId(sibling); } } } private bool IsAnalyzableSource(uint itemId, out string canonicalName) { // Find out if this item is a physical file. Guid typeGuid; canonicalName = null; int hr; try { hr = Hierarchy.GetGuidProperty(itemId, (int)__VSHPROPID.VSHPROPID_TypeGuid, out typeGuid); } catch (System.Runtime.InteropServices.COMException) { return false; } if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) || VSConstants.GUID_ItemType_PhysicalFile != typeGuid) { // It is not a file, we can exit now. return false; } // This item is a file; find if current language can recognize it. hr = Hierarchy.GetCanonicalName(itemId, out canonicalName); if (ErrorHandler.Failed(hr)) { return false; } return (System.IO.Path.GetExtension(canonicalName).Equals(".xaml", StringComparison.OrdinalIgnoreCase)) || _manager._package.IsRecognizedFile(canonicalName); } /// <summary> /// Gets the item id. /// </summary> /// <param name="variantValue">VARIANT holding an itemid.</param> /// <returns>Item Id of the concerned node</returns> private static uint GetItemId(object variantValue) { if (variantValue == null) return VSConstants.VSITEMID_NIL; if (variantValue is int) return (uint)(int)variantValue; if (variantValue is uint) return (uint)variantValue; if (variantValue is short) return (uint)(short)variantValue; if (variantValue is ushort) return (uint)(ushort)variantValue; if (variantValue is long) return (uint)(long)variantValue; return VSConstants.VSITEMID_NIL; } } } }
using System; using Foundation; using ObjCRuntime; using UserNotifications; namespace Com.OneSignal.iOS { // @interface OSNotificationAction : NSObject [BaseType(typeof(NSObject))] interface OSNotificationAction { // @property (readonly) OSNotificationActionType type; [Export("type")] OSNotificationActionType Type { get; } // @property (readonly) NSString * _Nullable actionId; [NullAllowed, Export("actionId")] string ActionId { get; } } // @interface OSNotification : NSObject [BaseType(typeof(NSObject))] interface OSNotification { // @property (readonly) NSString * _Nullable notificationId; [NullAllowed, Export("notificationId")] string NotificationId { get; } // @property (readonly) NSString * _Nullable templateId; [NullAllowed, Export("templateId")] string TemplateId { get; } // @property (readonly) NSString * _Nullable templateName; [NullAllowed, Export("templateName")] string TemplateName { get; } // @property (readonly) BOOL contentAvailable; [Export("contentAvailable")] bool ContentAvailable { get; } // @property (readonly, getter = hasMutableContent) BOOL mutableContent; [Export("mutableContent")] bool MutableContent { [Bind("hasMutableContent")] get; } // @property (readonly) NSString * _Nullable category; [NullAllowed, Export("category")] string Category { get; } // @property (readonly) NSInteger badge; [Export("badge")] nint Badge { get; } // @property (readonly) NSInteger badgeIncrement; [Export("badgeIncrement")] nint BadgeIncrement { get; } // @property (readonly) NSString * _Nullable sound; [NullAllowed, Export("sound")] string Sound { get; } // @property (readonly) NSString * _Nullable title; [NullAllowed, Export("title")] string Title { get; } // @property (readonly) NSString * _Nullable subtitle; [NullAllowed, Export("subtitle")] string Subtitle { get; } // @property (readonly) NSString * _Nullable body; [NullAllowed, Export("body")] string Body { get; } // @property (readonly) NSString * _Nullable launchURL; [NullAllowed, Export("launchURL")] string LaunchURL { get; } // @property (readonly) NSDictionary * _Nullable additionalData; [NullAllowed, Export("additionalData")] NSDictionary AdditionalData { get; } // @property (readonly) NSDictionary * _Nullable attachments; [NullAllowed, Export("attachments")] NSDictionary Attachments { get; } // @property (readonly) NSArray * _Nullable actionButtons; [NullAllowed, Export("actionButtons")] //[Verify (StronglyTypedNSArray)] NSObject[] ActionButtons { get; } // @property (readonly) NSDictionary * _Nonnull rawPayload; [Export("rawPayload")] NSDictionary RawPayload { get; } // @property (readonly) NSString * _Nullable threadId; [NullAllowed, Export("threadId")] string ThreadId { get; } // @property (readonly) NSNumber * _Nullable relevanceScore; [NullAllowed, Export("relevanceScore")] NSNumber RelevanceScore { get; } // @property (readonly) NSString * interruptionLevel; [Export("interruptionLevel")] string InterruptionLevel { get; } // +(instancetype)parseWithApns:(NSDictionary * _Nonnull)message; [Static] [Export("parseWithApns:")] OSNotification ParseWithApns(NSDictionary message); // -(NSDictionary * _Nonnull)jsonRepresentation; [Export("jsonRepresentation")] NSDictionary JsonRepresentation(); // -(NSString * _Nonnull)stringify; [Export("stringify")] //[Verify (MethodToProperty)] string Stringify(); } // @interface OSNotificationOpenedResult : NSObject [BaseType(typeof(NSObject))] interface OSNotificationOpenedResult { // @property (readonly) OSNotification * _Nonnull notification; [Export("notification")] OSNotification Notification { get; } // @property (readonly) OSNotificationAction * _Nonnull action; [Export("action")] OSNotificationAction Action { get; } // -(NSString * _Nonnull)stringify; [Export("stringify")] //[Verify (MethodToProperty)] string Stringify(); // -(NSDictionary * _Nonnull)jsonRepresentation; [Export("jsonRepresentation")] //[Verify (MethodToProperty)] NSDictionary JsonRepresentation(); } // @interface OSInAppMessage : NSObject [BaseType(typeof(NSObject))] interface OSInAppMessage { // @property (nonatomic, strong) NSString * _Nonnull messageId; [Export("messageId", ArgumentSemantic.Strong)] string MessageId { get; set; } } // @interface OSInAppMessageOutcome : NSObject [BaseType(typeof(NSObject))] interface OSInAppMessageOutcome { // @property (nonatomic, strong) NSString * _Nonnull name; [Export("name", ArgumentSemantic.Strong)] string Name { get; set; } // @property (nonatomic, strong) NSNumber * _Nonnull weight; [Export("weight", ArgumentSemantic.Strong)] NSNumber Weight { get; set; } // @property (nonatomic) BOOL unique; [Export("unique")] bool Unique { get; set; } // -(NSDictionary * _Nonnull)jsonRepresentation; [Export("jsonRepresentation")] //[Verify (MethodToProperty)] NSDictionary JsonRepresentation(); } // @interface OSInAppMessageTag : NSObject [BaseType(typeof(NSObject))] interface OSInAppMessageTag { // @property (nonatomic, strong) NSDictionary * _Nullable tagsToAdd; [NullAllowed, Export("tagsToAdd", ArgumentSemantic.Strong)] NSDictionary TagsToAdd { get; set; } // @property (nonatomic, strong) NSArray * _Nullable tagsToRemove; [NullAllowed, Export("tagsToRemove", ArgumentSemantic.Strong)] //[Verify (StronglyTypedNSArray)] NSObject[] TagsToRemove { get; set; } // -(NSDictionary * _Nonnull)jsonRepresentation; [Export("jsonRepresentation")] //[Verify (MethodToProperty)] NSDictionary JsonRepresentation(); } // @interface OSInAppMessageAction : NSObject [BaseType(typeof(NSObject))] interface OSInAppMessageAction { // @property (nonatomic, strong) NSString * _Nullable clickName; [NullAllowed, Export("clickName", ArgumentSemantic.Strong)] string ClickName { get; set; } // @property (nonatomic, strong) NSURL * _Nullable clickUrl; [NullAllowed, Export("clickUrl", ArgumentSemantic.Strong)] NSUrl ClickUrl { get; set; } // @property (nonatomic, strong) NSString * _Nullable pageId; [NullAllowed, Export("pageId", ArgumentSemantic.Strong)] string PageId { get; set; } // @property (nonatomic) BOOL firstClick; [Export("firstClick")] bool FirstClick { get; set; } // @property (nonatomic) BOOL closesMessage; [Export("closesMessage")] bool ClosesMessage { get; set; } // @property (nonatomic, strong) NSArray<OSInAppMessageOutcome *> * _Nullable outcomes; [NullAllowed, Export("outcomes", ArgumentSemantic.Strong)] OSInAppMessageOutcome[] Outcomes { get; set; } // @property (nonatomic, strong) OSInAppMessageTag * _Nullable tags; [NullAllowed, Export("tags", ArgumentSemantic.Strong)] OSInAppMessageTag Tags { get; set; } // -(NSDictionary * _Nonnull)jsonRepresentation; [Export("jsonRepresentation")] //[Verify (MethodToProperty)] NSDictionary JsonRepresentation(); } // @protocol OSInAppMessageDelegate <NSObject> [Protocol, Model(AutoGeneratedName = true)] [BaseType(typeof(NSObject))] interface OSInAppMessageDelegate { // @optional -(void)handleMessageAction:(OSInAppMessageAction * _Nonnull)action __attribute__((swift_name("handleMessageAction(action:)"))); [Export("handleMessageAction:")] void HandleMessageAction(OSInAppMessageAction action); } // @protocol OSInAppMessageLifecycleHandler <NSObject> /* Check whether adding [Model] to this declaration is appropriate. [Model] is used to generate a C# class that implements this protocol, and might be useful for protocols that consumers are supposed to implement, since consumers can subclass the generated class instead of implementing the generated interface. If consumers are not supposed to implement this protocol, then [Model] is redundant and will generate code that will never be used. */ [Protocol] [Model] [BaseType(typeof(NSObject))] interface OSInAppMessageLifecycleHandler { // @optional -(void)onWillDisplayInAppMessage:(OSInAppMessage *)message; [Export("onWillDisplayInAppMessage:")] void OnWillDisplayInAppMessage(OSInAppMessage message); // @optional -(void)onDidDisplayInAppMessage:(OSInAppMessage *)message; [Export("onDidDisplayInAppMessage:")] void OnDidDisplayInAppMessage(OSInAppMessage message); // @optional -(void)onWillDismissInAppMessage:(OSInAppMessage *)message; [Export("onWillDismissInAppMessage:")] void OnWillDismissInAppMessage(OSInAppMessage message); // @optional -(void)onDidDismissInAppMessage:(OSInAppMessage *)message; [Export("onDidDismissInAppMessage:")] void OnDidDismissInAppMessage(OSInAppMessage message); } // @interface OSOutcomeEvent : NSObject [BaseType(typeof(NSObject))] interface OSOutcomeEvent { // @property (nonatomic) OSInfluenceType session; [Export("session", ArgumentSemantic.Assign)] OSInfluenceType Session { get; set; } // @property (nonatomic, strong) NSArray * _Nullable notificationIds; [NullAllowed, Export("notificationIds", ArgumentSemantic.Strong)] //[Verify (StronglyTypedNSArray)] string[] NotificationIds { get; set; } // @property (nonatomic, strong) NSString * _Nonnull name; [Export("name", ArgumentSemantic.Strong)] string Name { get; set; } // @property (nonatomic, strong) NSNumber * _Nonnull timestamp; [Export("timestamp", ArgumentSemantic.Strong)] NSNumber Timestamp { get; set; } // @property (nonatomic, strong) NSDecimalNumber * _Nonnull weight; [Export("weight", ArgumentSemantic.Strong)] NSDecimalNumber Weight { get; set; } // -(NSDictionary * _Nonnull)jsonRepresentation; [Export("jsonRepresentation")] //[Verify (MethodToProperty)] NSDictionary JsonRepresentation(); } // @interface OSPermissionState : NSObject [BaseType(typeof(NSObject))] interface OSPermissionState { // @property (readonly, nonatomic) BOOL reachable; [Export("reachable")] bool Reachable { get; } // @property (readonly, nonatomic) BOOL hasPrompted; [Export("hasPrompted")] bool HasPrompted { get; } // @property (readonly, nonatomic) BOOL providesAppNotificationSettings; [Export("providesAppNotificationSettings")] bool ProvidesAppNotificationSettings { get; } // @property (readonly, nonatomic) OSNotificationPermission status; [Export("status")] OSNotificationPermission Status { get; } // -(NSDictionary * _Nonnull)toDictionary; [Export("toDictionary")] //[Verify (MethodToProperty)] NSDictionary ToDictionary(); } // @interface OSPermissionStateChanges : NSObject [BaseType(typeof(NSObject))] interface OSPermissionStateChanges { // @property (readonly) OSPermissionState * _Nonnull to; [Export("to")] OSPermissionState To { get; } // @property (readonly) OSPermissionState * _Nonnull from; [Export("from")] OSPermissionState From { get; } // -(NSDictionary * _Nonnull)toDictionary; [Export("toDictionary")] //[Verify (MethodToProperty)] NSDictionary ToDictionary(); } // @interface OSSubscriptionState : NSObject [BaseType(typeof(NSObject))] interface OSSubscriptionState { // @property (readonly, nonatomic) BOOL isSubscribed; [Export("isSubscribed")] bool IsSubscribed { get; } // @property (readonly, nonatomic) BOOL isPushDisabled; [Export("isPushDisabled")] bool IsPushDisabled { get; } // @property (readonly, nonatomic) NSString * _Nullable userId; [NullAllowed, Export("userId")] string UserId { get; } // @property (readonly, nonatomic) NSString * _Nullable pushToken; [NullAllowed, Export("pushToken")] string PushToken { get; } // -(NSDictionary * _Nonnull)toDictionary; [Export("toDictionary")] //[Verify (MethodToProperty)] NSDictionary ToDictionary(); } // @interface OSSubscriptionStateChanges : NSObject [BaseType(typeof(NSObject))] interface OSSubscriptionStateChanges { // @property (readonly) OSSubscriptionState * _Nonnull to; [Export("to")] OSSubscriptionState To { get; } // @property (readonly) OSSubscriptionState * _Nonnull from; [Export("from")] OSSubscriptionState From { get; } // -(NSDictionary * _Nonnull)toDictionary; [Export("toDictionary")] //[Verify (MethodToProperty)] NSDictionary ToDictionary(); } // @interface OSEmailSubscriptionState : NSObject [BaseType(typeof(NSObject))] interface OSEmailSubscriptionState { // @property (readonly, nonatomic) NSString * _Nullable emailUserId; [NullAllowed, Export("emailUserId")] string EmailUserId { get; } // @property (readonly, nonatomic) NSString * _Nullable emailAddress; [NullAllowed, Export("emailAddress")] string EmailAddress { get; } // @property (readonly, nonatomic) BOOL isSubscribed; [Export("isSubscribed")] bool IsSubscribed { get; } // -(NSDictionary * _Nonnull)toDictionary; [Export("toDictionary")] //[Verify (MethodToProperty)] NSDictionary ToDictionary(); } // @interface OSEmailSubscriptionStateChanges : NSObject [BaseType(typeof(NSObject))] interface OSEmailSubscriptionStateChanges { // @property (readonly) OSEmailSubscriptionState * _Nonnull to; [Export("to")] OSEmailSubscriptionState To { get; } // @property (readonly) OSEmailSubscriptionState * _Nonnull from; [Export("from")] OSEmailSubscriptionState From { get; } // -(NSDictionary * _Nonnull)toDictionary; [Export("toDictionary")] //[Verify (MethodToProperty)] NSDictionary ToDictionary(); } // @interface OSSMSSubscriptionState : NSObject [BaseType(typeof(NSObject))] interface OSSMSSubscriptionState { // @property (readonly, nonatomic) NSString * _Nullable smsUserId; [NullAllowed, Export("smsUserId")] string SmsUserId { get; } // @property (readonly, nonatomic) NSString * _Nullable smsNumber; [NullAllowed, Export("smsNumber")] string SmsNumber { get; } // @property (readonly, nonatomic) BOOL isSubscribed; [Export("isSubscribed")] bool IsSubscribed { get; } // -(NSDictionary * _Nonnull)toDictionary; [Export("toDictionary")] //[Verify (MethodToProperty)] NSDictionary ToDictionary(); } // @interface OSSMSSubscriptionStateChanges : NSObject [BaseType(typeof(NSObject))] interface OSSMSSubscriptionStateChanges { // @property (readonly) OSSMSSubscriptionState * _Nonnull to; [Export("to")] OSSMSSubscriptionState To { get; } // @property (readonly) OSSMSSubscriptionState * _Nonnull from; [Export("from")] OSSMSSubscriptionState From { get; } // -(NSDictionary * _Nonnull)toDictionary; [Export("toDictionary")] //[Verify (MethodToProperty)] NSDictionary ToDictionary(); } // @protocol OSPermissionObserver <NSObject> /* Check whether adding [Model] to this declaration is appropriate. [Model] is used to generate a C# class that implements this protocol, and might be useful for protocols that consumers are supposed to implement, since consumers can subclass the generated class instead of implementing the generated interface. If consumers are not supposed to implement this protocol, then [Model] is redundant and will generate code that will never be used. */ [Protocol] [Model] [BaseType(typeof(NSObject))] interface OSPermissionObserver { // @required -(void)onOSPermissionChanged:(OSPermissionStateChanges * _Nonnull)stateChanges; [Abstract] [Export("onOSPermissionChanged:")] void OnOSPermissionChanged(OSPermissionStateChanges stateChanges); } // @protocol OSSubscriptionObserver <NSObject> /* Check whether adding [Model] to this declaration is appropriate. [Model] is used to generate a C# class that implements this protocol, and might be useful for protocols that consumers are supposed to implement, since consumers can subclass the generated class instead of implementing the generated interface. If consumers are not supposed to implement this protocol, then [Model] is redundant and will generate code that will never be used. */ [Protocol] [Model] [BaseType(typeof(NSObject))] interface OSSubscriptionObserver { // @required -(void)onOSSubscriptionChanged:(OSSubscriptionStateChanges * _Nonnull)stateChanges; [Abstract] [Export("onOSSubscriptionChanged:")] void OnOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges); } // @protocol OSEmailSubscriptionObserver <NSObject> /* Check whether adding [Model] to this declaration is appropriate. [Model] is used to generate a C# class that implements this protocol, and might be useful for protocols that consumers are supposed to implement, since consumers can subclass the generated class instead of implementing the generated interface. If consumers are not supposed to implement this protocol, then [Model] is redundant and will generate code that will never be used. */ [Protocol] [Model] [BaseType(typeof(NSObject))] interface OSEmailSubscriptionObserver { // @required -(void)onOSEmailSubscriptionChanged:(OSEmailSubscriptionStateChanges * _Nonnull)stateChanges; [Abstract] [Export("onOSEmailSubscriptionChanged:")] void OnOSEmailSubscriptionChanged(OSEmailSubscriptionStateChanges stateChanges); } // @protocol OSSMSSubscriptionObserver <NSObject> /* Check whether adding [Model] to this declaration is appropriate. [Model] is used to generate a C# class that implements this protocol, and might be useful for protocols that consumers are supposed to implement, since consumers can subclass the generated class instead of implementing the generated interface. If consumers are not supposed to implement this protocol, then [Model] is redundant and will generate code that will never be used. */ [Protocol] [Model] [BaseType(typeof(NSObject))] interface OSSMSSubscriptionObserver { // @required -(void)onOSSMSSubscriptionChanged:(OSSMSSubscriptionStateChanges * _Nonnull)stateChanges; [Abstract] [Export("onOSSMSSubscriptionChanged:")] void OnOSSMSSubscriptionChanged(OSSMSSubscriptionStateChanges stateChanges); } // @interface OSDeviceState : NSObject [BaseType(typeof(NSObject))] interface OSDeviceState { // @property (readonly) BOOL hasNotificationPermission; [Export("hasNotificationPermission")] bool HasNotificationPermission { get; } // @property (readonly) BOOL isPushDisabled; [Export("isPushDisabled")] bool IsPushDisabled { get; } // @property (readonly) BOOL isSubscribed; [Export("isSubscribed")] bool IsSubscribed { get; } // @property (readonly) OSNotificationPermission notificationPermissionStatus; [Export("notificationPermissionStatus")] OSNotificationPermission NotificationPermissionStatus { get; } // @property (readonly) NSString * _Nullable userId; [NullAllowed, Export("userId")] string UserId { get; } // @property (readonly) NSString * _Nullable pushToken; [NullAllowed, Export("pushToken")] string PushToken { get; } // @property (readonly) NSString * _Nullable emailUserId; [NullAllowed, Export("emailUserId")] string EmailUserId { get; } // @property (readonly) NSString * _Nullable emailAddress; [NullAllowed, Export("emailAddress")] string EmailAddress { get; } // @property (readonly) BOOL isEmailSubscribed; [Export("isEmailSubscribed")] bool IsEmailSubscribed { get; } // @property (readonly) NSString * _Nullable smsUserId; [NullAllowed, Export("smsUserId")] string SmsUserId { get; } // @property (readonly) NSString * _Nullable smsNumber; [NullAllowed, Export("smsNumber")] string SmsNumber { get; } // @property (readonly) BOOL isSMSSubscribed; [Export("isSMSSubscribed")] bool IsSMSSubscribed { get; } // -(NSDictionary * _Nonnull)jsonRepresentation; [Export("jsonRepresentation")] //[Verify (MethodToProperty)] NSDictionary JsonRepresentation(); } // typedef void (^OSWebOpenURLResultBlock)(BOOL); delegate void OSWebOpenURLResultBlock(bool arg0); // typedef void (^OSResultSuccessBlock)(NSDictionary *); delegate void OSResultSuccessBlock(NSDictionary arg0); // typedef void (^OSFailureBlock)(NSError *); delegate void OSFailureBlock(NSError arg0); // typedef void (^OSSendOutcomeSuccess)(OSOutcomeEvent *); delegate void OSSendOutcomeSuccess(OSOutcomeEvent arg0); // @interface OneSignal : NSObject [BaseType(typeof(NSObject))] interface OneSignal { // +(NSString *)appId; // +(void)setAppId:(NSString * _Nonnull)newAppId; [Static] [Export("appId")] //[Verify (MethodToProperty)] string AppId { get; set; } // +(NSString * _Nonnull)sdkVersionRaw; [Static] [Export("sdkVersionRaw")] //[Verify (MethodToProperty)] string SdkVersionRaw { get; } // +(NSString * _Nonnull)sdkSemanticVersion; [Static] [Export("sdkSemanticVersion")] //[Verify (MethodToProperty)] string SdkSemanticVersion { get; } // +(void)disablePush:(BOOL)disable; [Static] [Export("disablePush:")] void DisablePush(bool disable); // +(void)setMSDKType:(NSString * _Nonnull)type; [Static] [Export("setMSDKType:")] void SetMSDKType(string type); // +(void)initWithLaunchOptions:(NSDictionary * _Nullable)launchOptions; [Static] [Export("initWithLaunchOptions:")] void InitWithLaunchOptions([NullAllowed] NSDictionary launchOptions); // +(void)setLaunchURLsInApp:(BOOL)launchInApp; [Static] [Export("setLaunchURLsInApp:")] void SetLaunchURLsInApp(bool launchInApp); // +(void)setProvidesNotificationSettingsView:(BOOL)providesView; [Static] [Export("setProvidesNotificationSettingsView:")] void SetProvidesNotificationSettingsView(bool providesView); // +(void)setLogLevel:(ONE_S_LOG_LEVEL)logLevel visualLevel:(ONE_S_LOG_LEVEL)visualLogLevel; [Static] [Export("setLogLevel:visualLevel:")] void SetLogLevel(OneSLogLevel logLevel, OneSLogLevel visualLogLevel); // +(void)onesignalLog:(ONE_S_LOG_LEVEL)logLevel message:(NSString * _Nonnull)message; [Static] [Export("onesignalLog:message:")] void OnesignalLog(OneSLogLevel logLevel, string message); // +(void)promptForPushNotificationsWithUserResponse:(OSUserResponseBlock)block; [Static] [Export("promptForPushNotificationsWithUserResponse:")] void PromptForPushNotificationsWithUserResponse(OSUserResponseBlock block); // +(void)promptForPushNotificationsWithUserResponse:(OSUserResponseBlock)block fallbackToSettings:(BOOL)fallback; [Static] [Export("promptForPushNotificationsWithUserResponse:fallbackToSettings:")] void PromptForPushNotificationsWithUserResponse(OSUserResponseBlock block, bool fallback); // +(void)registerForProvisionalAuthorization:(OSUserResponseBlock)block; [Static] [Export("registerForProvisionalAuthorization:")] void RegisterForProvisionalAuthorization(OSUserResponseBlock block); //+ (void)registerForPushNotifications; [Static] [Export("registerForPushNotifications")] void RegisterForPushNotifications(); // +(OSDeviceState *)getDeviceState; [Static] [Export("getDeviceState")] //[Verify (MethodToProperty)] OSDeviceState DeviceState(); // +(void)consentGranted:(BOOL)granted; [Static] [Export("consentGranted:")] void ConsentGranted(bool granted); // +(void)setRequiresUserPrivacyConsent:(BOOL)required; [Static] [Export("setRequiresUserPrivacyConsent:")] void SetRequiresUserPrivacyConsent(bool required); // +(BOOL)requiresUserPrivacyConsent; [Static] [Export("requiresUserPrivacyConsent")] //[Verify (MethodToProperty)] bool RequiresUserPrivacyConsent(); // +(void)setNotificationWillShowInForegroundHandler:(OSNotificationWillShowInForegroundBlock _Nullable)block; [Static] [Export("setNotificationWillShowInForegroundHandler:")] void SetNotificationWillShowInForegroundHandler([NullAllowed] OSNotificationWillShowInForegroundBlock block); // +(void)setNotificationOpenedHandler:(OSNotificationOpenedBlock _Nullable)block; [Static] [Export("setNotificationOpenedHandler:")] void SetNotificationOpenedHandler([NullAllowed] OSNotificationOpenedBlock block); // +(void)setInAppMessageClickHandler:(OSInAppMessageClickBlock _Nullable)block; [Static] [Export("setInAppMessageClickHandler:")] void SetInAppMessageClickHandler([NullAllowed] OSInAppMessageClickBlock block); // +(void)setInAppMessageLifecycleHandler:(NSObject<OSInAppMessageLifecycleHandler> * _Nullable)delegate; [Static] [Export("setInAppMessageLifecycleHandler:")] void SetInAppMessageLifecycleHandler([NullAllowed] OSInAppMessageLifecycleHandler @delegate); // +(void)postNotification:(NSDictionary * _Nonnull)jsonData; [Static] [Export("postNotification:")] void PostNotification(NSDictionary jsonData); // +(void)postNotification:(NSDictionary * _Nonnull)jsonData onSuccess:(OSResultSuccessBlock _Nullable)successBlock onFailure:(OSFailureBlock _Nullable)failureBlock; [Static] [Export("postNotification:onSuccess:onFailure:")] void PostNotification(NSDictionary jsonData, [NullAllowed] OSResultSuccessBlock successBlock, [NullAllowed] OSFailureBlock failureBlock); // +(void)postNotificationWithJsonString:(NSString * _Nonnull)jsonData onSuccess:(OSResultSuccessBlock _Nullable)successBlock onFailure:(OSFailureBlock _Nullable)failureBlock; [Static] [Export("postNotificationWithJsonString:onSuccess:onFailure:")] void PostNotificationWithJsonString(string jsonData, [NullAllowed] OSResultSuccessBlock successBlock, [NullAllowed] OSFailureBlock failureBlock); // +(void)promptLocation; [Static] [Export("promptLocation")] void PromptLocation(); // +(void)setLocationShared:(BOOL)enable; [Static] [Export("setLocationShared:")] void SetLocationShared(bool enable); // +(BOOL)isLocationShared; [Static] [Export("isLocationShared")] bool IsLocationShared(); // +(UNMutableNotificationContent *)didReceiveNotificationExtensionRequest:(UNNotificationRequest * _Nonnull)request withMutableNotificationContent:(UNMutableNotificationContent * _Nullable)replacementContent __attribute__((deprecated("Please use didReceiveNotificationExtensionRequest:withMutableNotificationContent:withContentHandler: instead."))); [Static] [Export("didReceiveNotificationExtensionRequest:withMutableNotificationContent:")] UNMutableNotificationContent DidReceiveNotificationExtensionRequest(UNNotificationRequest request, [NullAllowed] UNMutableNotificationContent replacementContent); // +(UNMutableNotificationContent *)didReceiveNotificationExtensionRequest:(UNNotificationRequest * _Nonnull)request withMutableNotificationContent:(UNMutableNotificationContent * _Nullable)replacementContent withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler; [Static] [Export("didReceiveNotificationExtensionRequest:withMutableNotificationContent:withContentHandler:")] UNMutableNotificationContent DidReceiveNotificationExtensionRequest(UNNotificationRequest request, [NullAllowed] UNMutableNotificationContent replacementContent, IosContentHandlerBlock contentHandler); // +(UNMutableNotificationContent *)serviceExtensionTimeWillExpireRequest:(UNNotificationRequest * _Nonnull)request withMutableNotificationContent:(UNMutableNotificationContent * _Nullable)replacementContent; [Static] [Export("serviceExtensionTimeWillExpireRequest:withMutableNotificationContent:")] UNMutableNotificationContent ServiceExtensionTimeWillExpireRequest(UNNotificationRequest request, [NullAllowed] UNMutableNotificationContent replacementContent); // +(void)sendTag:(NSString * _Nonnull)key value:(NSString * _Nonnull)value onSuccess:(OSResultSuccessBlock _Nullable)successBlock onFailure:(OSFailureBlock _Nullable)failureBlock; [Static] [Export("sendTag:value:onSuccess:onFailure:")] void SendTag(string key, string value, [NullAllowed] OSResultSuccessBlock successBlock, [NullAllowed] OSFailureBlock failureBlock); // +(void)sendTag:(NSString * _Nonnull)key value:(NSString * _Nonnull)value; [Static] [Export("sendTag:value:")] void SendTag(string key, string value); // +(void)sendTags:(NSDictionary * _Nonnull)keyValuePair onSuccess:(OSResultSuccessBlock _Nullable)successBlock onFailure:(OSFailureBlock _Nullable)failureBlock; [Static] [Export("sendTags:onSuccess:onFailure:")] void SendTags(NSDictionary keyValuePair, [NullAllowed] OSResultSuccessBlock successBlock, [NullAllowed] OSFailureBlock failureBlock); // +(void)sendTags:(NSDictionary * _Nonnull)keyValuePair; [Static] [Export("sendTags:")] void SendTags(NSDictionary keyValuePair); // +(void)sendTagsWithJsonString:(NSString * _Nonnull)jsonString; [Static] [Export("sendTagsWithJsonString:")] void SendTagsWithJsonString(string jsonString); // +(void)getTags:(OSResultSuccessBlock _Nullable)successBlock onFailure:(OSFailureBlock _Nullable)failureBlock; [Static] [Export("getTags:onFailure:")] void GetTags([NullAllowed] OSResultSuccessBlock successBlock, [NullAllowed] OSFailureBlock failureBlock); // +(void)getTags:(OSResultSuccessBlock _Nullable)successBlock; [Static] [Export("getTags:")] void GetTags([NullAllowed] OSResultSuccessBlock successBlock); // +(void)deleteTag:(NSString * _Nonnull)key onSuccess:(OSResultSuccessBlock _Nullable)successBlock onFailure:(OSFailureBlock _Nullable)failureBlock; [Static] [Export("deleteTag:onSuccess:onFailure:")] void DeleteTag(string key, [NullAllowed] OSResultSuccessBlock successBlock, [NullAllowed] OSFailureBlock failureBlock); // +(void)deleteTag:(NSString * _Nonnull)key; [Static] [Export("deleteTag:")] void DeleteTag(string key); // +(void)deleteTags:(NSArray * _Nonnull)keys onSuccess:(OSResultSuccessBlock _Nullable)successBlock onFailure:(OSFailureBlock _Nullable)failureBlock; [Static] [Export("deleteTags:onSuccess:onFailure:")] //[Verify (StronglyTypedNSArray)] void DeleteTags(NSObject[] keys, [NullAllowed] OSResultSuccessBlock successBlock, [NullAllowed] OSFailureBlock failureBlock); // +(void)deleteTags:(NSArray<NSString *> * _Nonnull)keys; [Static] [Export("deleteTags:")] void DeleteTags(string[] keys); // +(void)deleteTagsWithJsonString:(NSString * _Nonnull)jsonString; [Static] [Export("deleteTagsWithJsonString:")] void DeleteTagsWithJsonString(string jsonString); // +(void)addPermissionObserver:(NSObject<OSPermissionObserver> * _Nonnull)observer; [Static] [Export("addPermissionObserver:")] void AddPermissionObserver(OSPermissionObserver observer); // +(void)removePermissionObserver:(NSObject<OSPermissionObserver> * _Nonnull)observer; [Static] [Export("removePermissionObserver:")] void RemovePermissionObserver(OSPermissionObserver observer); // +(void)addSubscriptionObserver:(NSObject<OSSubscriptionObserver> * _Nonnull)observer; [Static] [Export("addSubscriptionObserver:")] void AddSubscriptionObserver(OSSubscriptionObserver observer); // +(void)removeSubscriptionObserver:(NSObject<OSSubscriptionObserver> * _Nonnull)observer; [Static] [Export("removeSubscriptionObserver:")] void RemoveSubscriptionObserver(OSSubscriptionObserver observer); // +(void)addEmailSubscriptionObserver:(NSObject<OSEmailSubscriptionObserver> * _Nonnull)observer; [Static] [Export("addEmailSubscriptionObserver:")] void AddEmailSubscriptionObserver(OSEmailSubscriptionObserver observer); // +(void)removeEmailSubscriptionObserver:(NSObject<OSEmailSubscriptionObserver> * _Nonnull)observer; [Static] [Export("removeEmailSubscriptionObserver:")] void RemoveEmailSubscriptionObserver(OSEmailSubscriptionObserver observer); // +(void)addSMSSubscriptionObserver:(NSObject<OSSMSSubscriptionObserver> * _Nonnull)observer; [Static] [Export("addSMSSubscriptionObserver:")] void AddSMSSubscriptionObserver(OSSMSSubscriptionObserver observer); // +(void)removeSMSSubscriptionObserver:(NSObject<OSSMSSubscriptionObserver> * _Nonnull)observer; [Static] [Export("removeSMSSubscriptionObserver:")] void RemoveSMSSubscriptionObserver(OSSMSSubscriptionObserver observer); // +(void)setEmail:(NSString * _Nonnull)email withEmailAuthHashToken:(NSString * _Nullable)hashToken; [Static] [Export("setEmail:withEmailAuthHashToken:")] void SetEmail(string email, [NullAllowed] string hashToken); // +(void)setEmail:(NSString * _Nonnull)email withEmailAuthHashToken:(NSString * _Nullable)hashToken withSuccess:(OSEmailSuccessBlock _Nullable)successBlock withFailure:(OSEmailFailureBlock _Nullable)failureBlock; [Static] [Export("setEmail:withEmailAuthHashToken:withSuccess:withFailure:")] void SetEmail(string email, [NullAllowed] string hashToken, [NullAllowed] OSEmailSuccessBlock successBlock, [NullAllowed] OSEmailFailureBlock failureBlock); // +(void)setEmail:(NSString * _Nonnull)email; [Static] [Export("setEmail:")] void SetEmail(string email); // +(void)setEmail:(NSString * _Nonnull)email withSuccess:(OSEmailSuccessBlock _Nullable)successBlock withFailure:(OSEmailFailureBlock _Nullable)failureBlock; [Static] [Export("setEmail:withSuccess:withFailure:")] void SetEmail(string email, [NullAllowed] OSEmailSuccessBlock successBlock, [NullAllowed] OSEmailFailureBlock failureBlock); // +(void)logoutEmail; [Static] [Export("logoutEmail")] void LogoutEmail(); // +(void)logoutEmailWithSuccess:(OSEmailSuccessBlock _Nullable)successBlock withFailure:(OSEmailFailureBlock _Nullable)failureBlock; [Static] [Export("logoutEmailWithSuccess:withFailure:")] void LogoutEmailWithSuccess([NullAllowed] OSEmailSuccessBlock successBlock, [NullAllowed] OSEmailFailureBlock failureBlock); // +(void)setSMSNumber:(NSString * _Nonnull)smsNumber withSMSAuthHashToken:(NSString * _Nullable)hashToken; [Static] [Export("setSMSNumber:withSMSAuthHashToken:")] void SetSMSNumber(string smsNumber, [NullAllowed] string hashToken); // +(void)setSMSNumber:(NSString * _Nonnull)smsNumber withSMSAuthHashToken:(NSString * _Nullable)hashToken withSuccess:(OSSMSSuccessBlock _Nullable)successBlock withFailure:(OSSMSFailureBlock _Nullable)failureBlock; [Static] [Export("setSMSNumber:withSMSAuthHashToken:withSuccess:withFailure:")] void SetSMSNumber(string smsNumber, [NullAllowed] string hashToken, [NullAllowed] OSSMSSuccessBlock successBlock, [NullAllowed] OSSMSFailureBlock failureBlock); // +(void)setSMSNumber:(NSString * _Nonnull)smsNumber; [Static] [Export("setSMSNumber:")] void SetSMSNumber(string smsNumber); // +(void)setSMSNumber:(NSString * _Nonnull)smsNumber withSuccess:(OSSMSSuccessBlock _Nullable)successBlock withFailure:(OSSMSFailureBlock _Nullable)failureBlock; [Static] [Export("setSMSNumber:withSuccess:withFailure:")] void SetSMSNumber(string smsNumber, [NullAllowed] OSSMSSuccessBlock successBlock, [NullAllowed] OSSMSFailureBlock failureBlock); // +(void)logoutSMSNumber; [Static] [Export("logoutSMSNumber")] void LogoutSMSNumber(); // +(void)logoutSMSNumberWithSuccess:(OSSMSSuccessBlock _Nullable)successBlock withFailure:(OSSMSFailureBlock _Nullable)failureBlock; [Static] [Export("logoutSMSNumberWithSuccess:withFailure:")] void LogoutSMSNumberWithSuccess([NullAllowed] OSSMSSuccessBlock successBlock, [NullAllowed] OSSMSFailureBlock failureBlock); // +(void)setLanguage:(NSString * _Nonnull)language; [Static] [Export("setLanguage:")] void SetLanguage(string language); // +(void)setLanguage:(NSString * _Nonnull)language withSuccess:(OSUpdateLanguageSuccessBlock _Nullable)successBlock withFailure:(OSUpdateLanguageFailureBlock)failureBlock; [Static] [Export("setLanguage:withSuccess:withFailure:")] void SetLanguage(string language, [NullAllowed] OSUpdateLanguageSuccessBlock successBlock, OSUpdateLanguageFailureBlock failureBlock); // +(void)setExternalUserId:(NSString * _Nonnull)externalId; [Static] [Export("setExternalUserId:")] void SetExternalUserId(string externalId); // +(void)setExternalUserId:(NSString * _Nonnull)externalId withSuccess:(OSUpdateExternalUserIdSuccessBlock _Nullable)successBlock withFailure:(OSUpdateExternalUserIdFailureBlock _Nullable)failureBlock; [Static] [Export("setExternalUserId:withSuccess:withFailure:")] void SetExternalUserId(string externalId, [NullAllowed] OSUpdateExternalUserIdSuccessBlock successBlock, [NullAllowed] OSUpdateExternalUserIdFailureBlock failureBlock); // +(void)setExternalUserId:(NSString *)externalId withExternalIdAuthHashToken:(NSString *)hashToken withSuccess:(OSUpdateExternalUserIdSuccessBlock _Nullable)successBlock withFailure:(OSUpdateExternalUserIdFailureBlock _Nullable)failureBlock; [Static] [Export("setExternalUserId:withExternalIdAuthHashToken:withSuccess:withFailure:")] void SetExternalUserId(string externalId, string hashToken, [NullAllowed] OSUpdateExternalUserIdSuccessBlock successBlock, [NullAllowed] OSUpdateExternalUserIdFailureBlock failureBlock); // +(void)removeExternalUserId; [Static] [Export("removeExternalUserId")] void RemoveExternalUserId(); // +(void)removeExternalUserId:(OSUpdateExternalUserIdSuccessBlock _Nullable)successBlock withFailure:(OSUpdateExternalUserIdFailureBlock _Nullable)failureBlock; [Static] [Export("removeExternalUserId:withFailure:")] void RemoveExternalUserId([NullAllowed] OSUpdateExternalUserIdSuccessBlock successBlock, [NullAllowed] OSUpdateExternalUserIdFailureBlock failureBlock); // +(BOOL)isInAppMessagingPaused; [Static] [Export("isInAppMessagingPaused")] bool IsInAppMessagingPaused(); // +(void)pauseInAppMessages:(BOOL)pause; [Static] [Export("pauseInAppMessages:")] void PauseInAppMessages(bool pause); // +(void)addTrigger:(NSString * _Nonnull)key withValue:(id _Nonnull)value; [Static] [Export("addTrigger:withValue:")] void AddTrigger(string key, NSObject value); // +(void)addTriggers:(NSDictionary<NSString *,id> * _Nonnull)triggers; [Static] [Export("addTriggers:")] void AddTriggers(NSDictionary triggers); // +(void)removeTriggerForKey:(NSString * _Nonnull)key; [Static] [Export("removeTriggerForKey:")] void RemoveTriggerForKey(string key); // +(void)removeTriggersForKeys:(NSArray<NSString *> * _Nonnull)keys; [Static] [Export("removeTriggersForKeys:")] void RemoveTriggersForKeys(string[] keys); // +(NSDictionary<NSString *,id> * _Nonnull)getTriggers; [Static] [Export("getTriggers")] NSDictionary<NSString, NSObject> GetTriggers(); // +(id _Nullable)getTriggerValueForKey:(NSString * _Nonnull)key; [Static] [Export("getTriggerValueForKey:")] [return: NullAllowed] NSObject GetTriggerValueForKey(string key); // +(void)sendOutcome:(NSString * _Nonnull)name; [Static] [Export("sendOutcome:")] void SendOutcome(string name); // +(void)sendOutcome:(NSString * _Nonnull)name onSuccess:(OSSendOutcomeSuccess _Nullable)success; [Static] [Export("sendOutcome:onSuccess:")] void SendOutcome(string name, [NullAllowed] OSSendOutcomeSuccess success); // +(void)sendUniqueOutcome:(NSString * _Nonnull)name; [Static] [Export("sendUniqueOutcome:")] void SendUniqueOutcome(string name); // +(void)sendUniqueOutcome:(NSString * _Nonnull)name onSuccess:(OSSendOutcomeSuccess _Nullable)success; [Static] [Export("sendUniqueOutcome:onSuccess:")] void SendUniqueOutcome(string name, [NullAllowed] OSSendOutcomeSuccess success); // +(void)sendOutcomeWithValue:(NSString * _Nonnull)name value:(NSNumber * _Nonnull)value; [Static] [Export("sendOutcomeWithValue:value:")] void SendOutcomeWithValue(string name, NSNumber value); // +(void)sendOutcomeWithValue:(NSString * _Nonnull)name value:(NSNumber * _Nonnull)value onSuccess:(OSSendOutcomeSuccess _Nullable)success; [Static] [Export("sendOutcomeWithValue:value:onSuccess:")] void SendOutcomeWithValue(string name, NSNumber value, [NullAllowed] OSSendOutcomeSuccess success); } [Static] //[Verify (ConstantsInterfaceAssociation)] partial interface Constants { // extern NSString *const ONESIGNAL_VERSION; [Field("ONESIGNAL_VERSION", "__Internal")] NSString ONESIGNAL_VERSION { get; } } // typedef void (^OSUserResponseBlock)(BOOL); delegate void OSUserResponseBlock(bool arg0); // typedef void (^OSNotificationDisplayResponse)(OSNotification * _Nullable); delegate void OSNotificationDisplayResponse([NullAllowed] OSNotification arg0); // typedef void (^OSNotificationWillShowInForegroundBlock)(OSNotification * _Nonnull, OSNotificationDisplayResponse _Nonnull); delegate void OSNotificationWillShowInForegroundBlock(OSNotification arg0, [BlockCallback] OSNotificationDisplayResponse arg1); // typedef void (^OSNotificationOpenedBlock)(OSNotificationOpenedResult * _Nonnull); delegate void OSNotificationOpenedBlock(OSNotificationOpenedResult arg0); // typedef void (^OSInAppMessageClickBlock)(OSInAppMessageAction * _Nonnull); delegate void OSInAppMessageClickBlock(OSInAppMessageAction arg0); // typedef void (^OSEmailFailureBlock)(NSError *); delegate void OSEmailFailureBlock(NSError arg0); // typedef void (^OSEmailSuccessBlock)(); delegate void OSEmailSuccessBlock(); // typedef void (^OSSMSFailureBlock)(NSError *); delegate void OSSMSFailureBlock(NSError arg0); // typedef void (^OSSMSSuccessBlock)(NSDictionary *); delegate void OSSMSSuccessBlock(NSDictionary arg0); // typedef void (^OSUpdateLanguageFailureBlock)(NSError *); delegate void OSUpdateLanguageFailureBlock(NSError arg0); // typedef void (^OSUpdateLanguageSuccessBlock)(); delegate void OSUpdateLanguageSuccessBlock(); // typedef void (^OSUpdateExternalUserIdFailureBlock)(NSError *); delegate void OSUpdateExternalUserIdFailureBlock(NSError arg0); // typedef void (^OSUpdateExternalUserIdSuccessBlock)(NSDictionary *); delegate void OSUpdateExternalUserIdSuccessBlock(NSDictionary arg0); // typedef (void (^)(UNNotificationContent *_Nonnull))contentHandler delegate void IosContentHandlerBlock(UNNotificationContent arg0); }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Todos.WebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Inflater.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using PdfSharp.SharpZipLib.Checksums; using PdfSharp.SharpZipLib.Zip.Compression.Streams; namespace PdfSharp.SharpZipLib.Zip.Compression { /// <summary> /// Inflater is used to decompress data that has been compressed according /// to the "deflate" standard described in rfc1951. /// /// By default Zlib (rfc1950) headers and footers are expected in the input. /// You can use constructor <code> public Inflater(bool noHeader)</code> passing true /// if there is no Zlib header information /// /// The usage is as following. First you have to set some input with /// <code>SetInput()</code>, then Inflate() it. If inflate doesn't /// inflate any bytes there may be three reasons: /// <ul> /// <li>IsNeedingInput() returns true because the input buffer is empty. /// You have to provide more input with <code>SetInput()</code>. /// NOTE: IsNeedingInput() also returns true when, the stream is finished. /// </li> /// <li>IsNeedingDictionary() returns true, you have to provide a preset /// dictionary with <code>SetDictionary()</code>.</li> /// <li>IsFinished returns true, the inflater has finished.</li> /// </ul> /// Once the first output byte is produced, a dictionary will not be /// needed at a later stage. /// /// Author of the original java version: John Leuner, Jochen Hoenicke /// </summary> internal class Inflater { #region Constants/Readonly /// <summary> /// Copy lengths for literal codes 257..285 /// </summary> static readonly int[] CPLENS = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }; /// <summary> /// Extra bits for literal codes 257..285 /// </summary> static readonly int[] CPLEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; /// <summary> /// Copy offsets for distance codes 0..29 /// </summary> static readonly int[] CPDIST = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; /// <summary> /// Extra bits for distance codes /// </summary> static readonly int[] CPDEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; /// <summary> /// These are the possible states for an inflater /// </summary> const int DECODE_HEADER = 0; const int DECODE_DICT = 1; const int DECODE_BLOCKS = 2; const int DECODE_STORED_LEN1 = 3; const int DECODE_STORED_LEN2 = 4; const int DECODE_STORED = 5; const int DECODE_DYN_HEADER = 6; const int DECODE_HUFFMAN = 7; const int DECODE_HUFFMAN_LENBITS = 8; const int DECODE_HUFFMAN_DIST = 9; const int DECODE_HUFFMAN_DISTBITS = 10; const int DECODE_CHKSUM = 11; const int FINISHED = 12; #endregion #region Instance Fields /// <summary> /// This variable contains the current state. /// </summary> int mode; /// <summary> /// The adler checksum of the dictionary or of the decompressed /// stream, as it is written in the header resp. footer of the /// compressed stream. /// Only valid if mode is DECODE_DICT or DECODE_CHKSUM. /// </summary> int readAdler; /// <summary> /// The number of bits needed to complete the current state. This /// is valid, if mode is DECODE_DICT, DECODE_CHKSUM, /// DECODE_HUFFMAN_LENBITS or DECODE_HUFFMAN_DISTBITS. /// </summary> int neededBits; int repLength; int repDist; int uncomprLen; /// <summary> /// True, if the last block flag was set in the last block of the /// inflated stream. This means that the stream ends after the /// current block. /// </summary> bool isLastBlock; /// <summary> /// The total number of inflated bytes. /// </summary> long totalOut; /// <summary> /// The total number of bytes set with setInput(). This is not the /// value returned by the TotalIn property, since this also includes the /// unprocessed input. /// </summary> long totalIn; /// <summary> /// This variable stores the noHeader flag that was given to the constructor. /// True means, that the inflated stream doesn't contain a Zlib header or /// footer. /// </summary> bool noHeader; StreamManipulator input; OutputWindow outputWindow; InflaterDynHeader dynHeader; InflaterHuffmanTree litlenTree, distTree; Adler32 adler; #endregion #region Constructors /// <summary> /// Creates a new inflater or RFC1951 decompressor /// RFC1950/Zlib headers and footers will be expected in the input data /// </summary> public Inflater() : this(false) { } /// <summary> /// Creates a new inflater. /// </summary> /// <param name="noHeader"> /// True if no RFC1950/Zlib header and footer fields are expected in the input data /// /// This is used for GZIPed/Zipped input. /// /// For compatibility with /// Sun JDK you should provide one byte of input more than needed in /// this case. /// </param> public Inflater(bool noHeader) { this.noHeader = noHeader; this.adler = new Adler32(); input = new StreamManipulator(); outputWindow = new OutputWindow(); mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; } #endregion /// <summary> /// Resets the inflater so that a new stream can be decompressed. All /// pending input and output will be discarded. /// </summary> public void Reset() { mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; totalIn = 0; totalOut = 0; input.Reset(); outputWindow.Reset(); dynHeader = null; litlenTree = null; distTree = null; isLastBlock = false; adler.Reset(); } /// <summary> /// Decodes a zlib/RFC1950 header. /// </summary> /// <returns> /// False if more input is needed. /// </returns> /// <exception cref="SharpZipBaseException"> /// The header is invalid. /// </exception> private bool DecodeHeader() { int header = input.PeekBits(16); if (header < 0) { return false; } input.DropBits(16); // The header is written in "wrong" byte order header = ((header << 8) | (header >> 8)) & 0xffff; if (header % 31 != 0) { throw new SharpZipBaseException("Header checksum illegal"); } if ((header & 0x0f00) != (Deflater.DEFLATED << 8)) { throw new SharpZipBaseException("Compression Method unknown"); } /* Maximum size of the backwards window in bits. * We currently ignore this, but we could use it to make the * inflater window more space efficient. On the other hand the * full window (15 bits) is needed most times, anyway. int max_wbits = ((header & 0x7000) >> 12) + 8; */ if ((header & 0x0020) == 0) { // Dictionary flag? mode = DECODE_BLOCKS; } else { mode = DECODE_DICT; neededBits = 32; } return true; } /// <summary> /// Decodes the dictionary checksum after the deflate header. /// </summary> /// <returns> /// False if more input is needed. /// </returns> private bool DecodeDict() { while (neededBits > 0) { int dictByte = input.PeekBits(8); if (dictByte < 0) { return false; } input.DropBits(8); readAdler = (readAdler << 8) | dictByte; neededBits -= 8; } return false; } /// <summary> /// Decodes the huffman encoded symbols in the input stream. /// </summary> /// <returns> /// false if more input is needed, true if output window is /// full or the current block ends. /// </returns> /// <exception cref="SharpZipBaseException"> /// if deflated stream is invalid. /// </exception> private bool DecodeHuffman() { int free = outputWindow.GetFreeSpace(); while (free >= 258) { int symbol; switch (mode) { case DECODE_HUFFMAN: // This is the inner loop so it is optimized a bit while (((symbol = litlenTree.GetSymbol(input)) & ~0xff) == 0) { outputWindow.Write(symbol); if (--free < 258) { return true; } } if (symbol < 257) { if (symbol < 0) { return false; } else { // symbol == 256: end of block distTree = null; litlenTree = null; mode = DECODE_BLOCKS; return true; } } try { repLength = CPLENS[symbol - 257]; neededBits = CPLEXT[symbol - 257]; } catch (Exception) { throw new SharpZipBaseException("Illegal rep length code"); } goto case DECODE_HUFFMAN_LENBITS; // fall through case DECODE_HUFFMAN_LENBITS: if (neededBits > 0) { mode = DECODE_HUFFMAN_LENBITS; int i = input.PeekBits(neededBits); if (i < 0) { return false; } input.DropBits(neededBits); repLength += i; } mode = DECODE_HUFFMAN_DIST; goto case DECODE_HUFFMAN_DIST; // fall through case DECODE_HUFFMAN_DIST: symbol = distTree.GetSymbol(input); if (symbol < 0) { return false; } try { repDist = CPDIST[symbol]; neededBits = CPDEXT[symbol]; } catch (Exception) { throw new SharpZipBaseException("Illegal rep dist code"); } goto case DECODE_HUFFMAN_DISTBITS; // fall through case DECODE_HUFFMAN_DISTBITS: if (neededBits > 0) { mode = DECODE_HUFFMAN_DISTBITS; int i = input.PeekBits(neededBits); if (i < 0) { return false; } input.DropBits(neededBits); repDist += i; } outputWindow.Repeat(repLength, repDist); free -= repLength; mode = DECODE_HUFFMAN; break; default: throw new SharpZipBaseException("Inflater unknown mode"); } } return true; } /// <summary> /// Decodes the adler checksum after the deflate stream. /// </summary> /// <returns> /// false if more input is needed. /// </returns> /// <exception cref="SharpZipBaseException"> /// If checksum doesn't match. /// </exception> private bool DecodeChksum() { while (neededBits > 0) { int chkByte = input.PeekBits(8); if (chkByte < 0) { return false; } input.DropBits(8); readAdler = (readAdler << 8) | chkByte; neededBits -= 8; } if ((int)adler.Value != readAdler) { throw new SharpZipBaseException("Adler chksum doesn't match: " + (int)adler.Value + " vs. " + readAdler); } mode = FINISHED; return false; } /// <summary> /// Decodes the deflated stream. /// </summary> /// <returns> /// false if more input is needed, or if finished. /// </returns> /// <exception cref="SharpZipBaseException"> /// if deflated stream is invalid. /// </exception> private bool Decode() { switch (mode) { case DECODE_HEADER: return DecodeHeader(); case DECODE_DICT: return DecodeDict(); case DECODE_CHKSUM: return DecodeChksum(); case DECODE_BLOCKS: if (isLastBlock) { if (noHeader) { mode = FINISHED; return false; } else { input.SkipToByteBoundary(); neededBits = 32; mode = DECODE_CHKSUM; return true; } } int type = input.PeekBits(3); if (type < 0) { return false; } input.DropBits(3); if ((type & 1) != 0) { isLastBlock = true; } switch (type >> 1) { case DeflaterConstants.STORED_BLOCK: input.SkipToByteBoundary(); mode = DECODE_STORED_LEN1; break; case DeflaterConstants.STATIC_TREES: litlenTree = InflaterHuffmanTree.defLitLenTree; distTree = InflaterHuffmanTree.defDistTree; mode = DECODE_HUFFMAN; break; case DeflaterConstants.DYN_TREES: dynHeader = new InflaterDynHeader(); mode = DECODE_DYN_HEADER; break; default: throw new SharpZipBaseException("Unknown block type " + type); } return true; case DECODE_STORED_LEN1: { if ((uncomprLen = input.PeekBits(16)) < 0) { return false; } input.DropBits(16); mode = DECODE_STORED_LEN2; } goto case DECODE_STORED_LEN2; // fall through case DECODE_STORED_LEN2: { int nlen = input.PeekBits(16); if (nlen < 0) { return false; } input.DropBits(16); if (nlen != (uncomprLen ^ 0xffff)) { throw new SharpZipBaseException("broken uncompressed block"); } mode = DECODE_STORED; } goto case DECODE_STORED; // fall through case DECODE_STORED: { int more = outputWindow.CopyStored(input, uncomprLen); uncomprLen -= more; if (uncomprLen == 0) { mode = DECODE_BLOCKS; return true; } return !input.IsNeedingInput; } case DECODE_DYN_HEADER: if (!dynHeader.Decode(input)) { return false; } litlenTree = dynHeader.BuildLitLenTree(); distTree = dynHeader.BuildDistTree(); mode = DECODE_HUFFMAN; goto case DECODE_HUFFMAN; // fall through case DECODE_HUFFMAN: case DECODE_HUFFMAN_LENBITS: case DECODE_HUFFMAN_DIST: case DECODE_HUFFMAN_DISTBITS: return DecodeHuffman(); case FINISHED: return false; default: throw new SharpZipBaseException("Inflater.Decode unknown mode"); } } /// <summary> /// Sets the preset dictionary. This should only be called, if /// needsDictionary() returns true and it should set the same /// dictionary, that was used for deflating. The getAdler() /// function returns the checksum of the dictionary needed. /// </summary> /// <param name="buffer"> /// The dictionary. /// </param> public void SetDictionary(byte[] buffer) { SetDictionary(buffer, 0, buffer.Length); } /// <summary> /// Sets the preset dictionary. This should only be called, if /// needsDictionary() returns true and it should set the same /// dictionary, that was used for deflating. The getAdler() /// function returns the checksum of the dictionary needed. /// </summary> /// <param name="buffer"> /// The dictionary. /// </param> /// <param name="index"> /// The index into buffer where the dictionary starts. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// No dictionary is needed. /// </exception> /// <exception cref="SharpZipBaseException"> /// The adler checksum for the buffer is invalid /// </exception> public void SetDictionary(byte[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (!IsNeedingDictionary) { throw new InvalidOperationException("Dictionary is not needed"); } adler.Update(buffer, index, count); if ((int)adler.Value != readAdler) { throw new SharpZipBaseException("Wrong adler checksum"); } adler.Reset(); outputWindow.CopyDict(buffer, index, count); mode = DECODE_BLOCKS; } /// <summary> /// Sets the input. This should only be called, if needsInput() /// returns true. /// </summary> /// <param name="buffer"> /// the input. /// </param> public void SetInput(byte[] buffer) { SetInput(buffer, 0, buffer.Length); } /// <summary> /// Sets the input. This should only be called, if needsInput() /// returns true. /// </summary> /// <param name="buffer"> /// The source of input data /// </param> /// <param name="index"> /// The index into buffer where the input starts. /// </param> /// <param name="count"> /// The number of bytes of input to use. /// </param> /// <exception cref="System.InvalidOperationException"> /// No input is needed. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// The index and/or count are wrong. /// </exception> public void SetInput(byte[] buffer, int index, int count) { input.SetInput(buffer, index, count); totalIn += (long)count; } /// <summary> /// Inflates the compressed stream to the output buffer. If this /// returns 0, you should check, whether IsNeedingDictionary(), /// IsNeedingInput() or IsFinished() returns true, to determine why no /// further output is produced. /// </summary> /// <param name="buffer"> /// the output buffer. /// </param> /// <returns> /// The number of bytes written to the buffer, 0 if no further /// output can be produced. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// if buffer has length 0. /// </exception> /// <exception cref="System.FormatException"> /// if deflated stream is invalid. /// </exception> public int Inflate(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } return Inflate(buffer, 0, buffer.Length); } /// <summary> /// Inflates the compressed stream to the output buffer. If this /// returns 0, you should check, whether needsDictionary(), /// needsInput() or finished() returns true, to determine why no /// further output is produced. /// </summary> /// <param name="buffer"> /// the output buffer. /// </param> /// <param name="offset"> /// the offset in buffer where storing starts. /// </param> /// <param name="count"> /// the maximum number of bytes to output. /// </param> /// <returns> /// the number of bytes written to the buffer, 0 if no further output can be produced. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// if count is less than 0. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// if the index and / or count are wrong. /// </exception> /// <exception cref="System.FormatException"> /// if deflated stream is invalid. /// </exception> public int Inflate(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "count cannot be negative"); #endif } if (offset < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "offset cannot be negative"); #endif } if (offset + count > buffer.Length) { throw new ArgumentException("count exceeds buffer bounds"); } // Special case: count may be zero if (count == 0) { if (!IsFinished) { // -jr- 08-Nov-2003 INFLATE_BUG fix.. Decode(); } return 0; } int bytesCopied = 0; do { if (mode != DECODE_CHKSUM) { /* Don't give away any output, if we are waiting for the * checksum in the input stream. * * With this trick we have always: * IsNeedingInput() and not IsFinished() * implies more output can be produced. */ int more = outputWindow.CopyOutput(buffer, offset, count); if (more > 0) { adler.Update(buffer, offset, more); offset += more; bytesCopied += more; totalOut += (long)more; count -= more; if (count == 0) { return bytesCopied; } } } } while (Decode() || ((outputWindow.GetAvailable() > 0) && (mode != DECODE_CHKSUM))); return bytesCopied; } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method also returns true when the stream is finished. /// </summary> public bool IsNeedingInput { get { return input.IsNeedingInput; } } /// <summary> /// Returns true, if a preset dictionary is needed to inflate the input. /// </summary> public bool IsNeedingDictionary { get { return mode == DECODE_DICT && neededBits == 0; } } /// <summary> /// Returns true, if the inflater has finished. This means, that no /// input is needed and no output can be produced. /// </summary> public bool IsFinished { get { return mode == FINISHED && outputWindow.GetAvailable() == 0; } } /// <summary> /// Gets the adler checksum. This is either the checksum of all /// uncompressed bytes returned by inflate(), or if needsDictionary() /// returns true (and thus no output was yet produced) this is the /// adler checksum of the expected dictionary. /// </summary> /// <returns> /// the adler checksum. /// </returns> public int Adler { get { return IsNeedingDictionary ? readAdler : (int)adler.Value; } } /// <summary> /// Gets the total number of output bytes returned by Inflate(). /// </summary> /// <returns> /// the total number of output bytes. /// </returns> public long TotalOut { get { return totalOut; } } /// <summary> /// Gets the total number of processed compressed input bytes. /// </summary> /// <returns> /// The total number of bytes of processed input bytes. /// </returns> public long TotalIn { get { return totalIn - (long)RemainingInput; } } /// <summary> /// Gets the number of unprocessed input bytes. Useful, if the end of the /// stream is reached and you want to further process the bytes after /// the deflate stream. /// </summary> /// <returns> /// The number of bytes of the input which have not been processed. /// </returns> public int RemainingInput { // TODO: This should be a long? get { return input.AvailableBytes; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/proto/grpc/testing/metrics.proto // Original file comments: // Copyright 2015-2016, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Contains the definitions for a metrics service and the type of metrics // exposed by the service. // // Currently, 'Gauge' (i.e a metric that represents the measured value of // something at an instant of time) is the only metric type supported by the // service. #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Grpc.Testing { public static class MetricsService { static readonly string __ServiceName = "grpc.testing.MetricsService"; static readonly Marshaller<global::Grpc.Testing.EmptyMessage> __Marshaller_EmptyMessage = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.EmptyMessage.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.GaugeResponse> __Marshaller_GaugeResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.GaugeResponse.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.GaugeRequest> __Marshaller_GaugeRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.GaugeRequest.Parser.ParseFrom); static readonly Method<global::Grpc.Testing.EmptyMessage, global::Grpc.Testing.GaugeResponse> __Method_GetAllGauges = new Method<global::Grpc.Testing.EmptyMessage, global::Grpc.Testing.GaugeResponse>( MethodType.ServerStreaming, __ServiceName, "GetAllGauges", __Marshaller_EmptyMessage, __Marshaller_GaugeResponse); static readonly Method<global::Grpc.Testing.GaugeRequest, global::Grpc.Testing.GaugeResponse> __Method_GetGauge = new Method<global::Grpc.Testing.GaugeRequest, global::Grpc.Testing.GaugeResponse>( MethodType.Unary, __ServiceName, "GetGauge", __Marshaller_GaugeRequest, __Marshaller_GaugeResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.MetricsReflection.Descriptor.Services[0]; } } /// <summary>Client for MetricsService</summary> [System.Obsolete("Client side interfaced will be removed in the next release. Use client class directly.")] public interface IMetricsServiceClient { /// <summary> /// Returns the values of all the gauges that are currently being maintained by /// the service /// </summary> AsyncServerStreamingCall<global::Grpc.Testing.GaugeResponse> GetAllGauges(global::Grpc.Testing.EmptyMessage request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the values of all the gauges that are currently being maintained by /// the service /// </summary> AsyncServerStreamingCall<global::Grpc.Testing.GaugeResponse> GetAllGauges(global::Grpc.Testing.EmptyMessage request, CallOptions options); /// <summary> /// Returns the value of one gauge /// </summary> global::Grpc.Testing.GaugeResponse GetGauge(global::Grpc.Testing.GaugeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the value of one gauge /// </summary> global::Grpc.Testing.GaugeResponse GetGauge(global::Grpc.Testing.GaugeRequest request, CallOptions options); /// <summary> /// Returns the value of one gauge /// </summary> AsyncUnaryCall<global::Grpc.Testing.GaugeResponse> GetGaugeAsync(global::Grpc.Testing.GaugeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the value of one gauge /// </summary> AsyncUnaryCall<global::Grpc.Testing.GaugeResponse> GetGaugeAsync(global::Grpc.Testing.GaugeRequest request, CallOptions options); } /// <summary>Interface of server-side implementations of MetricsService</summary> [System.Obsolete("Service implementations should inherit from the generated abstract base class instead.")] public interface IMetricsService { /// <summary> /// Returns the values of all the gauges that are currently being maintained by /// the service /// </summary> global::System.Threading.Tasks.Task GetAllGauges(global::Grpc.Testing.EmptyMessage request, IServerStreamWriter<global::Grpc.Testing.GaugeResponse> responseStream, ServerCallContext context); /// <summary> /// Returns the value of one gauge /// </summary> global::System.Threading.Tasks.Task<global::Grpc.Testing.GaugeResponse> GetGauge(global::Grpc.Testing.GaugeRequest request, ServerCallContext context); } /// <summary>Base class for server-side implementations of MetricsService</summary> public abstract class MetricsServiceBase { /// <summary> /// Returns the values of all the gauges that are currently being maintained by /// the service /// </summary> public virtual global::System.Threading.Tasks.Task GetAllGauges(global::Grpc.Testing.EmptyMessage request, IServerStreamWriter<global::Grpc.Testing.GaugeResponse> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Returns the value of one gauge /// </summary> public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.GaugeResponse> GetGauge(global::Grpc.Testing.GaugeRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for MetricsService</summary> #pragma warning disable 0618 public class MetricsServiceClient : ClientBase<MetricsServiceClient>, IMetricsServiceClient #pragma warning restore 0618 { public MetricsServiceClient(Channel channel) : base(channel) { } public MetricsServiceClient(CallInvoker callInvoker) : base(callInvoker) { } ///<summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected MetricsServiceClient() : base() { } ///<summary>Protected constructor to allow creation of configured clients.</summary> protected MetricsServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Returns the values of all the gauges that are currently being maintained by /// the service /// </summary> public virtual AsyncServerStreamingCall<global::Grpc.Testing.GaugeResponse> GetAllGauges(global::Grpc.Testing.EmptyMessage request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetAllGauges(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the values of all the gauges that are currently being maintained by /// the service /// </summary> public virtual AsyncServerStreamingCall<global::Grpc.Testing.GaugeResponse> GetAllGauges(global::Grpc.Testing.EmptyMessage request, CallOptions options) { return CallInvoker.AsyncServerStreamingCall(__Method_GetAllGauges, null, options, request); } /// <summary> /// Returns the value of one gauge /// </summary> public virtual global::Grpc.Testing.GaugeResponse GetGauge(global::Grpc.Testing.GaugeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetGauge(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the value of one gauge /// </summary> public virtual global::Grpc.Testing.GaugeResponse GetGauge(global::Grpc.Testing.GaugeRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetGauge, null, options, request); } /// <summary> /// Returns the value of one gauge /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.GaugeResponse> GetGaugeAsync(global::Grpc.Testing.GaugeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetGaugeAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the value of one gauge /// </summary> public virtual AsyncUnaryCall<global::Grpc.Testing.GaugeResponse> GetGaugeAsync(global::Grpc.Testing.GaugeRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetGauge, null, options, request); } protected override MetricsServiceClient NewInstance(ClientBaseConfiguration configuration) { return new MetricsServiceClient(configuration); } } /// <summary>Creates a new client for MetricsService</summary> public static MetricsServiceClient NewClient(Channel channel) { return new MetricsServiceClient(channel); } /// <summary>Creates service definition that can be registered with a server</summary> #pragma warning disable 0618 public static ServerServiceDefinition BindService(IMetricsService serviceImpl) #pragma warning restore 0618 { return ServerServiceDefinition.CreateBuilder(__ServiceName) .AddMethod(__Method_GetAllGauges, serviceImpl.GetAllGauges) .AddMethod(__Method_GetGauge, serviceImpl.GetGauge).Build(); } /// <summary>Creates service definition that can be registered with a server</summary> #pragma warning disable 0618 public static ServerServiceDefinition BindService(MetricsServiceBase serviceImpl) #pragma warning restore 0618 { return ServerServiceDefinition.CreateBuilder(__ServiceName) .AddMethod(__Method_GetAllGauges, serviceImpl.GetAllGauges) .AddMethod(__Method_GetGauge, serviceImpl.GetGauge).Build(); } } } #endregion
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection.Metadata; using Internal.TypeSystem.Ecma; namespace Internal.TypeSystem.TypesDebugInfo { public class UserDefinedTypeDescriptor { public UserDefinedTypeDescriptor(ITypesDebugInfoWriter objectWriter) { _objectWriter = objectWriter; } public uint GetVariableTypeIndex(TypeDesc type, bool needsCompleteIndex) { uint typeIndex = 0; if (type.IsPrimitive) { typeIndex = PrimitiveTypeDescriptor.GetPrimitiveTypeIndex(type); } else { typeIndex = GetTypeIndex(type, needsCompleteIndex); } return typeIndex; } public uint GetTypeIndex(TypeDesc type, bool needsCompleteType) { uint variableTypeIndex = 0; if (needsCompleteType ? _completeKnownTypes.TryGetValue(type, out variableTypeIndex) : _knownTypes.TryGetValue(type, out variableTypeIndex)) { return variableTypeIndex; } else { return GetNewTypeIndex(type, needsCompleteType); } } private uint GetNewTypeIndex(TypeDesc type, bool needsCompleteType) { if (type.IsEnum) { return GetEnumTypeIndex(type); } else if (type.IsArray) { return GetArrayTypeIndex(type); } else if (type.IsDefType) { return GetClassTypeIndex(type, needsCompleteType); } return 0; } public uint GetEnumTypeIndex(TypeDesc type) { System.Diagnostics.Debug.Assert(type.IsEnum, "GetEnumTypeIndex was called with wrong type"); DefType defType = type as DefType; System.Diagnostics.Debug.Assert(defType != null, "GetEnumTypeIndex was called with non def type"); List<FieldDesc> fieldsDescriptors = new List<FieldDesc>(); foreach (var field in defType.GetFields()) { if (field.IsLiteral) { fieldsDescriptors.Add(field); } } EnumTypeDescriptor enumTypeDescriptor = new EnumTypeDescriptor { ElementCount = (ulong)fieldsDescriptors.Count, ElementType = PrimitiveTypeDescriptor.GetPrimitiveTypeIndex(defType.UnderlyingType), Name = _objectWriter.GetMangledName(type), UniqueName = defType.GetFullName() }; EnumRecordTypeDescriptor[] typeRecords = new EnumRecordTypeDescriptor[enumTypeDescriptor.ElementCount]; for (int i = 0; i < fieldsDescriptors.Count; ++i) { FieldDesc field = fieldsDescriptors[i]; EnumRecordTypeDescriptor recordTypeDescriptor; recordTypeDescriptor.Value = GetEnumRecordValue(field); recordTypeDescriptor.Name = field.Name; typeRecords[i] = recordTypeDescriptor; } uint typeIndex = _objectWriter.GetEnumTypeIndex(enumTypeDescriptor, typeRecords); _knownTypes[type] = typeIndex; _completeKnownTypes[type] = typeIndex; return typeIndex; } public uint GetArrayTypeIndex(TypeDesc type) { System.Diagnostics.Debug.Assert(type.IsArray, "GetArrayTypeIndex was called with wrong type"); ArrayType arrayType = (ArrayType)type; ArrayTypeDescriptor arrayTypeDescriptor = new ArrayTypeDescriptor { Rank = (uint)arrayType.Rank, ElementType = GetVariableTypeIndex(arrayType.ElementType, false), Size = (uint)arrayType.GetElementSize().AsInt, IsMultiDimensional = arrayType.IsMdArray ? 1 : 0 }; ClassTypeDescriptor classDescriptor = new ClassTypeDescriptor { IsStruct = 0, Name = _objectWriter.GetMangledName(type), BaseClassId = GetVariableTypeIndex(arrayType.BaseType, false) }; uint typeIndex = _objectWriter.GetArrayTypeIndex(classDescriptor, arrayTypeDescriptor); _knownTypes[type] = typeIndex; _completeKnownTypes[type] = typeIndex; return typeIndex; } public ulong GetEnumRecordValue(FieldDesc field) { var ecmaField = field as EcmaField; if (ecmaField != null) { MetadataReader reader = ecmaField.MetadataReader; FieldDefinition fieldDef = reader.GetFieldDefinition(ecmaField.Handle); ConstantHandle defaultValueHandle = fieldDef.GetDefaultValue(); if (!defaultValueHandle.IsNil) { return HandleConstant(ecmaField.Module, defaultValueHandle); } } return 0; } private ulong HandleConstant(EcmaModule module, ConstantHandle constantHandle) { MetadataReader reader = module.MetadataReader; Constant constant = reader.GetConstant(constantHandle); BlobReader blob = reader.GetBlobReader(constant.Value); switch (constant.TypeCode) { case ConstantTypeCode.Byte: return (ulong)blob.ReadByte(); case ConstantTypeCode.Int16: return (ulong)blob.ReadInt16(); case ConstantTypeCode.Int32: return (ulong)blob.ReadInt32(); case ConstantTypeCode.Int64: return (ulong)blob.ReadInt64(); case ConstantTypeCode.SByte: return (ulong)blob.ReadSByte(); case ConstantTypeCode.UInt16: return (ulong)blob.ReadUInt16(); case ConstantTypeCode.UInt32: return (ulong)blob.ReadUInt32(); case ConstantTypeCode.UInt64: return (ulong)blob.ReadUInt64(); } System.Diagnostics.Debug.Assert(false); return 0; } public uint GetClassTypeIndex(TypeDesc type, bool needsCompleteType) { DefType defType = type as DefType; System.Diagnostics.Debug.Assert(defType != null, "GetClassTypeIndex was called with non def type"); ClassTypeDescriptor classTypeDescriptor = new ClassTypeDescriptor { IsStruct = type.IsValueType ? 1 : 0, Name = _objectWriter.GetMangledName(type), UniqueName = defType.GetFullName(), BaseClassId = 0 }; uint typeIndex = _objectWriter.GetClassTypeIndex(classTypeDescriptor); _knownTypes[type] = typeIndex; if (type.HasBaseType && !type.IsValueType) { classTypeDescriptor.BaseClassId = GetVariableTypeIndex(defType.BaseType, false); } List<DataFieldDescriptor> fieldsDescs = new List<DataFieldDescriptor>(); foreach (var fieldDesc in defType.GetFields()) { if (fieldDesc.HasRva || fieldDesc.IsLiteral) continue; DataFieldDescriptor field = new DataFieldDescriptor { FieldTypeIndex = GetVariableTypeIndex(fieldDesc.FieldType, false), Offset = (ulong)fieldDesc.Offset.AsInt, Name = fieldDesc.Name }; fieldsDescs.Add(field); } DataFieldDescriptor[] fields = new DataFieldDescriptor[fieldsDescs.Count]; for (int i = 0; i < fieldsDescs.Count; ++i) { fields[i] = fieldsDescs[i]; } ClassFieldsTypeDescriptor fieldsDescriptor = new ClassFieldsTypeDescriptor { Size = (ulong)defType.GetElementSize().AsInt, FieldsCount = fieldsDescs.Count }; uint completeTypeIndex = _objectWriter.GetCompleteClassTypeIndex(classTypeDescriptor, fieldsDescriptor, fields); _completeKnownTypes[type] = completeTypeIndex; if (needsCompleteType) return completeTypeIndex; else return typeIndex; } private ITypesDebugInfoWriter _objectWriter; private Dictionary<TypeDesc, uint> _knownTypes = new Dictionary<TypeDesc, uint>(); private Dictionary<TypeDesc, uint> _completeKnownTypes = new Dictionary<TypeDesc, uint>(); } }
using System; using System.Collections.Generic; using System.Globalization; namespace Irony.Parsing { #region notes //Identifier terminal. Matches alpha-numeric sequences that usually represent identifiers and keywords. // c#: @ prefix signals to not interpret as a keyword; allows \u escapes // #endregion [Flags] public enum IdOptions : short { None = 0, AllowsEscapes = 0x01, CanStartWithEscape = 0x03, IsNotKeyword = 0x10, NameIncludesPrefix = 0x20 } public enum CaseRestriction { None, FirstUpper, FirstLower, AllUpper, AllLower } public class UnicodeCategoryList : List<UnicodeCategory> { } public class IdentifierTerminal : CompoundTerminalBase { //Id flags for internal use internal enum IdFlagsInternal : short { HasEscapes = 0x100 } #region constructors and initialization public IdentifierTerminal(string name) : this(name, IdOptions.None) { } public IdentifierTerminal(string name, IdOptions options) : this(name, "_", "_") { Options = options; } public IdentifierTerminal(string name, string extraChars, string extraFirstChars = "") : base(name) { AllFirstChars = Strings.AllLatinLetters + extraFirstChars; AllChars = Strings.AllLatinLetters + Strings.DecimalDigits + extraChars; } public void AddPrefix(string prefix, IdOptions options) { AddPrefixFlag(prefix, (short) options); } #endregion #region properties: AllChars, AllFirstChars private CharHashSet _allCharsSet; private CharHashSet _allFirstCharsSet; public string AllFirstChars; public string AllChars; public TokenEditorInfo KeywordEditorInfo = new TokenEditorInfo(TokenType.Keyword, TokenColor.Keyword, TokenTriggers.None); public IdOptions Options; //flags for the case when there are no prefixes public CaseRestriction CaseRestriction; public readonly UnicodeCategoryList StartCharCategories = new UnicodeCategoryList(); //categories of first char public readonly UnicodeCategoryList CharCategories = new UnicodeCategoryList(); //categories of all other chars public readonly UnicodeCategoryList CharsToRemoveCategories = new UnicodeCategoryList(); //categories of chars to remove from final id, usually formatting category #endregion #region overrides public override void Init(GrammarData grammarData) { base.Init(grammarData); _allCharsSet = new CharHashSet(Grammar.CaseSensitive); _allCharsSet.UnionWith(AllChars.ToCharArray()); //Adjust case restriction. We adjust only first chars; if first char is ok, we will scan the rest without restriction // and then check casing for entire identifier switch (CaseRestriction) { case CaseRestriction.AllLower: case CaseRestriction.FirstLower: _allFirstCharsSet = new CharHashSet(true); _allFirstCharsSet.UnionWith(AllFirstChars.ToLowerInvariant().ToCharArray()); break; case CaseRestriction.AllUpper: case CaseRestriction.FirstUpper: _allFirstCharsSet = new CharHashSet(true); _allFirstCharsSet.UnionWith(AllFirstChars.ToUpperInvariant().ToCharArray()); break; default: //None _allFirstCharsSet = new CharHashSet(Grammar.CaseSensitive); _allFirstCharsSet.UnionWith(AllFirstChars.ToCharArray()); break; } //if there are "first" chars defined by categories, add the terminal to FallbackTerminals if (StartCharCategories.Count > 0) grammarData.NoPrefixTerminals.Add(this); if (EditorInfo == null) EditorInfo = new TokenEditorInfo(TokenType.Identifier, TokenColor.Identifier, TokenTriggers.None); } public override IList<string> GetFirsts() { // new scanner: identifier has no prefixes return null; /* var list = new StringList(); list.AddRange(Prefixes); foreach (char ch in _allFirstCharsSet) list.Add(ch.ToString()); if ((Options & IdOptions.CanStartWithEscape) != 0) list.Add(this.EscapeChar.ToString()); return list; */ } protected override void InitDetails(ParsingContext context, CompoundTokenDetails details) { base.InitDetails(context, details); details.Flags = (short) Options; } //Override to assign IsKeyword flag to keyword tokens protected override Token CreateToken(ParsingContext context, ISourceStream source, CompoundTokenDetails details) { var token = base.CreateToken(context, source, details); if (details.IsSet((short) IdOptions.IsNotKeyword)) return token; //check if it is keyword CheckReservedWord(token); return token; } private void CheckReservedWord(Token token) { KeyTerm keyTerm; if (Grammar.KeyTerms.TryGetValue(token.Text, out keyTerm)) { token.KeyTerm = keyTerm; //if it is reserved word, then overwrite terminal if (keyTerm.Flags.IsSet(TermFlags.IsReservedWord)) token.SetTerminal(keyTerm); } } protected override Token QuickParse(ParsingContext context, ISourceStream source) { if (!_allFirstCharsSet.Contains(source.PreviewChar)) return null; source.PreviewPosition++; while (_allCharsSet.Contains(source.PreviewChar) && !source.EOF()) source.PreviewPosition++; //if it is not a terminator then cancel; we need to go through full algorithm if (!Grammar.IsWhitespaceOrDelimiter(source.PreviewChar)) return null; var token = source.CreateToken(OutputTerminal); if (CaseRestriction != CaseRestriction.None && !CheckCaseRestriction(token.ValueString)) return null; //!!! Do not convert to common case (all-lower) for case-insensitive grammar. Let identifiers remain as is, // it is responsibility of interpreter to provide case-insensitive read/write operations for identifiers // if (!this.GrammarData.Grammar.CaseSensitive) // token.Value = token.Text.ToLower(CultureInfo.InvariantCulture); CheckReservedWord(token); return token; } protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) { var start = source.PreviewPosition; var allowEscapes = details.IsSet((short) IdOptions.AllowsEscapes); var outputChars = new CharList(); while (!source.EOF()) { var current = source.PreviewChar; if (Grammar.IsWhitespaceOrDelimiter(current)) break; if (allowEscapes && current == EscapeChar) { current = ReadUnicodeEscape(source, details); //We need to back off the position. ReadUnicodeEscape sets the position to symbol right after escape digits. //This is the char that we should process in next iteration, so we must backup one char, to pretend the escaped // char is at position of last digit of escape sequence. source.PreviewPosition--; if (details.Error != null) return false; } //Check if current character is OK if (!CharOk(current, source.PreviewPosition == start)) break; //Check if we need to skip this char var currCat = CharUnicodeInfo.GetUnicodeCategory(current); //I know, it suxx, we do it twice, fix it later if (!CharsToRemoveCategories.Contains(currCat)) outputChars.Add(current); //add it to output (identifier) source.PreviewPosition++; } //while if (outputChars.Count == 0) return false; //Convert collected chars to string details.Body = new string(outputChars.ToArray()); if (!CheckCaseRestriction(details.Body)) return false; return !string.IsNullOrEmpty(details.Body); } private bool CharOk(char ch, bool first) { //first check char lists, then categories var charSet = first ? _allFirstCharsSet : _allCharsSet; if (charSet.Contains(ch)) return true; //check categories if (CharCategories.Count > 0) { var chCat = CharUnicodeInfo.GetUnicodeCategory(ch); var catList = first ? StartCharCategories : CharCategories; if (catList.Contains(chCat)) return true; } return false; } private bool CheckCaseRestriction(string body) { switch (CaseRestriction) { case CaseRestriction.FirstLower: return char.IsLower(body, 0); case CaseRestriction.FirstUpper: return char.IsUpper(body, 0); case CaseRestriction.AllLower: return body.ToLower() == body; case CaseRestriction.AllUpper: return body.ToUpper() == body; default: return true; } } //method private char ReadUnicodeEscape(ISourceStream source, CompoundTokenDetails details) { //Position is currently at "\" symbol source.PreviewPosition++; //move to U/u char int len; switch (source.PreviewChar) { case 'u': len = 4; break; case 'U': len = 8; break; default: details.Error = Resources.ErrInvEscSymbol; // "Invalid escape symbol, expected 'u' or 'U' only." return '\0'; } if (source.PreviewPosition + len > source.Text.Length) { details.Error = Resources.ErrInvEscSeq; // "Invalid escape sequence"; return '\0'; } source.PreviewPosition++; //move to the first digit var digits = source.Text.Substring(source.PreviewPosition, len); var result = (char) Convert.ToUInt32(digits, 16); source.PreviewPosition += len; details.Flags |= (int) IdFlagsInternal.HasEscapes; return result; } protected override bool ConvertValue(CompoundTokenDetails details) { if (details.IsSet((short) IdOptions.NameIncludesPrefix)) details.Value = details.Prefix + details.Body; else details.Value = details.Body; return true; } #endregion } //class } //namespace
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using erl.Oracle.TnsNames.Antlr4.Runtime.Misc; namespace erl.Oracle.TnsNames.Antlr4.Runtime { /// <summary> /// Useful for rewriting out a buffered input token stream after doing some /// augmentation or other manipulations on it. /// </summary> /// <remarks> /// Useful for rewriting out a buffered input token stream after doing some /// augmentation or other manipulations on it. /// <p> /// You can insert stuff, replace, and delete chunks. Note that the operations /// are done lazily--only if you convert the buffer to a /// <see cref="string"/> /// with /// <see cref="ITokenStream.GetText()"/> /// . This is very efficient because you are not /// moving data around all the time. As the buffer of tokens is converted to /// strings, the /// <see cref="GetText()"/> /// method(s) scan the input token stream and /// check to see if there is an operation at the current index. If so, the /// operation is done and then normal /// <see cref="string"/> /// rendering continues on the /// buffer. This is like having multiple Turing machine instruction streams /// (programs) operating on a single input tape. :)</p> /// <p> /// This rewriter makes no modifications to the token stream. It does not ask the /// stream to fill itself up nor does it advance the input cursor. The token /// stream /// <see cref="IIntStream.Index()"/> /// will return the same value before and /// after any /// <see cref="GetText()"/> /// call.</p> /// <p> /// The rewriter only works on tokens that you have in the buffer and ignores the /// current input cursor. If you are buffering tokens on-demand, calling /// <see cref="GetText()"/> /// halfway through the input will only do rewrites for those /// tokens in the first half of the file.</p> /// <p> /// Since the operations are done lazily at /// <see cref="GetText()"/> /// -time, operations do /// not screw up the token index values. That is, an insert operation at token /// index /// <c>i</c> /// does not change the index values for tokens /// <c>i</c> /// +1..n-1.</p> /// <p> /// Because operations never actually alter the buffer, you may always get the /// original token stream back without undoing anything. Since the instructions /// are queued up, you can easily simulate transactions and roll back any changes /// if there is an error just by removing instructions. For example,</p> /// <pre> /// CharStream input = new ANTLRFileStream("input"); /// TLexer lex = new TLexer(input); /// CommonTokenStream tokens = new CommonTokenStream(lex); /// T parser = new T(tokens); /// TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens); /// parser.startRule(); /// </pre> /// <p> /// Then in the rules, you can execute (assuming rewriter is visible):</p> /// <pre> /// Token t,u; /// ... /// rewriter.insertAfter(t, "text to put after t");} /// rewriter.insertAfter(u, "text after u");} /// System.out.println(tokens.toString()); /// </pre> /// <p> /// You can also have multiple "instruction streams" and get multiple rewrites /// from a single pass over the input. Just name the instruction streams and use /// that name again when printing the buffer. This could be useful for generating /// a C file and also its header file--all from the same buffer:</p> /// <pre> /// tokens.insertAfter("pass1", t, "text to put after t");} /// tokens.insertAfter("pass2", u, "text after u");} /// System.out.println(tokens.toString("pass1")); /// System.out.println(tokens.toString("pass2")); /// </pre> /// <p> /// If you don't use named rewrite streams, a "default" stream is used as the /// first example shows.</p> /// </remarks> public class TokenStreamRewriter { public const string DefaultProgramName = "default"; public const int ProgramInitSize = 100; public const int MinTokenIndex = 0; public class RewriteOperation { protected internal readonly ITokenStream tokens; /// <summary>What index into rewrites List are we?</summary> protected internal int instructionIndex; /// <summary>Token buffer index.</summary> /// <remarks>Token buffer index.</remarks> protected internal int index; protected internal object text; protected internal RewriteOperation(ITokenStream tokens, int index) { // Define the rewrite operation hierarchy this.tokens = tokens; this.index = index; } protected internal RewriteOperation(ITokenStream tokens, int index, object text) { this.tokens = tokens; this.index = index; this.text = text; } /// <summary>Execute the rewrite operation by possibly adding to the buffer.</summary> /// <remarks> /// Execute the rewrite operation by possibly adding to the buffer. /// Return the index of the next token to operate on. /// </remarks> public virtual int Execute(StringBuilder buf) { return index; } public override string ToString() { string opName = GetType().FullName; int index = opName.IndexOf('$'); opName = Sharpen.Runtime.Substring(opName, index + 1, opName.Length); return "<" + opName + "@" + tokens.Get(this.index) + ":\"" + text + "\">"; } } internal class InsertBeforeOp : TokenStreamRewriter.RewriteOperation { public InsertBeforeOp(ITokenStream tokens, int index, object text) : base(tokens, index, text) { } public override int Execute(StringBuilder buf) { buf.Append(text); if (tokens.Get(index).Type != TokenConstants.EOF) { buf.Append(tokens.Get(index).Text); } return index + 1; } } /// <summary> /// I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp /// instructions. /// </summary> /// <remarks> /// I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp /// instructions. /// </remarks> internal class ReplaceOp : TokenStreamRewriter.RewriteOperation { protected internal int lastIndex; public ReplaceOp(ITokenStream tokens, int from, int to, object text) : base(tokens, from, text) { lastIndex = to; } public override int Execute(StringBuilder buf) { if (text != null) { buf.Append(text); } return lastIndex + 1; } public override string ToString() { if (text == null) { return "<DeleteOp@" + tokens.Get(index) + ".." + tokens.Get(lastIndex) + ">"; } return "<ReplaceOp@" + tokens.Get(index) + ".." + tokens.Get(lastIndex) + ":\"" + text + "\">"; } } /// <summary>Our source stream</summary> protected internal readonly ITokenStream tokens; /// <summary>You may have multiple, named streams of rewrite operations.</summary> /// <remarks> /// You may have multiple, named streams of rewrite operations. /// I'm calling these things "programs." /// Maps String (name) &#x2192; rewrite (List) /// </remarks> protected internal readonly IDictionary<string, IList<TokenStreamRewriter.RewriteOperation>> programs; /// <summary>Map String (program name) &#x2192; Integer index</summary> protected internal readonly IDictionary<string, int> lastRewriteTokenIndexes; public TokenStreamRewriter(ITokenStream tokens) { this.tokens = tokens; programs = new Dictionary<string, IList<TokenStreamRewriter.RewriteOperation>>(); programs[DefaultProgramName] = new List<TokenStreamRewriter.RewriteOperation>(ProgramInitSize); lastRewriteTokenIndexes = new Dictionary<string, int>(); } public ITokenStream TokenStream { get { return tokens; } } public virtual void Rollback(int instructionIndex) { Rollback(DefaultProgramName, instructionIndex); } /// <summary> /// Rollback the instruction stream for a program so that /// the indicated instruction (via instructionIndex) is no /// longer in the stream. /// </summary> /// <remarks> /// Rollback the instruction stream for a program so that /// the indicated instruction (via instructionIndex) is no /// longer in the stream. UNTESTED! /// </remarks> public virtual void Rollback(string programName, int instructionIndex) { IList<TokenStreamRewriter.RewriteOperation> @is; if (programs.TryGetValue(programName, out @is)) { programs[programName] = new List<RewriteOperation>(@is.Skip(MinTokenIndex).Take(instructionIndex - MinTokenIndex)); } } public virtual void DeleteProgram() { DeleteProgram(DefaultProgramName); } /// <summary>Reset the program so that no instructions exist</summary> public virtual void DeleteProgram(string programName) { Rollback(programName, MinTokenIndex); } public virtual void InsertAfter(IToken t, object text) { InsertAfter(DefaultProgramName, t, text); } public virtual void InsertAfter(int index, object text) { InsertAfter(DefaultProgramName, index, text); } public virtual void InsertAfter(string programName, IToken t, object text) { InsertAfter(programName, t.TokenIndex, text); } public virtual void InsertAfter(string programName, int index, object text) { // to insert after, just insert before next index (even if past end) InsertBefore(programName, index + 1, text); } public virtual void InsertBefore(IToken t, object text) { InsertBefore(DefaultProgramName, t, text); } public virtual void InsertBefore(int index, object text) { InsertBefore(DefaultProgramName, index, text); } public virtual void InsertBefore(string programName, IToken t, object text) { InsertBefore(programName, t.TokenIndex, text); } public virtual void InsertBefore(string programName, int index, object text) { TokenStreamRewriter.RewriteOperation op = new TokenStreamRewriter.InsertBeforeOp(tokens, index, text); IList<TokenStreamRewriter.RewriteOperation> rewrites = GetProgram(programName); op.instructionIndex = rewrites.Count; rewrites.Add(op); } public virtual void Replace(int index, object text) { Replace(DefaultProgramName, index, index, text); } public virtual void Replace(int from, int to, object text) { Replace(DefaultProgramName, from, to, text); } public virtual void Replace(IToken indexT, object text) { Replace(DefaultProgramName, indexT, indexT, text); } public virtual void Replace(IToken from, IToken to, object text) { Replace(DefaultProgramName, from, to, text); } public virtual void Replace(string programName, int from, int to, object text) { if (from > to || from < 0 || to < 0 || to >= tokens.Size) { throw new ArgumentException("replace: range invalid: " + from + ".." + to + "(size=" + tokens.Size + ")"); } TokenStreamRewriter.RewriteOperation op = new TokenStreamRewriter.ReplaceOp(tokens, from, to, text); IList<TokenStreamRewriter.RewriteOperation> rewrites = GetProgram(programName); op.instructionIndex = rewrites.Count; rewrites.Add(op); } public virtual void Replace(string programName, IToken from, IToken to, object text) { Replace(programName, from.TokenIndex, to.TokenIndex, text); } public virtual void Delete(int index) { Delete(DefaultProgramName, index, index); } public virtual void Delete(int from, int to) { Delete(DefaultProgramName, from, to); } public virtual void Delete(IToken indexT) { Delete(DefaultProgramName, indexT, indexT); } public virtual void Delete(IToken from, IToken to) { Delete(DefaultProgramName, from, to); } public virtual void Delete(string programName, int from, int to) { Replace(programName, from, to, null); } public virtual void Delete(string programName, IToken from, IToken to) { Replace(programName, from, to, null); } public virtual int LastRewriteTokenIndex { get { return GetLastRewriteTokenIndex(DefaultProgramName); } } protected internal virtual int GetLastRewriteTokenIndex(string programName) { int I; if (!lastRewriteTokenIndexes.TryGetValue(programName, out I)) { return -1; } return I; } protected internal virtual void SetLastRewriteTokenIndex(string programName, int i) { lastRewriteTokenIndexes[programName] = i; } protected internal virtual IList<TokenStreamRewriter.RewriteOperation> GetProgram(string name) { IList<TokenStreamRewriter.RewriteOperation> @is; if (!programs.TryGetValue(name, out @is)) { @is = InitializeProgram(name); } return @is; } private IList<TokenStreamRewriter.RewriteOperation> InitializeProgram(string name) { IList<TokenStreamRewriter.RewriteOperation> @is = new List<TokenStreamRewriter.RewriteOperation>(ProgramInitSize); programs[name] = @is; return @is; } /// <summary> /// Return the text from the original tokens altered per the /// instructions given to this rewriter. /// </summary> /// <remarks> /// Return the text from the original tokens altered per the /// instructions given to this rewriter. /// </remarks> public virtual string GetText() { return GetText(DefaultProgramName, Interval.Of(0, tokens.Size - 1)); } /// <summary> /// Return the text associated with the tokens in the interval from the /// original token stream but with the alterations given to this rewriter. /// </summary> /// <remarks> /// Return the text associated with the tokens in the interval from the /// original token stream but with the alterations given to this rewriter. /// The interval refers to the indexes in the original token stream. /// We do not alter the token stream in any way, so the indexes /// and intervals are still consistent. Includes any operations done /// to the first and last token in the interval. So, if you did an /// insertBefore on the first token, you would get that insertion. /// The same is true if you do an insertAfter the stop token. /// </remarks> public virtual string GetText(Interval interval) { return GetText(DefaultProgramName, interval); } public virtual string GetText(string programName, Interval interval) { IList<TokenStreamRewriter.RewriteOperation> rewrites; if (!programs.TryGetValue(programName, out rewrites)) rewrites = null; int start = interval.a; int stop = interval.b; // ensure start/end are in range if (stop > tokens.Size - 1) { stop = tokens.Size - 1; } if (start < 0) { start = 0; } if (rewrites == null || rewrites.Count == 0) { return tokens.GetText(interval); } // no instructions to execute StringBuilder buf = new StringBuilder(); // First, optimize instruction stream IDictionary<int, TokenStreamRewriter.RewriteOperation> indexToOp = ReduceToSingleOperationPerIndex(rewrites); // Walk buffer, executing instructions and emitting tokens int i = start; while (i <= stop && i < tokens.Size) { TokenStreamRewriter.RewriteOperation op; if (indexToOp.TryGetValue(i, out op)) indexToOp.Remove(i); // remove so any left have index size-1 IToken t = tokens.Get(i); if (op == null) { // no operation at that index, just dump token if (t.Type != TokenConstants.EOF) { buf.Append(t.Text); } i++; } else { // move to next token i = op.Execute(buf); } } // execute operation and skip // include stuff after end if it's last index in buffer // So, if they did an insertAfter(lastValidIndex, "foo"), include // foo if end==lastValidIndex. if (stop == tokens.Size - 1) { // Scan any remaining operations after last token // should be included (they will be inserts). foreach (TokenStreamRewriter.RewriteOperation op in indexToOp.Values) { if (op.index >= tokens.Size - 1) { buf.Append(op.text); } } } return buf.ToString(); } /// <summary> /// We need to combine operations and report invalid operations (like /// overlapping replaces that are not completed nested). /// </summary> /// <remarks> /// We need to combine operations and report invalid operations (like /// overlapping replaces that are not completed nested). Inserts to /// same index need to be combined etc... Here are the cases: /// I.i.u I.j.v leave alone, nonoverlapping /// I.i.u I.i.v combine: Iivu /// R.i-j.u R.x-y.v | i-j in x-y delete first R /// R.i-j.u R.i-j.v delete first R /// R.i-j.u R.x-y.v | x-y in i-j ERROR /// R.i-j.u R.x-y.v | boundaries overlap ERROR /// Delete special case of replace (text==null): /// D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right) /// I.i.u R.x-y.v | i in (x+1)-y delete I (since insert before /// we're not deleting i) /// I.i.u R.x-y.v | i not in (x+1)-y leave alone, nonoverlapping /// R.x-y.v I.i.u | i in x-y ERROR /// R.x-y.v I.x.u R.x-y.uv (combine, delete I) /// R.x-y.v I.i.u | i not in x-y leave alone, nonoverlapping /// I.i.u = insert u before op @ index i /// R.x-y.u = replace x-y indexed tokens with u /// First we need to examine replaces. For any replace op: /// 1. wipe out any insertions before op within that range. /// 2. Drop any replace op before that is contained completely within /// that range. /// 3. Throw exception upon boundary overlap with any previous replace. /// Then we can deal with inserts: /// 1. for any inserts to same index, combine even if not adjacent. /// 2. for any prior replace with same left boundary, combine this /// insert with replace and delete this replace. /// 3. throw exception if index in same range as previous replace /// Don't actually delete; make op null in list. Easier to walk list. /// Later we can throw as we add to index &#x2192; op map. /// Note that I.2 R.2-2 will wipe out I.2 even though, technically, the /// inserted stuff would be before the replace range. But, if you /// add tokens in front of a method body '{' and then delete the method /// body, I think the stuff before the '{' you added should disappear too. /// Return a map from token index to operation. /// </remarks> protected internal virtual IDictionary<int, TokenStreamRewriter.RewriteOperation> ReduceToSingleOperationPerIndex(IList<TokenStreamRewriter.RewriteOperation> rewrites) { // System.out.println("rewrites="+rewrites); // WALK REPLACES for (int i = 0; i < rewrites.Count; i++) { TokenStreamRewriter.RewriteOperation op = rewrites[i]; if (op == null) { continue; } if (!(op is TokenStreamRewriter.ReplaceOp)) { continue; } TokenStreamRewriter.ReplaceOp rop = (TokenStreamRewriter.ReplaceOp)rewrites[i]; // Wipe prior inserts within range IList<TokenStreamRewriter.InsertBeforeOp> inserts = GetKindOfOps<TokenStreamRewriter.InsertBeforeOp>(rewrites, i); foreach (TokenStreamRewriter.InsertBeforeOp iop in inserts) { if (iop.index == rop.index) { // E.g., insert before 2, delete 2..2; update replace // text to include insert before, kill insert rewrites[iop.instructionIndex] = null; rop.text = iop.text.ToString() + (rop.text != null ? rop.text.ToString() : string.Empty); } else { if (iop.index > rop.index && iop.index <= rop.lastIndex) { // delete insert as it's a no-op. rewrites[iop.instructionIndex] = null; } } } // Drop any prior replaces contained within IList<TokenStreamRewriter.ReplaceOp> prevReplaces = GetKindOfOps<TokenStreamRewriter.ReplaceOp>(rewrites, i); foreach (TokenStreamRewriter.ReplaceOp prevRop in prevReplaces) { if (prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex) { // delete replace as it's a no-op. rewrites[prevRop.instructionIndex] = null; continue; } // throw exception unless disjoint or identical bool disjoint = prevRop.lastIndex < rop.index || prevRop.index > rop.lastIndex; bool same = prevRop.index == rop.index && prevRop.lastIndex == rop.lastIndex; // Delete special case of replace (text==null): // D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right) if (prevRop.text == null && rop.text == null && !disjoint) { //System.out.println("overlapping deletes: "+prevRop+", "+rop); rewrites[prevRop.instructionIndex] = null; // kill first delete rop.index = Math.Min(prevRop.index, rop.index); rop.lastIndex = Math.Max(prevRop.lastIndex, rop.lastIndex); System.Console.Out.WriteLine("new rop " + rop); } else { if (!disjoint && !same) { throw new ArgumentException("replace op boundaries of " + rop + " overlap with previous " + prevRop); } } } } // WALK INSERTS for (int i_1 = 0; i_1 < rewrites.Count; i_1++) { TokenStreamRewriter.RewriteOperation op = rewrites[i_1]; if (op == null) { continue; } if (!(op is TokenStreamRewriter.InsertBeforeOp)) { continue; } TokenStreamRewriter.InsertBeforeOp iop = (TokenStreamRewriter.InsertBeforeOp)rewrites[i_1]; // combine current insert with prior if any at same index IList<TokenStreamRewriter.InsertBeforeOp> prevInserts = GetKindOfOps<TokenStreamRewriter.InsertBeforeOp>(rewrites, i_1); foreach (TokenStreamRewriter.InsertBeforeOp prevIop in prevInserts) { if (prevIop.index == iop.index) { // combine objects // convert to strings...we're in process of toString'ing // whole token buffer so no lazy eval issue with any templates iop.text = CatOpText(iop.text, prevIop.text); // delete redundant prior insert rewrites[prevIop.instructionIndex] = null; } } // look for replaces where iop.index is in range; error IList<TokenStreamRewriter.ReplaceOp> prevReplaces = GetKindOfOps<TokenStreamRewriter.ReplaceOp>(rewrites, i_1); foreach (TokenStreamRewriter.ReplaceOp rop in prevReplaces) { if (iop.index == rop.index) { rop.text = CatOpText(iop.text, rop.text); rewrites[i_1] = null; // delete current insert continue; } if (iop.index >= rop.index && iop.index <= rop.lastIndex) { throw new ArgumentException("insert op " + iop + " within boundaries of previous " + rop); } } } // System.out.println("rewrites after="+rewrites); IDictionary<int, TokenStreamRewriter.RewriteOperation> m = new Dictionary<int, TokenStreamRewriter.RewriteOperation>(); for (int i_2 = 0; i_2 < rewrites.Count; i_2++) { TokenStreamRewriter.RewriteOperation op = rewrites[i_2]; if (op == null) { continue; } // ignore deleted ops if (m.ContainsKey(op.index)) { throw new InvalidOperationException("should only be one op per index"); } m[op.index] = op; } //System.out.println("index to op: "+m); return m; } protected internal virtual string CatOpText(object a, object b) { string x = string.Empty; string y = string.Empty; if (a != null) { x = a.ToString(); } if (b != null) { y = b.ToString(); } return x + y; } /// <summary>Get all operations before an index of a particular kind</summary> protected internal virtual IList<T> GetKindOfOps<T>(IList<RewriteOperation> rewrites, int before) { return rewrites.Take(before).OfType<T>().ToList(); } } }
//$Id$ using System; using Microsoft.Build.Framework; using System.DirectoryServices; using System.Runtime.InteropServices; using Microsoft.Build.Utilities; namespace MSBuild.Community.Tasks.IIS { /// <summary> /// Sets an application mapping for a filename extension on an existing web directory. /// </summary> /// <example>Map the .axd extension to the lastest version of ASP.NET: /// <code><![CDATA[ /// <WebDirectoryScriptMap VirtualDirectoryName="MyWeb" Extension=".axd" MapToAspNet="True" VerifyFileExists="False" /> /// ]]></code> /// </example> /// <example>Map GET requests to the .rss extension to a specific executable: /// <code><![CDATA[ /// <WebDirectoryScriptMap VirtualDirectoryName="MyWeb" Extension=".rss" Verbs="GET" ExecutablePath="$(WINDIR)\Microsoft.Net\Framework\1.0.3705\aspnet_isapi.dll" /> /// ]]></code> /// </example> public class WebDirectoryScriptMap : WebBase { private string mVirtualDirectoryName; /// <summary> /// Gets or sets the name of the virtual directory. /// </summary> /// <value>The name of the virtual directory.</value> [Required] public string VirtualDirectoryName { get { return mVirtualDirectoryName; } set { mVirtualDirectoryName = value; } } private string extension; /// <summary> /// The filename extension that will be mapped to an executable. /// </summary> [Required] public string Extension { get { return extension; } set { extension = value; } } private string executablePath; /// <summary> /// The full path to the executable used to respond to requests for a Uri ending with <see cref="Extension"/> /// </summary> /// <remarks>This property is required when <see cref="MapToAspNet"/> is <c>false</c> (the default).</remarks> public string ExecutablePath { get { return executablePath; } set { executablePath = value; } } private bool mapToAspNet; /// <summary> /// Indicates whether <see cref="Extension"/> should be mapped to the ASP.NET runtime. /// </summary> /// <remarks>When <c>true</c>, <see cref="ExecutablePath"/> is set to aspnet_isapi.dll /// in the installation folder of the latest version of the .NET Framework.</remarks> public bool MapToAspNet { get { return mapToAspNet; } set { mapToAspNet = value; } } private string verbs; /// <summary> /// A comma-separated list of the HTTP verbs to include in the application mapping. /// </summary> /// <remarks>The default behavior (when this property is empty or unspecified) is to map all verbs. /// <para>A semi-colon-separated list will also be recognized, allowing you to use an MSBuild Item.</para></remarks> public string Verbs { get { return verbs; } set { verbs = value; } } private bool enableScriptEngine; /// <summary> /// Set to <c>true</c> when you want the application to run in a directory without Execute permissions. /// </summary> public bool EnableScriptEngine { get { return enableScriptEngine; } set { enableScriptEngine = value; } } private bool verifyFileExists; /// <summary> /// Set to <c>true</c> to instruct the Web server to verify the existence of the requested script file and to ensure that the requesting user has access permission for that script file. /// </summary> public bool VerifyFileExists { get { return verifyFileExists; } set { verifyFileExists = value; } } /// <summary> /// When overridden in a derived class, executes the task. /// </summary> /// <returns> /// True if the task successfully executed; otherwise, false. /// </returns> public override bool Execute() { if (!mapToAspNet && String.IsNullOrEmpty(executablePath)) { Log.LogError("You must either specify a value for ExecutablePath, or set MapToAspNet = True."); return false; } if (mapToAspNet) { executablePath = ToolLocationHelper.GetPathToDotNetFrameworkFile("aspnet_isapi.dll", TargetDotNetFrameworkVersion.VersionLatest); enableScriptEngine = true; } int flags = 0; if (enableScriptEngine) flags += 1; if (verifyFileExists) flags += 4; if (!extension.StartsWith(".") && extension != "*") extension = "." + extension; DirectoryEntry targetDirectory = null; try { Log.LogMessage(MessageImportance.Normal, Properties.Resources.WebDirectoryScriptMapUpdate, Extension, VirtualDirectoryName, ServerName); VerifyIISRoot(); string targetDirectoryPath = (VirtualDirectoryName == "/") ? targetDirectoryPath = IISServerPath : targetDirectoryPath = IISServerPath + "/" + VirtualDirectoryName; targetDirectory = new DirectoryEntry(targetDirectoryPath); try { string directoryExistsTest = targetDirectory.SchemaClassName; } catch (COMException) { Log.LogError(Properties.Resources.WebDirectoryInvalidDirectory, VirtualDirectoryName, ServerName); return false; } PropertyValueCollection scriptMaps = targetDirectory.Properties["ScriptMaps"]; if (scriptMaps == null) { Log.LogError(Properties.Resources.WebDirectorySettingInvalidSetting, VirtualDirectoryName, ServerName, "ScriptMaps"); return false; } int extensionIndex = -1; for (int i = 0; i < scriptMaps.Count; i++) { string scriptMap = scriptMaps[i] as string; if (scriptMap == null) continue; if (scriptMap.StartsWith(extension + ",", StringComparison.InvariantCultureIgnoreCase)) { extensionIndex = i; break; } } string newVerbs = !String.IsNullOrEmpty(verbs) ? "," + verbs.Replace(';', ',') : String.Empty; string mappingDetails = String.Format("{0},{1},{2}{3}", extension, executablePath, flags.ToString(), newVerbs ); if (extensionIndex >= 0) { scriptMaps[extensionIndex] = mappingDetails; } else { scriptMaps.Add(mappingDetails); } targetDirectory.CommitChanges(); } finally { if (targetDirectory != null) targetDirectory.Dispose(); } return true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public partial class ParallelQueryCombinationTests { [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Aggregate_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate((x, y) => x)); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate(0, (x, y) => x + y)); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate(0, (x, y) => x + y, r => r)); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r)); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void All_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).All(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Any_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Any(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Average_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Average()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Contains_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Contains(DefaultStart)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Count_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Count()); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).LongCount()); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Count(x => true)); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).LongCount(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ElementAt_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).ElementAt(0)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ElementAtOrDefault_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).ElementAtOrDefault(0)); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).ElementAtOrDefault(DefaultSize + 1)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void First_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).First()); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).First(x => false)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void FirstOrDefault_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).FirstOrDefault()); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).FirstOrDefault(x => false)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ForAll_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ForAll(x => { })); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Last_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Last()); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Last(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void LastOrDefault_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).LastOrDefault()); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).LastOrDefault(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Max_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, (start, count, ignore) => source.Item(start, count).WithCancellation(cs.Token)).Max()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Min_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Min()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SequenceEqual_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).SequenceEqual(ParallelEnumerable.Range(0, 2))); Functions.AssertIsCanceled(cs, () => ParallelEnumerable.Range(0, 2).SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item))); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Single_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Single()); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Single(x => false)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SingleOrDefault_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).SingleOrDefault()); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).SingleOrDefault(x => false)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Sum_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).Sum()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ToArray_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToArray()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ToDictionary_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToDictionary(x => x)); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToDictionary(x => x, y => y)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ToList_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToList()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ToLookup_OperationCanceledException_PreCanceled(LabeledOperation source, LabeledOperation operation) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToLookup(x => x)); Functions.AssertIsCanceled(cs, () => operation.Item(DefaultStart, DefaultSize, source.Append(WithCancellation(cs.Token)).Item).ToLookup(x => x, y => y)); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcbdv = Google.Cloud.BigQuery.DataTransfer.V1; using sys = System; namespace Google.Cloud.BigQuery.DataTransfer.V1 { /// <summary>Resource name for the <c>DataSource</c> resource.</summary> public sealed partial class DataSourceName : gax::IResourceName, sys::IEquatable<DataSourceName> { /// <summary>The possible contents of <see cref="DataSourceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/dataSources/{data_source}</c>.</summary> ProjectDataSource = 1, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/dataSources/{data_source}</c>. /// </summary> ProjectLocationDataSource = 2, } private static gax::PathTemplate s_projectDataSource = new gax::PathTemplate("projects/{project}/dataSources/{data_source}"); private static gax::PathTemplate s_projectLocationDataSource = new gax::PathTemplate("projects/{project}/locations/{location}/dataSources/{data_source}"); /// <summary>Creates a <see cref="DataSourceName"/> 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="DataSourceName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static DataSourceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new DataSourceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="DataSourceName"/> with the pattern <c>projects/{project}/dataSources/{data_source}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dataSourceId">The <c>DataSource</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="DataSourceName"/> constructed from the provided ids.</returns> public static DataSourceName FromProjectDataSource(string projectId, string dataSourceId) => new DataSourceName(ResourceNameType.ProjectDataSource, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), dataSourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(dataSourceId, nameof(dataSourceId))); /// <summary> /// Creates a <see cref="DataSourceName"/> with the pattern /// <c>projects/{project}/locations/{location}/dataSources/{data_source}</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="dataSourceId">The <c>DataSource</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="DataSourceName"/> constructed from the provided ids.</returns> public static DataSourceName FromProjectLocationDataSource(string projectId, string locationId, string dataSourceId) => new DataSourceName(ResourceNameType.ProjectLocationDataSource, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), dataSourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(dataSourceId, nameof(dataSourceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="DataSourceName"/> with pattern /// <c>projects/{project}/dataSources/{data_source}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dataSourceId">The <c>DataSource</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DataSourceName"/> with pattern /// <c>projects/{project}/dataSources/{data_source}</c>. /// </returns> public static string Format(string projectId, string dataSourceId) => FormatProjectDataSource(projectId, dataSourceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="DataSourceName"/> with pattern /// <c>projects/{project}/dataSources/{data_source}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dataSourceId">The <c>DataSource</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DataSourceName"/> with pattern /// <c>projects/{project}/dataSources/{data_source}</c>. /// </returns> public static string FormatProjectDataSource(string projectId, string dataSourceId) => s_projectDataSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(dataSourceId, nameof(dataSourceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="DataSourceName"/> with pattern /// <c>projects/{project}/locations/{location}/dataSources/{data_source}</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="dataSourceId">The <c>DataSource</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DataSourceName"/> with pattern /// <c>projects/{project}/locations/{location}/dataSources/{data_source}</c>. /// </returns> public static string FormatProjectLocationDataSource(string projectId, string locationId, string dataSourceId) => s_projectLocationDataSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(dataSourceId, nameof(dataSourceId))); /// <summary>Parses the given resource name string into a new <see cref="DataSourceName"/> 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}/dataSources/{data_source}</c></description></item> /// <item> /// <description><c>projects/{project}/locations/{location}/dataSources/{data_source}</c></description> /// </item> /// </list> /// </remarks> /// <param name="dataSourceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="DataSourceName"/> if successful.</returns> public static DataSourceName Parse(string dataSourceName) => Parse(dataSourceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="DataSourceName"/> 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}/dataSources/{data_source}</c></description></item> /// <item> /// <description><c>projects/{project}/locations/{location}/dataSources/{data_source}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="dataSourceName">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="DataSourceName"/> if successful.</returns> public static DataSourceName Parse(string dataSourceName, bool allowUnparsed) => TryParse(dataSourceName, allowUnparsed, out DataSourceName 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="DataSourceName"/> 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}/dataSources/{data_source}</c></description></item> /// <item> /// <description><c>projects/{project}/locations/{location}/dataSources/{data_source}</c></description> /// </item> /// </list> /// </remarks> /// <param name="dataSourceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="DataSourceName"/>, 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 dataSourceName, out DataSourceName result) => TryParse(dataSourceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DataSourceName"/> 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}/dataSources/{data_source}</c></description></item> /// <item> /// <description><c>projects/{project}/locations/{location}/dataSources/{data_source}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="dataSourceName">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="DataSourceName"/>, 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 dataSourceName, bool allowUnparsed, out DataSourceName result) { gax::GaxPreconditions.CheckNotNull(dataSourceName, nameof(dataSourceName)); gax::TemplatedResourceName resourceName; if (s_projectDataSource.TryParseName(dataSourceName, out resourceName)) { result = FromProjectDataSource(resourceName[0], resourceName[1]); return true; } if (s_projectLocationDataSource.TryParseName(dataSourceName, out resourceName)) { result = FromProjectLocationDataSource(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(dataSourceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private DataSourceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string dataSourceId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; DataSourceId = dataSourceId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="DataSourceName"/> class from the component parts of pattern /// <c>projects/{project}/dataSources/{data_source}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="dataSourceId">The <c>DataSource</c> ID. Must not be <c>null</c> or empty.</param> public DataSourceName(string projectId, string dataSourceId) : this(ResourceNameType.ProjectDataSource, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), dataSourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(dataSourceId, nameof(dataSourceId))) { } /// <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>DataSource</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string DataSourceId { get; } /// <summary> /// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </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.ProjectDataSource: return s_projectDataSource.Expand(ProjectId, DataSourceId); case ResourceNameType.ProjectLocationDataSource: return s_projectLocationDataSource.Expand(ProjectId, LocationId, DataSourceId); 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 DataSourceName); /// <inheritdoc/> public bool Equals(DataSourceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(DataSourceName a, DataSourceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(DataSourceName a, DataSourceName b) => !(a == b); } public partial class DataSource { /// <summary> /// <see cref="gcbdv::DataSourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbdv::DataSourceName DataSourceName { get => string.IsNullOrEmpty(Name) ? null : gcbdv::DataSourceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetDataSourceRequest { /// <summary> /// <see cref="gcbdv::DataSourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbdv::DataSourceName DataSourceName { get => string.IsNullOrEmpty(Name) ? null : gcbdv::DataSourceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListDataSourcesRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location)) { return location; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class CreateTransferConfigRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location)) { return location; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class GetTransferConfigRequest { /// <summary> /// <see cref="gcbdv::TransferConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbdv::TransferConfigName TransferConfigName { get => string.IsNullOrEmpty(Name) ? null : gcbdv::TransferConfigName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteTransferConfigRequest { /// <summary> /// <see cref="gcbdv::TransferConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbdv::TransferConfigName TransferConfigName { get => string.IsNullOrEmpty(Name) ? null : gcbdv::TransferConfigName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetTransferRunRequest { /// <summary> /// <see cref="gcbdv::RunName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbdv::RunName RunName { get => string.IsNullOrEmpty(Name) ? null : gcbdv::RunName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteTransferRunRequest { /// <summary> /// <see cref="gcbdv::RunName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbdv::RunName RunName { get => string.IsNullOrEmpty(Name) ? null : gcbdv::RunName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListTransferConfigsRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } if (gagr::LocationName.TryParse(Parent, out gagr::LocationName location)) { return location; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class ListTransferRunsRequest { /// <summary> /// <see cref="TransferConfigName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public TransferConfigName ParentAsTransferConfigName { get => string.IsNullOrEmpty(Parent) ? null : TransferConfigName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListTransferLogsRequest { /// <summary><see cref="RunName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public RunName ParentAsRunName { get => string.IsNullOrEmpty(Parent) ? null : RunName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class CheckValidCredsRequest { /// <summary> /// <see cref="gcbdv::DataSourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbdv::DataSourceName DataSourceName { get => string.IsNullOrEmpty(Name) ? null : gcbdv::DataSourceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ScheduleTransferRunsRequest { /// <summary> /// <see cref="TransferConfigName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public TransferConfigName ParentAsTransferConfigName { get => string.IsNullOrEmpty(Parent) ? null : TransferConfigName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class StartManualTransferRunsRequest { /// <summary> /// <see cref="TransferConfigName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public TransferConfigName ParentAsTransferConfigName { get => string.IsNullOrEmpty(Parent) ? null : TransferConfigName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using DotSpatial.Data; using DotSpatial.NTSExtension; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// PointScheme. /// </summary> [TypeConverter(typeof(ExpandableObjectConverter))] [Serializable] public class PointScheme : FeatureScheme, IPointScheme { #region Fields private PointCategoryCollection _categories; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PointScheme"/> class. /// </summary> public PointScheme() { Configure(); PointCategory def = new PointCategory(); Categories.Add(def); } /// <summary> /// Initializes a new instance of the <see cref="PointScheme"/> class. /// </summary> /// <param name="extent">The geographic point size for the default will be 1/100th the specified extent.</param> public PointScheme(IRectangle extent) { Configure(); PointCategory def = new PointCategory(extent); Categories.Add(def); } #endregion #region Properties /// <summary> /// Gets or sets the symbolic categories as a valid IPointSchemeCategoryCollection. /// </summary> /// <remarks> /// [TypeConverter(typeof(CategoryCollectionConverter))] /// [Editor(typeof(PointCategoryCollectionEditor), typeof(UITypeEditor))]. /// </remarks> [Description("Gets the list of categories.")] [Serialize("Categories")] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PointCategoryCollection Categories { get { return _categories; } set { OnExcludeCategories(_categories); _categories = value; OnIncludeCategories(_categories); } } /// <summary> /// Gets the number of categories in this scheme. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override int NumCategories => _categories?.Count ?? 0; #endregion #region Methods /// <summary> /// Adds a new scheme, assuming that the new scheme is the correct type. /// </summary> /// <param name="category">The category to add.</param> public override void AddCategory(ICategory category) { IPointCategory pc = category as IPointCategory; if (pc != null) _categories.Add(pc); } /// <summary> /// Clears the categories. /// </summary> public override void ClearCategories() { _categories.Clear(); } /// <summary> /// Creates the category using a random fill color. /// </summary> /// <param name="fillColor">The base color to use for creating the category.</param> /// <param name="size">The double size of the larger dimension of the point.</param> /// <returns>A new polygon category.</returns> public override ICategory CreateNewCategory(Color fillColor, double size) { IPointSymbolizer ps = EditorSettings.TemplateSymbolizer.Copy() as IPointSymbolizer ?? new PointSymbolizer(fillColor, PointShape.Ellipse, size); ps.SetFillColor(fillColor); Size2D oSize = ps.GetSize(); double rat = size / Math.Max(oSize.Width, oSize.Height); ps.SetSize(new Size2D(rat * oSize.Width, rat * oSize.Height)); return new PointCategory(ps); } /// <summary> /// Uses the settings on this scheme to create a random category. /// </summary> /// <param name="filterExpression">Used as filterExpression and LegendText in the resulting category.</param> /// <returns>A new IFeatureCategory.</returns> public override IFeatureCategory CreateRandomCategory(string filterExpression) { PointCategory result = new PointCategory(); Color fillColor = CreateRandomColor(); result.Symbolizer = new PointSymbolizer(fillColor, PointShape.Ellipse, 10); result.FilterExpression = filterExpression; result.LegendText = filterExpression; return result; } /// <summary> /// Reduces the index value of the specified category by 1 by /// exchaning it with the category before it. If there is no /// category before it, then this does nothing. /// </summary> /// <param name="category">The category to decrease the index of.</param> /// <returns>True, if index was decreased.</returns> public override bool DecreaseCategoryIndex(ICategory category) { IPointCategory pc = category as IPointCategory; return pc != null && Categories.DecreaseIndex(pc); } /// <summary> /// Draws the regular symbolizer for the specified cateogry to the specified graphics /// surface in the specified bounding rectangle. /// </summary> /// <param name="index">The integer index of the feature to draw.</param> /// <param name="g">The Graphics object to draw to.</param> /// <param name="bounds">The rectangular bounds to draw in.</param> public override void DrawCategory(int index, Graphics g, Rectangle bounds) { Categories[index].Symbolizer.Draw(g, bounds); } /// <summary> /// Calculates the unique colors as a scheme. /// </summary> /// <param name="fs">The featureset with the data Table definition.</param> /// <param name="uniqueField">The unique field.</param> /// <returns>A hashtable with the generated unique colors.</returns> public Hashtable GenerateUniqueColors(IFeatureSet fs, string uniqueField) { return GenerateUniqueColors(fs, uniqueField, color => new PointCategory(color, PointShape.Rectangle, 10)); } /// <summary> /// Gets the point categories cast as FeatureCategories. This is enumerable, /// but should be thought of as a copy of the original, not the original itself. /// </summary> /// <returns>The categories.</returns> public override IEnumerable<IFeatureCategory> GetCategories() { return _categories; } /// <summary> /// Re-orders the specified member by attempting to exchange it with the next higher /// index category. If there is no higher index, this does nothing. /// </summary> /// <param name="category">The category to increase the index of.</param> /// <returns>True, if index was increased.</returns> public override bool IncreaseCategoryIndex(ICategory category) { IPointCategory pc = category as IPointCategory; return pc != null && Categories.IncreaseIndex(pc); } /// <summary> /// Inserts the category at the specified index. /// </summary> /// <param name="index">The integer index where the category should be inserted.</param> /// <param name="category">The category to insert.</param> public override void InsertCategory(int index, ICategory category) { IPointCategory pc = category as IPointCategory; if (pc != null) _categories.Insert(index, pc); } /// <summary> /// Removes the specified category. /// </summary> /// <param name="category">The category to insert.</param> public override void RemoveCategory(ICategory category) { IPointCategory pc = category as IPointCategory; if (pc != null) _categories.Remove(pc); } /// <summary> /// Resumes the category events. /// </summary> public override void ResumeEvents() { _categories.ResumeEvents(); } /// <summary> /// Suspends the category events. /// </summary> public override void SuspendEvents() { _categories.SuspendEvents(); } /// <summary> /// If possible, use the template to control the colors. Otherwise, just use the default /// settings for creating "unbounded" colors. /// </summary> /// <param name="count">The integer count.</param> /// <returns>The List of colors.</returns> protected override List<Color> GetDefaultColors(int count) { IPointSymbolizer ps = EditorSettings?.TemplateSymbolizer as IPointSymbolizer; if (ps != null) { List<Color> result = new List<Color>(); Color c = ps.GetFillColor(); for (int i = 0; i < count; i++) { result.Add(c); } return result; } return base.GetDefaultColors(count); } /// <summary> /// Handle the event un-wiring and scheme update for the old categories. /// </summary> /// <param name="categories">The category collection to update.</param> protected virtual void OnExcludeCategories(PointCategoryCollection categories) { if (categories == null) return; categories.Scheme = null; categories.ItemChanged -= CategoriesItemChanged; categories.SelectFeatures -= OnSelectFeatures; categories.DeselectFeatures -= OnDeselectFeatures; } /// <summary> /// Handle the event wiring and scheme update for the new categories. /// </summary> /// <param name="categories">The category collection to update.</param> protected virtual void OnIncludeCategories(PointCategoryCollection categories) { if (categories == null) return; categories.Scheme = this; categories.ItemChanged += CategoriesItemChanged; categories.SelectFeatures += OnSelectFeatures; categories.DeselectFeatures += OnDeselectFeatures; } private void CategoriesItemChanged(object sender, EventArgs e) { OnItemChanged(sender); } private void Configure() { _categories = new PointCategoryCollection(); OnIncludeCategories(_categories); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.Security.Tests { public static class SecureStringTests { [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(ushort.MaxValue + 1)] // max allowed length public static void Ctor(int length) { string expected = CreateString(length); using (SecureString actual = CreateSecureString(expected)) { AssertEquals(expected, actual); } } [Fact] public static unsafe void Ctor_CharInt_Invalid() { Assert.Throws<ArgumentNullException>("value", () => new SecureString(null, 0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => { fixed (char* chars = "test") new SecureString(chars, -1); }); Assert.Throws<ArgumentOutOfRangeException>("length", () => CreateSecureString(CreateString(ushort.MaxValue + 2 /*65537: Max allowed length is 65536*/))); } [Fact] public static void AppendChar() { using (SecureString testString = CreateSecureString(string.Empty)) { var expected = new StringBuilder(); foreach (var ch in new[] { 'a', 'b', 'c', 'd' }) { testString.AppendChar(ch); expected.Append(ch); AssertEquals(expected.ToString(), testString); } AssertEquals(expected.ToString(), testString); // check last case one more time for idempotency } } [Fact] public static void AppendChar_TooLong_Throws() { using (SecureString ss = CreateSecureString(CreateString(ushort.MaxValue + 1))) { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => ss.AppendChar('a')); } } [Theory] [InlineData("")] [InlineData("test")] public static void Clear(string initialValue) { using (SecureString testString = CreateSecureString(initialValue)) { AssertEquals(initialValue, testString); testString.Clear(); AssertEquals(string.Empty, testString); } } [Fact] public static void MakeReadOnly_ReadingSucceeds_AllOtherModificationsThrow() { string initialValue = "test"; using (SecureString ss = CreateSecureString(initialValue)) { Assert.False(ss.IsReadOnly()); ss.MakeReadOnly(); Assert.True(ss.IsReadOnly()); // Reads succeed AssertEquals(initialValue, ss); Assert.Equal(initialValue.Length, ss.Length); using (SecureString other = ss.Copy()) { AssertEquals(initialValue, other); } ss.MakeReadOnly(); // ok to call again // Writes throw Assert.Throws<InvalidOperationException>(() => ss.AppendChar('a')); Assert.Throws<InvalidOperationException>(() => ss.Clear()); Assert.Throws<InvalidOperationException>(() => ss.InsertAt(0, 'a')); Assert.Throws<InvalidOperationException>(() => ss.RemoveAt(0)); Assert.Throws<InvalidOperationException>(() => ss.SetAt(0, 'a')); } } [Fact] public static void Dispose_AllOtherOperationsThrow() { SecureString ss = CreateSecureString("test"); ss.Dispose(); Assert.Throws<ObjectDisposedException>(() => ss.AppendChar('a')); Assert.Throws<ObjectDisposedException>(() => ss.Clear()); Assert.Throws<ObjectDisposedException>(() => ss.Copy()); Assert.Throws<ObjectDisposedException>(() => ss.InsertAt(0, 'a')); Assert.Throws<ObjectDisposedException>(() => ss.IsReadOnly()); Assert.Throws<ObjectDisposedException>(() => ss.Length); Assert.Throws<ObjectDisposedException>(() => ss.MakeReadOnly()); Assert.Throws<ObjectDisposedException>(() => ss.RemoveAt(0)); Assert.Throws<ObjectDisposedException>(() => ss.SetAt(0, 'a')); Assert.Throws<ObjectDisposedException>(() => SecureStringMarshal.SecureStringToCoTaskMemAnsi(ss)); Assert.Throws<ObjectDisposedException>(() => SecureStringMarshal.SecureStringToCoTaskMemUnicode(ss)); Assert.Throws<ObjectDisposedException>(() => SecureStringMarshal.SecureStringToGlobalAllocAnsi(ss)); Assert.Throws<ObjectDisposedException>(() => SecureStringMarshal.SecureStringToGlobalAllocUnicode(ss)); ss.Dispose(); // ok to call again } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(4000)] public static void Copy(int length) { string expected = CreateString(length); using (SecureString testString = CreateSecureString(expected)) using (SecureString copyString = testString.Copy()) { Assert.False(copyString.IsReadOnly()); AssertEquals(expected, copyString); } using (SecureString testString = CreateSecureString(expected)) { testString.MakeReadOnly(); using (SecureString copyString = testString.Copy()) { Assert.False(copyString.IsReadOnly()); AssertEquals(expected, copyString); } } } [Fact] public static void InsertAt() { using (SecureString testString = CreateSecureString("bd")) { testString.InsertAt(0, 'a'); AssertEquals("abd", testString); testString.InsertAt(3, 'e'); AssertEquals("abde", testString); testString.InsertAt(2, 'c'); AssertEquals("abcde", testString); } } [Fact] public static void InsertAt_LongString() { string initialValue = CreateString(ushort.MaxValue); for (int iter = 0; iter < 2; iter++) { using (SecureString testString = CreateSecureString(initialValue)) { string expected = initialValue; AssertEquals(expected, testString); if (iter == 0) // add at the beginning { expected = 'b' + expected; testString.InsertAt(0, 'b'); } else // add at the end { expected += 'b'; testString.InsertAt(testString.Length, 'b'); } AssertEquals(expected, testString); } } } [Fact] public static void InsertAt_Invalid_Throws() { using (SecureString testString = CreateSecureString("bd")) { Assert.Throws<ArgumentOutOfRangeException>("index", () => testString.InsertAt(-1, 'S')); Assert.Throws<ArgumentOutOfRangeException>("index", () => testString.InsertAt(6, 'S')); } using (SecureString testString = CreateSecureString(CreateString(ushort.MaxValue + 1))) { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => testString.InsertAt(22, 'S')); } } [Fact] public static void RemoveAt() { using (SecureString testString = CreateSecureString("abcde")) { testString.RemoveAt(3); AssertEquals("abce", testString); testString.RemoveAt(3); AssertEquals("abc", testString); testString.RemoveAt(0); AssertEquals("bc", testString); testString.RemoveAt(1); AssertEquals("b", testString); testString.RemoveAt(0); AssertEquals("", testString); testString.AppendChar('f'); AssertEquals("f", testString); testString.AppendChar('g'); AssertEquals("fg", testString); testString.RemoveAt(0); AssertEquals("g", testString); } } [Fact] public static void RemoveAt_Largest() { string expected = CreateString(ushort.MaxValue + 1); using (SecureString testString = CreateSecureString(expected)) { testString.RemoveAt(22); expected = expected.Substring(0, 22) + expected.Substring(23); AssertEquals(expected, testString); } } [Fact] public static void RemoveAt_Invalid_Throws() { using (SecureString testString = CreateSecureString("test")) { Assert.Throws<ArgumentOutOfRangeException>("index", () => testString.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => testString.RemoveAt(testString.Length)); Assert.Throws<ArgumentOutOfRangeException>("index", () => testString.RemoveAt(testString.Length + 1)); } } [Fact] public static void SetAt() { using (SecureString testString = CreateSecureString("abc")) { testString.SetAt(2, 'f'); AssertEquals("abf", testString); testString.SetAt(0, 'd'); AssertEquals("dbf", testString); testString.SetAt(1, 'e'); AssertEquals("def", testString); } string expected = CreateString(ushort.MaxValue + 1); using (SecureString testString = CreateSecureString(expected)) { testString.SetAt(22, 'b'); char[] chars = expected.ToCharArray(); chars[22] = 'b'; AssertEquals(new string(chars), testString); } } [Fact] public static void SetAt_Invalid_Throws() { using (SecureString testString = CreateSecureString("test")) { Assert.Throws<ArgumentOutOfRangeException>("index", () => testString.SetAt(-1, 'a')); Assert.Throws<ArgumentOutOfRangeException>("index", () => testString.SetAt(testString.Length, 'b')); Assert.Throws<ArgumentOutOfRangeException>("index", () => testString.SetAt(testString.Length + 1, 'c')); } } [Fact] public static void SecureStringMarshal_NullArgsAllowed_IntPtrZero() { Assert.Equal(IntPtr.Zero, SecureStringMarshal.SecureStringToCoTaskMemAnsi(null)); Assert.Equal(IntPtr.Zero, SecureStringMarshal.SecureStringToCoTaskMemUnicode(null)); Assert.Equal(IntPtr.Zero, SecureStringMarshal.SecureStringToGlobalAllocAnsi(null)); Assert.Equal(IntPtr.Zero, SecureStringMarshal.SecureStringToGlobalAllocUnicode(null)); } [Fact] public static void RepeatedCtorDispose() { string str = CreateString(4000); for (int i = 0; i < 1000; i++) { CreateSecureString(str).Dispose(); } } [Theory] [InlineData(0, false)] [InlineData(0, true)] [InlineData(1, false)] [InlineData(1, true)] [InlineData(2, false)] [InlineData(2, true)] [InlineData(1000, false)] [InlineData(1000, true)] public static void SecureStringMarshal_Ansi_Roundtrip(int length, bool allocHGlobal) { string input = new string(Enumerable .Range(0, length) .Select(i => (char)('a' + i)) // include non-ASCII chars .ToArray()); IntPtr marshaledString = Marshal.StringToHGlobalAnsi(input); string expectedAnsi = Marshal.PtrToStringAnsi(marshaledString); Marshal.FreeHGlobal(marshaledString); using (SecureString ss = CreateSecureString(input)) { IntPtr marshaledSecureString = allocHGlobal ? SecureStringMarshal.SecureStringToGlobalAllocAnsi(ss) : SecureStringMarshal.SecureStringToCoTaskMemAnsi(ss); string actualAnsi = Marshal.PtrToStringAnsi(marshaledSecureString); if (allocHGlobal) { Marshal.FreeHGlobal(marshaledSecureString); } else { Marshal.FreeCoTaskMem(marshaledSecureString); } Assert.Equal(expectedAnsi, actualAnsi); } } [Theory] [InlineData(0, false)] [InlineData(0, true)] [InlineData(1, false)] [InlineData(1, true)] [InlineData(2, false)] [InlineData(2, true)] [InlineData(1000, false)] [InlineData(1000, true)] public static void SecureStringMarshal_Unicode_Roundtrip(int length, bool allocHGlobal) { string input = new string(Enumerable .Range(0, length) .Select(i => (char)('a' + i)) // include non-ASCII chars .ToArray()); IntPtr marshaledString = Marshal.StringToHGlobalUni(input); string expectedAnsi = Marshal.PtrToStringUni(marshaledString); Marshal.FreeHGlobal(marshaledString); using (SecureString ss = CreateSecureString(input)) { IntPtr marshaledSecureString = allocHGlobal ? SecureStringMarshal.SecureStringToGlobalAllocUnicode(ss) : SecureStringMarshal.SecureStringToCoTaskMemUnicode(ss); string actualAnsi = Marshal.PtrToStringUni(marshaledSecureString); if (allocHGlobal) { Marshal.FreeHGlobal(marshaledSecureString); } else { Marshal.FreeCoTaskMem(marshaledSecureString); } Assert.Equal(expectedAnsi, actualAnsi); } } [Fact] public static void GrowAndContract_Small() { var rand = new Random(42); var sb = new StringBuilder(string.Empty); using (SecureString testString = CreateSecureString(string.Empty)) { for (int loop = 0; loop < 3; loop++) { for (int i = 0; i < 100; i++) { char c = (char)('a' + rand.Next(0, 26)); int addPos = rand.Next(0, sb.Length); testString.InsertAt(addPos, c); sb.Insert(addPos, c); AssertEquals(sb.ToString(), testString); } while (sb.Length > 0) { int removePos = rand.Next(0, sb.Length); testString.RemoveAt(removePos); sb.Remove(removePos, 1); AssertEquals(sb.ToString(), testString); } } } } [Fact] public static void Grow_Large() { string starting = CreateString(6000); var sb = new StringBuilder(starting); using (SecureString testString = CreateSecureString(starting)) { for (int i = 0; i < 4000; i++) { char c = (char)('a' + (i % 26)); testString.AppendChar(c); sb.Append(c); } AssertEquals(sb.ToString(), testString); } } private static unsafe void AssertEquals(string expected, SecureString actual) { Assert.Equal(expected, CreateString(actual)); } private static string CreateString(int length) { var sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.Append((char)('a' + (i % 26))); } return sb.ToString(); } // WARNING: // A key value of SecureString is in keeping string data off of the GC heap, such that it can // be reliably cleared when no longer needed. Creating a SecureString from a string or converting // a SecureString to a string diminishes that value. These conversion functions are for testing that // SecureString works, and does not represent a pattern to follow in any non-test situation. private static unsafe SecureString CreateSecureString(string value) { if (string.IsNullOrEmpty(value)) { return new SecureString(); } fixed (char* mychars = value.ToCharArray()) { return new SecureString(mychars, value.Length); } } private static string CreateString(SecureString value) { IntPtr ptr = SecureStringMarshal.SecureStringToGlobalAllocUnicode(value); try { return Marshal.PtrToStringUni(ptr); } finally { Marshal.ZeroFreeGlobalAllocUnicode(ptr); } } } }
//uScript Generated Code - Build 1.0.3018 using UnityEngine; using System.Collections; using System.Collections.Generic; [NodePath("Graphs")] [System.Serializable] [FriendlyName("Untitled", "")] public class push : uScriptLogic { #pragma warning disable 414 GameObject parentGameObject = null; uScript_GUI thisScriptsOnGuiListener = null; bool m_RegisteredForEvents = false; //externally exposed events //external parameters //local nodes System.String local_12_System_String = "push"; UnityEngine.Vector3 local_2_UnityEngine_Vector3 = new Vector3( (float)0, (float)0, (float)0 ); UnityEngine.GameObject local_4_UnityEngine_GameObject = default(UnityEngine.GameObject); UnityEngine.GameObject local_4_UnityEngine_GameObject_previous = null; //owner nodes UnityEngine.GameObject owner_Connection_5 = null; //logic nodes //pointer to script instanced logic node uScriptAct_AddForce logic_uScriptAct_AddForce_uScriptAct_AddForce_1 = new uScriptAct_AddForce( ); UnityEngine.GameObject logic_uScriptAct_AddForce_Target_1 = default(UnityEngine.GameObject); UnityEngine.Vector3 logic_uScriptAct_AddForce_Force_1 = new Vector3( ); System.Single logic_uScriptAct_AddForce_Scale_1 = (float) 10; System.Boolean logic_uScriptAct_AddForce_UseForceMode_1 = (bool) false; UnityEngine.ForceMode logic_uScriptAct_AddForce_ForceModeType_1 = UnityEngine.ForceMode.Force; bool logic_uScriptAct_AddForce_Out_1 = true; //pointer to script instanced logic node uScriptCon_GameObjectHasTag logic_uScriptCon_GameObjectHasTag_uScriptCon_GameObjectHasTag_11 = new uScriptCon_GameObjectHasTag( ); UnityEngine.GameObject logic_uScriptCon_GameObjectHasTag_GameObject_11 = default(UnityEngine.GameObject); System.String[] logic_uScriptCon_GameObjectHasTag_Tag_11 = new System.String[] {}; bool logic_uScriptCon_GameObjectHasTag_HasAllTags_11 = true; bool logic_uScriptCon_GameObjectHasTag_HasTag_11 = true; bool logic_uScriptCon_GameObjectHasTag_MissingTags_11 = true; //event nodes UnityEngine.GameObject event_UnityEngine_GameObject_GameObject_0 = default(UnityEngine.GameObject); UnityEngine.CharacterController event_UnityEngine_GameObject_Controller_0 = default(UnityEngine.CharacterController); UnityEngine.Collider event_UnityEngine_GameObject_Collider_0 = default(UnityEngine.Collider); UnityEngine.Rigidbody event_UnityEngine_GameObject_RigidBody_0 = default(UnityEngine.Rigidbody); UnityEngine.Transform event_UnityEngine_GameObject_Transform_0 = default(UnityEngine.Transform); UnityEngine.Vector3 event_UnityEngine_GameObject_Point_0 = new Vector3( (float)0, (float)0, (float)0 ); UnityEngine.Vector3 event_UnityEngine_GameObject_Normal_0 = new Vector3( (float)0, (float)0, (float)0 ); UnityEngine.Vector3 event_UnityEngine_GameObject_MoveDirection_0 = new Vector3( ); System.Single event_UnityEngine_GameObject_MoveLength_0 = (float) 0; //property nodes //method nodes #pragma warning restore 414 //functions to refresh properties from entities void SyncUnityHooks( ) { SyncEventListeners( ); //if our game object reference was changed then we need to reset event listeners if ( local_4_UnityEngine_GameObject_previous != local_4_UnityEngine_GameObject || false == m_RegisteredForEvents ) { //tear down old listeners local_4_UnityEngine_GameObject_previous = local_4_UnityEngine_GameObject; //setup new listeners } if ( null == owner_Connection_5 || false == m_RegisteredForEvents ) { owner_Connection_5 = parentGameObject; if ( null != owner_Connection_5 ) { { uScript_ProxyController component = owner_Connection_5.GetComponent<uScript_ProxyController>(); if ( null == component ) { component = owner_Connection_5.AddComponent<uScript_ProxyController>(); } if ( null != component ) { component.OnHit += Instance_OnHit_0; } } } } } void RegisterForUnityHooks( ) { SyncEventListeners( ); //if our game object reference was changed then we need to reset event listeners if ( local_4_UnityEngine_GameObject_previous != local_4_UnityEngine_GameObject || false == m_RegisteredForEvents ) { //tear down old listeners local_4_UnityEngine_GameObject_previous = local_4_UnityEngine_GameObject; //setup new listeners } //reset event listeners if needed //this isn't a variable node so it should only be called once per enabling of the script //if it's called twice there would be a double event registration (which is an error) if ( false == m_RegisteredForEvents ) { if ( null != owner_Connection_5 ) { { uScript_ProxyController component = owner_Connection_5.GetComponent<uScript_ProxyController>(); if ( null == component ) { component = owner_Connection_5.AddComponent<uScript_ProxyController>(); } if ( null != component ) { component.OnHit += Instance_OnHit_0; } } } } } void SyncEventListeners( ) { } void UnregisterEventListeners( ) { if ( null != owner_Connection_5 ) { { uScript_ProxyController component = owner_Connection_5.GetComponent<uScript_ProxyController>(); if ( null != component ) { component.OnHit -= Instance_OnHit_0; } } } } public override void SetParent(GameObject g) { parentGameObject = g; logic_uScriptAct_AddForce_uScriptAct_AddForce_1.SetParent(g); logic_uScriptCon_GameObjectHasTag_uScriptCon_GameObjectHasTag_11.SetParent(g); owner_Connection_5 = parentGameObject; } public void Awake() { } public void Start() { SyncUnityHooks( ); m_RegisteredForEvents = true; } public void OnEnable() { RegisterForUnityHooks( ); m_RegisteredForEvents = true; } public void OnDisable() { UnregisterEventListeners( ); m_RegisteredForEvents = false; } public void Update() { //other scripts might have added GameObjects with event scripts //so we need to verify all our event listeners are registered SyncEventListeners( ); } public void OnDestroy() { } void Instance_OnHit_0(object o, uScript_ProxyController.ProxyControllerCollisionEventArgs e) { //fill globals event_UnityEngine_GameObject_GameObject_0 = e.GameObject; event_UnityEngine_GameObject_Controller_0 = e.Controller; event_UnityEngine_GameObject_Collider_0 = e.Collider; event_UnityEngine_GameObject_RigidBody_0 = e.RigidBody; event_UnityEngine_GameObject_Transform_0 = e.Transform; event_UnityEngine_GameObject_Point_0 = e.Point; event_UnityEngine_GameObject_Normal_0 = e.Normal; event_UnityEngine_GameObject_MoveDirection_0 = e.MoveDirection; event_UnityEngine_GameObject_MoveLength_0 = e.MoveLength; //relay event to nodes Relay_OnHit_0( ); } void Relay_OnHit_0() { local_4_UnityEngine_GameObject = event_UnityEngine_GameObject_GameObject_0; { //if our game object reference was changed then we need to reset event listeners if ( local_4_UnityEngine_GameObject_previous != local_4_UnityEngine_GameObject || false == m_RegisteredForEvents ) { //tear down old listeners local_4_UnityEngine_GameObject_previous = local_4_UnityEngine_GameObject; //setup new listeners } } local_2_UnityEngine_Vector3 = event_UnityEngine_GameObject_MoveDirection_0; Relay_In_11(); } void Relay_In_1() { { { { //if our game object reference was changed then we need to reset event listeners if ( local_4_UnityEngine_GameObject_previous != local_4_UnityEngine_GameObject || false == m_RegisteredForEvents ) { //tear down old listeners local_4_UnityEngine_GameObject_previous = local_4_UnityEngine_GameObject; //setup new listeners } } logic_uScriptAct_AddForce_Target_1 = local_4_UnityEngine_GameObject; } { logic_uScriptAct_AddForce_Force_1 = local_2_UnityEngine_Vector3; } { } { } { } } logic_uScriptAct_AddForce_uScriptAct_AddForce_1.In(logic_uScriptAct_AddForce_Target_1, logic_uScriptAct_AddForce_Force_1, logic_uScriptAct_AddForce_Scale_1, logic_uScriptAct_AddForce_UseForceMode_1, logic_uScriptAct_AddForce_ForceModeType_1); //save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested } void Relay_In_11() { { { { //if our game object reference was changed then we need to reset event listeners if ( local_4_UnityEngine_GameObject_previous != local_4_UnityEngine_GameObject || false == m_RegisteredForEvents ) { //tear down old listeners local_4_UnityEngine_GameObject_previous = local_4_UnityEngine_GameObject; //setup new listeners } } logic_uScriptCon_GameObjectHasTag_GameObject_11 = local_4_UnityEngine_GameObject; } { int index = 0; if ( logic_uScriptCon_GameObjectHasTag_Tag_11.Length <= index) { System.Array.Resize(ref logic_uScriptCon_GameObjectHasTag_Tag_11, index + 1); } logic_uScriptCon_GameObjectHasTag_Tag_11[ index++ ] = local_12_System_String; } } logic_uScriptCon_GameObjectHasTag_uScriptCon_GameObjectHasTag_11.In(logic_uScriptCon_GameObjectHasTag_GameObject_11, logic_uScriptCon_GameObjectHasTag_Tag_11); //save off values because, if there are multiple, our relay logic could cause them to change before the next value is tested bool test_0 = logic_uScriptCon_GameObjectHasTag_uScriptCon_GameObjectHasTag_11.HasTag; if ( test_0 == true ) { Relay_In_1(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using System.Collections.Generic; using System.Linq; using Xunit; using BindingFlags = System.Reflection.BindingFlags; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ResultsViewTests : CSharpResultProviderTestBase { // IEnumerable pattern not supported. [Fact] public void IEnumerablePattern() { var source = @"using System.Collections; class C { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } // IEnumerable<T> pattern not supported. [Fact] public void IEnumerableOfTPattern() { var source = @"using System.Collections.Generic; class C<T> { private readonly IEnumerable<T> e; internal C(IEnumerable<T> e) { this.e = e; } public IEnumerator<T> GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } [Fact] public void IEnumerableImplicitImplementation() { var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]"), EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[1]")); } } [Fact] public void IEnumerableOfTImplicitImplementation() { var source = @"using System.Collections; using System.Collections.Generic; struct S<T> : IEnumerable<T> { private readonly IEnumerable<T> e; internal S(IEnumerable<T> e) { this.e = e; } public IEnumerator<T> GetEnumerator() { return this.e.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("S`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{S<int>}", "S<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]"), EvalResult("[1]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[1]")); } } [Fact] public void IEnumerableExplicitImplementation() { var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } IEnumerator IEnumerable.GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]"), EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[1]")); } } [Fact] public void IEnumerableOfTExplicitImplementation() { var source = @"using System.Collections; using System.Collections.Generic; class C<T> : IEnumerable<T> { private readonly IEnumerable<T> e; internal C(IEnumerable<T> e) { this.e = e; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.e.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult("[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]"), EvalResult("[1]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[1]")); } } // Results View not supported for // IEnumerator implementation. [Fact] public void IEnumerator() { var source = @"using System; using System.Collections; using System.Collections.Generic; class C : IEnumerator<int> { private int[] c = new[] { 1, 2, 3 }; private int i = 0; object IEnumerator.Current { get { return this.c[this.i]; } } int IEnumerator<int>.Current { get { return this.c[this.i]; } } bool IEnumerator.MoveNext() { this.i++; return this.i < this.c.Length; } void IEnumerator.Reset() { this.i = 0; } void IDisposable.Dispose() { } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "System.Collections.Generic.IEnumerator<int>.Current", "1", "int", "((System.Collections.Generic.IEnumerator<int>)o).Current", DkmEvaluationResultFlags.ReadOnly), EvalResult( "System.Collections.IEnumerator.Current", "1", "object {int}", "((System.Collections.IEnumerator)o).Current", DkmEvaluationResultFlags.ReadOnly), EvalResult("c", "{int[3]}", "int[]", "o.c", DkmEvaluationResultFlags.Expandable), EvalResult("i", "0", "int", "o.i")); } } [Fact] public void Overrides() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A : IEnumerable<object> { public virtual IEnumerator<object> GetEnumerator() { yield return 0; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B1 : A { public override IEnumerator<object> GetEnumerator() { yield return 1; } } class B2 : A, IEnumerable<int> { public new IEnumerator<int> GetEnumerator() { yield return 2; } } class B3 : A { public new IEnumerable<int> GetEnumerator() { yield return 3; } } class B4 : A { } class C { A _1 = new B1(); A _2 = new B2(); A _3 = new B3(); A _4 = new B4(); }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "{B1}", "A {B1}", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{B2}", "A {B2}", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{B3}", "A {B3}", "o._3", DkmEvaluationResultFlags.Expandable), EvalResult("_4", "{B4}", "A {B4}", "o._4", DkmEvaluationResultFlags.Expandable)); // A _1 = new B1(); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._1, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._1).Items[0]")); // A _2 = new B2(); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._2, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o._2).Items[0]")); // A _3 = new B3(); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._3, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._3).Items[0]")); // A _4 = new B4(); moreChildren = GetChildren(children[3]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._4, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._4).Items[0]")); } } /// <summary> /// Include Results View on base types /// (matches legacy EE behavior). /// </summary> [Fact] public void BaseTypes() { var source = @"using System.Collections; using System.Collections.Generic; class A1 { } class B1 : A1, IEnumerable { public IEnumerator GetEnumerator() { yield return 0; } } class A2 { public IEnumerator GetEnumerator() { yield return 1; } } class B2 : A2, IEnumerable<object> { IEnumerator<object> IEnumerable<object>.GetEnumerator() { yield return 2; } } struct S : IEnumerable { public IEnumerator GetEnumerator() { yield return 3; } } class C { A1 _1 = new B1(); B2 _2 = new B2(); System.ValueType _3 = new S(); }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "{B1}", "A1 {B1}", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{B2}", "B2", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{S}", "System.ValueType {S}", "o._3", DkmEvaluationResultFlags.Expandable)); // A1 _1 = new B1(); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._1, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); Verify(GetChildren(moreChildren[0]), EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o._1).Items[0]")); // B2 _2 = new B2(); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._2, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); Verify(GetChildren(moreChildren[0]), EvalResult("[0]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._2).Items[0]")); // System.ValueType _3 = new S(); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._3, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); Verify(GetChildren(moreChildren[0]), EvalResult("[0]", "3", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o._3).Items[0]")); } } [Fact] public void Nullable() { var source = @"using System; using System.Collections; using System.Collections.Generic; struct S : IEnumerable<object> { internal readonly object[] c; internal S(object[] c) { this.c = c; } public IEnumerator<object> GetEnumerator() { foreach (var o in this.c) { yield return o; } } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class C { S? F = new S(new object[] { null }); }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{S}", "S?", "o.F", DkmEvaluationResultFlags.Expandable)); children = GetChildren(children[0]); Verify(children, EvalResult("c", "{object[1]}", "object[]", "o.F.c", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o.F, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[1]); Verify(children, EvalResult( "[0]", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<object>(o.F).Items[0]")); } } [Fact] public void ConstructedType() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A<T> : IEnumerable<T> { private readonly T[] items; internal A(T[] items) { this.items = items; } public IEnumerator<T> GetEnumerator() { foreach (var item in items) { yield return item; } } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B { internal object F; } class C : A<B> { internal C() : base(new[] { new B() }) { } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "items", "{B[1]}", "B[]", "o.items", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly), EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var moreChildren = GetChildren(children[1]); Verify(moreChildren, // The legacy EE treats the Items elements as readonly, but since // Items is a T[], we treat the elements as read/write. However, Items // is not updated when modifying elements so this is harmless. EvalResult( "[0]", "{B}", "B", "new System.Linq.SystemCore_EnumerableDebugView<B>(o).Items[0]", DkmEvaluationResultFlags.Expandable)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("F", "null", "object", "(new System.Linq.SystemCore_EnumerableDebugView<B>(o).Items[0]).F")); } } /// <summary> /// System.Array should not have Results View. /// </summary> [Fact] public void Array() { var source = @"using System; using System.Collections; class C { char[] _1 = new char[] { '1' }; Array _2 = new char[] { '2' }; IEnumerable _3 = new char[] { '3' }; }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "{char[1]}", "char[]", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{char[1]}", "System.Array {char[]}", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{char[1]}", "System.Collections.IEnumerable {char[]}", "o._3", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[0]), EvalResult("[0]", "49 '1'", "char", "o._1[0]", editableValue: "'1'")); Verify(GetChildren(children[1]), EvalResult("[0]", "50 '2'", "char", "((char[])o._2)[0]", editableValue: "'2'")); children = GetChildren(children[2]); Verify(children, EvalResult("[0]", "51 '3'", "char", "((char[])o._3)[0]", editableValue: "'3'")); } } /// <summary> /// String should not have Results View. /// </summary> [Fact] public void String() { var source = @"using System.Collections; using System.Collections.Generic; class C { string _1 = ""1""; object _2 = ""2""; IEnumerable _3 = ""3""; IEnumerable<char> _4 = ""4""; }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_1", "\"1\"", "string", "o._1", DkmEvaluationResultFlags.RawString, editableValue: "\"1\""), EvalResult("_2", "\"2\"", "object {string}", "o._2", DkmEvaluationResultFlags.RawString, editableValue: "\"2\""), EvalResult("_3", "\"3\"", "System.Collections.IEnumerable {string}", "o._3", DkmEvaluationResultFlags.RawString, editableValue: "\"3\""), EvalResult("_4", "\"4\"", "System.Collections.Generic.IEnumerable<char> {string}", "o._4", DkmEvaluationResultFlags.RawString, editableValue: "\"4\"")); } } [WorkItem(1006160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1006160")] [Fact] public void MultipleImplementations_DifferentImplementors() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A<T> : IEnumerable<T> { IEnumerator<T> IEnumerable<T>.GetEnumerator() { yield return default(T); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B1 : A<object>, IEnumerable<int> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield return 1; } } class B2 : A<int>, IEnumerable<object> { IEnumerator<object> IEnumerable<object>.GetEnumerator() { yield return null; } } class B3 : A<object>, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { yield return 3; } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); // class B1 : A<object>, IEnumerable<int> var type = assembly.GetType("B1"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B1}", "B1", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]")); // class B2 : A<int>, IEnumerable<object> type = assembly.GetType("B2"); value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B2}", "B2", "o", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<object>(o).Items[0]")); // class B3 : A<object>, IEnumerable type = assembly.GetType("B3"); value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B3}", "B3", "o", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<object>(o).Items[0]")); } } [Fact] public void MultipleImplementations_SameImplementor() { var source = @"using System; using System.Collections; using System.Collections.Generic; class A : IEnumerable<int>, IEnumerable<string> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield return 1; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield return null; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class B : IEnumerable<string>, IEnumerable<int> { IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield return null; } IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield return 1; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); // class A : IEnumerable<int>, IEnumerable<string> var type = assembly.GetType("A"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("a", value); Verify(evalResult, EvalResult("a", "{A}", "A", "a", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "a, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(a).Items[0]")); // class B : IEnumerable<string>, IEnumerable<int> type = assembly.GetType("B"); value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); evalResult = FormatResult("b", value); Verify(evalResult, EvalResult("b", "{B}", "B", "b", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "b, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalResult( "[0]", "null", "string", "new System.Linq.SystemCore_EnumerableDebugView<string>(b).Items[0]")); } } /// <summary> /// Types with [DebuggerTypeProxy] should not have Results View. /// </summary> [Fact] public void DebuggerTypeProxy() { var source = @"using System.Collections; using System.Diagnostics; public class P : IEnumerable { private readonly C c; public P(C c) { this.c = c; } public IEnumerator GetEnumerator() { return this.c.GetEnumerator(); } public int Length { get { return this.c.o.Length; } } } [DebuggerTypeProxy(typeof(P))] public class C : IEnumerable { internal readonly object[] o; public C(object[] o) { this.o = o; } public IEnumerator GetEnumerator() { return this.o.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new object[] { new object[] { string.Empty } }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Length", "1", "int", "new P(o).Length", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[1]); Verify(children, EvalResult("o", "{object[1]}", "object[]", "o.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } /// <summary> /// Do not expose Results View if the proxy type is missing. /// </summary> [Fact] public void MissingProxyType() { var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = new[] { assembly }; using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); } } /// <summary> /// Proxy type not in System.Core.dll. /// </summary> [Fact] public void MissingProxyType_SystemCore() { // "System.Core.dll" var source0 = ""; var compilation0 = CSharpTestBase.CreateStandardCompilation(source0, assemblyName: "system.core"); var assembly0 = ReflectionUtilities.Load(compilation0.EmitToArray()); var source = @"using System.Collections; class C : IEnumerable { private readonly IEnumerable e; internal C(IEnumerable e) { this.e = e; } public IEnumerator GetEnumerator() { return this.e.GetEnumerator(); } }"; var assembly = GetAssembly(source); var assemblies = new[] { assembly0, assembly }; using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(new[] { 1, 2 }), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); // Verify the module was found but ResolveTypeName failed. var module = runtime.Modules.Single(m => m.Assembly == assembly0); Assert.Equal(module.ResolveTypeNameFailures, 1); } } /// <summary> /// Report "Enumeration yielded no results" when /// GetEnumerator returns an empty collection or null. /// </summary> [Fact] public void GetEnumeratorEmptyOrNull() { var source = @"using System; using System.Collections; using System.Collections.Generic; // IEnumerable returns empty collection. class C0 : IEnumerable { public IEnumerator GetEnumerator() { yield break; } } // IEnumerable<T> returns empty collection. class C1<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { yield break; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } // IEnumerable returns null. class C2 : IEnumerable { public IEnumerator GetEnumerator() { return null; } } // IEnumerable<T> returns null. class C3<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } class C { C0 _0 = new C0(); C1<object> _1 = new C1<object>(); C2 _2 = new C2(); C3<object> _3 = new C3<object>(); }"; using (new EnsureEnglishUICulture()) { var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("_0", "{C0}", "C0", "o._0", DkmEvaluationResultFlags.Expandable), EvalResult("_1", "{C1<object>}", "C1<object>", "o._1", DkmEvaluationResultFlags.Expandable), EvalResult("_2", "{C2}", "C2", "o._2", DkmEvaluationResultFlags.Expandable), EvalResult("_3", "{C3<object>}", "C3<object>", "o._3", DkmEvaluationResultFlags.Expandable)); // C0 _0 = new C0(); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._0, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); // C1<object> _1 = new C1<object>(); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._1, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); // C2 _2 = new C2(); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._2, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); // C3<object> _3 = new C3<object>(); moreChildren = GetChildren(children[3]); Verify(moreChildren, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o._3, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult( "Empty", "\"Enumeration yielded no results\"", "string", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString)); } } } /// <summary> /// Do not instantiate proxy type for null IEnumerable. /// </summary> [WorkItem(1009646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1009646")] [Fact] public void IEnumerableNull() { var source = @"using System.Collections; using System.Collections.Generic; interface I : IEnumerable { } class C { IEnumerable<char> E = null; I F = null; string S = null; }"; var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("E", "null", "System.Collections.Generic.IEnumerable<char>", "o.E"), EvalResult("F", "null", "I", "o.F"), EvalResult("S", "null", "string", "o.S")); } } [Fact] public void GetEnumeratorException() { var source = @"using System; using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { throw new NotImplementedException(); } }"; using (new EnsureEnglishUICulture()) { var assembly = GetAssembly(source); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children[6], EvalResult("Message", "\"The method or operation is not implemented.\"", "string", null, DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly)); } } } [Fact] [WorkItem(1145125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1145125")] [WorkItem(5666, "https://github.com/dotnet/roslyn/issues/5666")] public void GetEnumerableException() { var source = @"using System; using System.Collections; class E : Exception, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { yield return 1; } } class C { internal IEnumerable P { get { throw new NotImplementedException(); } } internal IEnumerable Q { get { throw new E(); } } }"; using (new EnsureEnglishUICulture()) { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "P", "'o.P' threw an exception of type 'System.NotImplementedException'", "System.Collections.IEnumerable {System.NotImplementedException}", "o.P", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.ExceptionThrown), EvalResult( "Q", "'o.Q' threw an exception of type 'E'", "System.Collections.IEnumerable {E}", "o.Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.ExceptionThrown)); children = GetChildren(children[1]); Verify(children[6], EvalResult( "Message", "\"Exception of type 'E' was thrown.\"", "string", null, DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly)); } } } [Fact] public void GetEnumerableError() { var source = @"using System.Collections; class C { bool f; internal ArrayList P { get { while (!this.f) { } return new ArrayList(); } } }"; DkmClrRuntimeInstance runtime = null; GetMemberValueDelegate getMemberValue = (v, m) => (m == "P") ? CreateErrorValue(runtime.GetType(typeof(System.Collections.ArrayList)), "Function evaluation timed out") : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext); var evalResult = FormatResult("o.P", memberValue); Verify(evalResult, EvalFailedResult("o.P", "Function evaluation timed out", "System.Collections.ArrayList", "o.P")); } } /// <summary> /// If evaluation of the proxy Items property returns an error /// (say, evaluation of the enumerable requires func-eval and /// either func-eval is disabled or we're debugging a .dmp), /// we should include a row that reports the error rather than /// having an empty expansion (since the container Items property /// is [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]). /// Note, the native EE has an empty expansion when .dmp debugging. /// </summary> [WorkItem(1043746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1043746")] [Fact] public void GetProxyPropertyValueError() { var source = @"using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 1; } }"; DkmClrRuntimeInstance runtime = null; GetMemberValueDelegate getMemberValue = (v, m) => (m == "Items") ? CreateErrorValue(runtime.GetType(typeof(object)).MakeArrayType(), string.Format("Unable to evaluate '{0}'", m)) : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult( "Results View", "Expanding the Results View will enumerate the IEnumerable", "", "o, results", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(children[0]); Verify(children, EvalFailedResult("Error", "Unable to evaluate 'Items'", flags: DkmEvaluationResultFlags.None)); } } /// <summary> /// Root-level synthetic values declared as IEnumerable or /// IEnumerable&lt;T&gt; should be expanded directly /// without intermediate "Results View" row. /// </summary> [WorkItem(1114276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114276")] [Fact] public void SyntheticIEnumerable() { var source = @"using System.Collections; using System.Collections.Generic; class C { IEnumerable P { get { yield return 1; yield return 2; } } IEnumerable<int> Q { get { yield return 3; } } IEnumerable R { get { return null; } } IEnumerable S { get { return string.Empty; } } IEnumerable<int> T { get { return new int[] { 4, 5 }; } } IList<int> U { get { return new List<int>(new int[] { 6 }); } } }"; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.UnderlyingType.Instantiate(); // IEnumerable var evalResult = FormatPropertyValue(runtime, value, "P"); Verify(evalResult, EvalResult( "P", "{C.<get_P>d__1}", "System.Collections.IEnumerable {C.<get_P>d__1}", "P", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(P).Items[0]"), EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(P).Items[1]")); // IEnumerable<int> evalResult = FormatPropertyValue(runtime, value, "Q"); Verify(evalResult, EvalResult( "Q", "{C.<get_Q>d__3}", "System.Collections.Generic.IEnumerable<int> {C.<get_Q>d__3}", "Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Method)); children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "3", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(Q).Items[0]")); // null (unchanged) evalResult = FormatPropertyValue(runtime, value, "R"); Verify(evalResult, EvalResult( "R", "null", "System.Collections.IEnumerable", "R", DkmEvaluationResultFlags.None)); // string (unchanged) evalResult = FormatPropertyValue(runtime, value, "S"); Verify(evalResult, EvalResult( "S", "\"\"", "System.Collections.IEnumerable {string}", "S", DkmEvaluationResultFlags.RawString, DkmEvaluationResultCategory.Other, editableValue: "\"\"")); // array (unchanged) evalResult = FormatPropertyValue(runtime, value, "T"); Verify(evalResult, EvalResult( "T", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "T", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "4", "int", "((int[])T)[0]"), EvalResult("[1]", "5", "int", "((int[])T)[1]")); // IList<int> declared type (unchanged) evalResult = FormatPropertyValue(runtime, value, "U"); Verify(evalResult, EvalResult( "U", "Count = 1", "System.Collections.Generic.IList<int> {System.Collections.Generic.List<int>}", "U", DkmEvaluationResultFlags.Expandable)); children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "6", "int", "new System.Collections.Generic.Mscorlib_CollectionDebugView<int>(U).Items[0]"), EvalResult("Raw View", null, "", "U, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } } [WorkItem(4098, "https://github.com/dotnet/roslyn/issues/4098")] [Fact] public void IEnumerableOfAnonymousType() { var code = @"using System.Collections.Generic; using System.Linq; class C { static void M(List<int> list) { var result = from x in list from y in list where x > 0 select new { x, y }; } }"; var assembly = GetAssembly(code); var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly); using (ReflectionUtilities.LoadAssemblies(assemblies)) { var runtime = new DkmClrRuntimeInstance(assemblies); var anonymousType = assembly.GetType("<>f__AnonymousType0`2").MakeGenericType(typeof(int), typeof(int)); var type = typeof(Enumerable).GetNestedType("WhereSelectEnumerableIterator`2", BindingFlags.NonPublic).MakeGenericType(anonymousType, anonymousType); var displayClass = assembly.GetType("C+<>c"); var instance = displayClass.Instantiate(); var ctor = type.GetConstructors().Single(); var parameters = ctor.GetParameters(); var listType = typeof(List<>).MakeGenericType(anonymousType); var source = listType.Instantiate(); listType.GetMethod("Add").Invoke(source, new[] { anonymousType.Instantiate(1, 1) }); var predicate = Delegate.CreateDelegate(parameters[1].ParameterType, instance, displayClass.GetMethod("<M>b__0_2", BindingFlags.Instance | BindingFlags.NonPublic)); var selector = Delegate.CreateDelegate(parameters[2].ParameterType, instance, displayClass.GetMethod("<M>b__0_3", BindingFlags.Instance | BindingFlags.NonPublic)); var value = CreateDkmClrValue( value: type.Instantiate(source, predicate, selector), type: runtime.GetType((TypeImpl)type)); var expr = "from x in my_list from y in my_list where x > 0 select new { x, y }"; var typeName = "System.Linq.Enumerable.WhereSelectEnumerableIterator<<>f__AnonymousType0<int, int>, <>f__AnonymousType0<int, int>>"; var name = expr + ";"; var evalResult = FormatResult(name, value); Verify(evalResult, EvalResult(name, $"{{{typeName}}}", typeName, expr, DkmEvaluationResultFlags.Expandable)); var resultsViewRow = GetChildren(evalResult).Last(); Verify(GetChildren(resultsViewRow), EvalResult( "[0]", "{{ x = 1, y = 1 }}", "<>f__AnonymousType0<int, int>", null, DkmEvaluationResultFlags.Expandable)); name = expr + ", results"; evalResult = FormatResult(name, value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ResultsOnly)); Verify(evalResult, EvalResult(name, $"{{{typeName}}}", typeName, name, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(evalResult), EvalResult( "[0]", "{{ x = 1, y = 1 }}", "<>f__AnonymousType0<int, int>", null, DkmEvaluationResultFlags.Expandable)); } } private DkmEvaluationResult FormatPropertyValue(DkmClrRuntimeInstance runtime, object value, string propertyName) { var propertyInfo = value.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var propertyValue = propertyInfo.GetValue(value); var propertyType = runtime.GetType(propertyInfo.PropertyType); var valueType = (propertyValue == null) ? propertyType : runtime.GetType(propertyValue.GetType()); return FormatResult( propertyName, CreateDkmClrValue(propertyValue, type: valueType, valueFlags: DkmClrValueFlags.Synthetic), declaredType: propertyType); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Graphics; namespace EM_Sim { class Camera { private float lookSensitivityFactor; private float moveSpeedFactor; private float cameraYaw; private float cameraPitch; private Vector3 cameraPosition; private MouseState mouseState; private Matrix projectionMatrix; private bool printCameraInfo = false; private readonly float nearDistanceDefault = 0.1f; private readonly float farDistanceDefault = 1000.0f; private GraphicsDevice device; private bool mouseLocked = true; private int frames = 0; #region Constructors public Camera(GraphicsDevice deviceTemp) { cameraPosition = Vector3.Zero; cameraYaw = 0; cameraPitch = 0; lookSensitivityFactor = 0.1f; moveSpeedFactor = 30.0f; device = deviceTemp; float ratio = (float)device.Viewport.Width / (float)device.Viewport.Height; SetProjMatrix(MathHelper.PiOver4, nearDistanceDefault, farDistanceDefault); printCameraInfo = false; } public Camera(Vector3 pos, float yaw, float pitch, float sens, float speed, GraphicsDevice deviceTemp) { cameraPosition = pos; cameraYaw = yaw; cameraPitch = pitch; device = deviceTemp; float ratio = (float)device.Viewport.Width / (float)device.Viewport.Height; SetProjMatrix(MathHelper.ToRadians(60.0f), nearDistanceDefault, farDistanceDefault); lookSensitivityFactor = sens; moveSpeedFactor = speed; Mouse.SetPosition(device.Viewport.Width / 2, device.Viewport.Height / 2); mouseState = Mouse.GetState(); printCameraInfo = false; } public Camera(Vector3 pos, float yaw, float pitch, float fov, float closeDistance, float farDistance, float sens, float speed, GraphicsDevice deviceTemp) { cameraPosition = pos; cameraYaw = yaw; cameraPitch = pitch; device = deviceTemp; float ratio = (float)device.Viewport.Width / (float)device.Viewport.Height; SetProjMatrix(fov, closeDistance, farDistance); lookSensitivityFactor = 0.1f; moveSpeedFactor = speed; printCameraInfo = false; } #endregion #region Camera Update public void UpdateCam(float scaleSpeed) { if ((CheckKey(Keys.LeftControl) || CheckKey(Keys.RightControl)) && frames == 0) { mouseLocked = !mouseLocked; frames = 30; } float moveSpeed = moveSpeedFactor * scaleSpeed; float turnSpeed = lookSensitivityFactor * scaleSpeed; MoveCam(CheckMoveVector(moveSpeed)); RotateCam(turnSpeed); if (printCameraInfo) { Console.WriteLine("Yaw: " + cameraYaw + " pitch: " + cameraPitch); //Console.WriteLine("Pos: " + cameraPosition); } if (frames > 0) frames--; } private Vector3 CheckMoveVector(float moveSpeed) { Vector3 movement = new Vector3(0, 0, 0); // X Movement if (CheckKey(Keys.W)) { movement += new Vector3(0, 0, -moveSpeed); } if (CheckKey(Keys.S)) { movement += new Vector3(0, 0, moveSpeed); } // Z Movement if (CheckKey(Keys.A)) { movement += new Vector3(-moveSpeed, 0, 0); } if (CheckKey(Keys.D)) { movement += new Vector3(moveSpeed, 0, 0); } //Console. return movement; } private void MoveCam(Vector3 move) { Matrix rot = Matrix.CreateRotationX(cameraPitch) * Matrix.CreateRotationY(cameraYaw); move = Vector3.Transform(move, rot); cameraPosition += move; } private void RotateCam(float speed) { if (mouseLocked) { MouseState currentState = Mouse.GetState(); if ((currentState.X != mouseState.X) || (currentState.Y != mouseState.Y)) { int dx = mouseState.X - currentState.X; int dy = mouseState.Y - currentState.Y; cameraYaw += dx * speed; cameraPitch += dy * speed; } Mouse.SetPosition(device.Viewport.Width / 2, device.Viewport.Height / 2); mouseState = Mouse.GetState(); } } #endregion #region Get Statements public Matrix GetViewProjMatrix() { Vector3 lookAt = new Vector3(0, 0, -1); lookAt = Vector3.Transform(lookAt, Matrix.CreateRotationX(cameraPitch)); lookAt = Vector3.Transform(lookAt, Matrix.CreateRotationY(cameraYaw)); Matrix viewMatrix = Matrix.CreateLookAt( cameraPosition, cameraPosition + lookAt, Vector3.Up ); return viewMatrix * projectionMatrix; } public Matrix GetViewMatrix() { Vector3 lookAt = new Vector3(0, 0, -1); lookAt = Vector3.Transform(lookAt, Matrix.CreateRotationX(cameraPitch)); lookAt = Vector3.Transform(lookAt, Matrix.CreateRotationY(cameraYaw)); Matrix viewMatrix = Matrix.CreateLookAt( cameraPosition, cameraPosition + lookAt, Vector3.Up ); return viewMatrix; } public Matrix GetProjMatrix() { return projectionMatrix; } public Vector3 GetPos() { return cameraPosition; } public float GetYaw() { return cameraYaw; } public float GetPitch() { return cameraPitch; } public float GetSensitivity() { return lookSensitivityFactor; } public float GetSpeed() { return moveSpeedFactor; } public Vector3 GetLookAt() { Vector3 lookAt = new Vector3(0, 0, -1); lookAt = Vector3.Transform(lookAt, Matrix.CreateRotationX(cameraPitch)); lookAt = Vector3.Transform(lookAt, Matrix.CreateRotationY(cameraYaw)); return cameraPosition + lookAt; } #endregion #region Set Statements public void SetProjMatrix(float fov, float nearDistance, float farDistance) { float ratio = (float)device.Viewport.Width / (float)device.Viewport.Height; projectionMatrix = Matrix.CreatePerspectiveFieldOfView( fov, ratio, nearDistance, farDistance ); } public void SetProjMatrix(Matrix newProjMatrix) { projectionMatrix = newProjMatrix; } public void SetSensitivity(float sens) { lookSensitivityFactor = sens; } public void SetMoveSpeed(float speed) { moveSpeedFactor = speed; } public void SetPrintInfo(bool value) { printCameraInfo = value; } public void SetHeight(float newHeight) { cameraPosition.Y = newHeight; } #endregion #region Key Checker private bool CheckKey(Keys key) { KeyboardState state = Keyboard.GetState(); if (state.IsKeyDown(key)) return true; else return false; } #endregion } }
namespace EthanYoung.PersonalWebsite.ImageManipulation { public enum ImagePropertyType { PropertyTagTypeByte =1, PropertyTagTypeASCII =2, PropertyTagTypeShort =3, PropertyTagTypeLong =4, PropertyTagTypeRational =5, PropertyTagTypeUndefined =7, PropertyTagTypeSLONG =9, PropertyTagTypeSRational =10, } public enum ImagePropertyID { // Added Manually // The following items correspond to the EXIF IDs that // are set by windows file explorer when edited in the // properties dialog summary page. FileExplorerTitle =0x9c9b, FileExplorerSubject =0x9c9f, FileExplorerKeywords=0x9c9e, FileExplorerComments=0x9c9c, // Taken from GDIConstants.h ExifIFD =0x8769, GpsIFD =0x8825, NewSubfileType =0x00FE, SubfileType =0x00FF, ImageWidth =0x0100, ImageHeight =0x0101, BitsPerSample =0x0102, Compression =0x0103, PhotometricInterp =0x0106, ThreshHolding =0x0107, CellWidth =0x0108, CellHeight =0x0109, FillOrder =0x010A, DocumentName =0x010D, ImageDescription =0x010E, EquipMake =0x010F, EquipModel =0x0110, StripOffsets =0x0111, Orientation =0x0112, SamplesPerPixel =0x0115, RowsPerStrip =0x0116, StripBytesCount =0x0117, MinSampleValue =0x0118, MaxSampleValue =0x0119, XResolution =0x011A, // Image resolution in width direction, YResolution =0x011B, // Image resolution in height direction, PlanarConfig =0x011C, // Image data arrangement, PageName =0x011D, XPosition =0x011E, YPosition =0x011F, FreeOffset =0x0120, FreeByteCounts =0x0121, GrayResponseUnit =0x0122, GrayResponseCurve =0x0123, T4Option =0x0124, T6Option =0x0125, ResolutionUnit =0x0128, // Unit of X and Y resolution, PageNumber =0x0129, TransferFuncition =0x012D, SoftwareUsed =0x0131, DateTime =0x0132, Artist =0x013B, HostComputer =0x013C, Predictor =0x013D, WhitePoint =0x013E, PrimaryChromaticities =0x013F, ColorMap =0x0140, HalftoneHints =0x0141, TileWidth =0x0142, TileLength =0x0143, TileOffset =0x0144, TileByteCounts =0x0145, InkSet =0x014C, InkNames =0x014D, NumberOfInks =0x014E, DotRange =0x0150, TargetPrinter =0x0151, ExtraSamples =0x0152, SampleFormat =0x0153, SMinSampleValue =0x0154, SMaxSampleValue =0x0155, TransferRange =0x0156, JPEGProc =0x0200, JPEGInterFormat =0x0201, JPEGInterLength =0x0202, JPEGRestartInterval =0x0203, JPEGLosslessPredictors =0x0205, JPEGPointTransforms =0x0206, JPEGQTables =0x0207, JPEGDCTables =0x0208, JPEGACTables =0x0209, YCbCrCoefficients =0x0211, YCbCrSubsampling =0x0212, YCbCrPositioning =0x0213, REFBlackWhite =0x0214, ICCProfile =0x8773, // This TAG is defined by ICC, // for embedded ICC in TIFF, Gamma =0x0301, ICCProfileDescriptor =0x0302, SRGBRenderingIntent =0x0303, ImageTitle =0x0320, Copyright =0x8298, // Extra TAGs (Like Adobe Image Information tags etc.) ResolutionXUnit =0x5001, ResolutionYUnit =0x5002, ResolutionXLengthUnit =0x5003, ResolutionYLengthUnit =0x5004, PrintFlags =0x5005, PrintFlagsVersion =0x5006, PrintFlagsCrop =0x5007, PrintFlagsBleedWidth =0x5008, PrintFlagsBleedWidthScale =0x5009, HalftoneLPI =0x500A, HalftoneLPIUnit =0x500B, HalftoneDegree =0x500C, HalftoneShape =0x500D, HalftoneMisc =0x500E, HalftoneScreen =0x500F, JPEGQuality =0x5010, GridSize =0x5011, ThumbnailFormat =0x5012, // 1 = JPEG, 0 = RAW RGB, ThumbnailWidth =0x5013, ThumbnailHeight =0x5014, ThumbnailColorDepth =0x5015, ThumbnailPlanes =0x5016, ThumbnailRawBytes =0x5017, ThumbnailSize =0x5018, ThumbnailCompressedSize =0x5019, ColorTransferFunction =0x501A, ThumbnailData =0x501B, // RAW thumbnail bits in, // JPEG format or RGB format, // depends on, // ThumbnailFormat, // Thumbnail related TAGs, ThumbnailImageWidth =0x5020, // Thumbnail width, ThumbnailImageHeight =0x5021, // Thumbnail height, ThumbnailBitsPerSample =0x5022, // Number of bits per, // component, ThumbnailCompression =0x5023, // Compression Scheme, ThumbnailPhotometricInterp =0x5024, // Pixel composition, ThumbnailImageDescription =0x5025, // Image Tile, ThumbnailEquipMake =0x5026, // Manufacturer of Image, // Input equipment, ThumbnailEquipModel =0x5027, // Model of Image input, // equipment, ThumbnailStripOffsets =0x5028, // Image data location, ThumbnailOrientation =0x5029, // Orientation of image, ThumbnailSamplesPerPixel =0x502A, // Number of components, ThumbnailRowsPerStrip =0x502B, // Number of rows per strip, ThumbnailStripBytesCount =0x502C, // Bytes per compressed, // strip, ThumbnailResolutionX =0x502D, // Resolution in width, // direction, ThumbnailResolutionY =0x502E, // Resolution in height, // direction, ThumbnailPlanarConfig =0x502F, // Image data arrangement, ThumbnailResolutionUnit =0x5030, // Unit of X and Y, // Resolution, ThumbnailTransferFunction =0x5031, // Transfer function, ThumbnailSoftwareUsed =0x5032, // Software used, ThumbnailDateTime =0x5033, // File change date and, // time, ThumbnailArtist =0x5034, // Person who created the, // image, ThumbnailWhitePoint =0x5035, // White point chromaticity, ThumbnailPrimaryChromaticities =0x5036, // Chromaticities of, // primaries, ThumbnailYCbCrCoefficients =0x5037, // Color space transforma- // tion coefficients, ThumbnailYCbCrSubsampling =0x5038, // Subsampling ratio of Y, // to C, ThumbnailYCbCrPositioning =0x5039, // Y and C position, ThumbnailRefBlackWhite =0x503A, // Pair of black and white, // reference values, ThumbnailCopyRight =0x503B, // CopyRight holder, LuminanceTable =0x5090, ChrominanceTable =0x5091, FrameDelay =0x5100, LoopCount =0x5101, PixelUnit =0x5110, // Unit specifier for pixel/unit, PixelPerUnitX =0x5111, // Pixels per unit in X, PixelPerUnitY =0x5112, // Pixels per unit in Y, PaletteHistogram =0x5113, // Palette histogram, // EXIF specific tag, ExifExposureTime =0x829A, ExifFNumber =0x829D, ExifExposureProg =0x8822, ExifSpectralSense =0x8824, ExifISOSpeed =0x8827, ExifOECF =0x8828, ExifVer =0x9000, ExifDTOrig =0x9003, // Date & time of original, ExifDTDigitized =0x9004, // Date & time of digital data generation, ExifCompConfig =0x9101, ExifCompBPP =0x9102, ExifShutterSpeed =0x9201, ExifAperture =0x9202, ExifBrightness =0x9203, ExifExposureBias =0x9204, ExifMaxAperture =0x9205, ExifSubjectDist =0x9206, ExifMeteringMode =0x9207, ExifLightSource =0x9208, ExifFlash =0x9209, ExifFocalLength =0x920A, ExifMakerNote =0x927C, ExifUserComment =0x9286, ExifDTSubsec =0x9290, // Date & Time subseconds, ExifDTOrigSS =0x9291, // Date & Time original subseconds, ExifDTDigSS =0x9292, // Date & TIme digitized subseconds, ExifFPXVer =0xA000, ExifColorSpace =0xA001, ExifPixXDim =0xA002, ExifPixYDim =0xA003, ExifRelatedWav =0xA004, // related sound file, ExifInterop =0xA005, ExifFlashEnergy =0xA20B, ExifSpatialFR =0xA20C, // Spatial Frequency Response, ExifFocalXRes =0xA20E, // Focal Plane X Resolution, ExifFocalYRes =0xA20F, // Focal Plane Y Resolution, ExifFocalResUnit =0xA210, // Focal Plane Resolution Unit, ExifSubjectLoc =0xA214, ExifExposureIndex =0xA215, ExifSensingMethod =0xA217, ExifFileSource =0xA300, ExifSceneType =0xA301, ExifCfaPattern =0xA302, GpsVer =0x0000, GpsLatitudeRef =0x0001, GpsLatitude =0x0002, GpsLongitudeRef =0x0003, GpsLongitude =0x0004, GpsAltitudeRef =0x0005, GpsAltitude =0x0006, GpsGpsTime =0x0007, GpsGpsSatellites =0x0008, GpsGpsStatus =0x0009, GpsGpsMeasureMode =0x00A, GpsGpsDop =0x000B, // Measurement precision, GpsSpeedRef =0x000C, GpsSpeed =0x000D, GpsTrackRef =0x000E, GpsTrack =0x000F, GpsImgDirRef =0x0010, GpsImgDir =0x0011, GpsMapDatum =0x0012, GpsDestLatRef =0x0013, GpsDestLat =0x0014, GpsDestLongRef =0x0015, GpsDestLong =0x0016, GpsDestBearRef =0x0017, GpsDestBear =0x0018, GpsDestDistRef =0x0019, GpsDestDist =0x001A, } }
/* * 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 log4net.Config; using NUnit.Framework; using NUnit.Framework.Constraints; using OpenMetaverse; using OpenSim.Framework; using System.Data.Common; using log4net; #if !NUNIT25 using NUnit.Framework.SyntaxHelpers; #endif // DBMS-specific: using MySql.Data.MySqlClient; using OpenSim.Data.MySQL; using System.Data.SqlClient; using OpenSim.Data.MSSQL; using Mono.Data.Sqlite; using OpenSim.Data.SQLite; namespace OpenSim.Data.Tests { #if NUNIT25 [TestFixture(typeof(MySqlConnection), typeof(MySQLAssetData), Description="Basic Asset store tests (MySQL)")] [TestFixture(typeof(SqlConnection), typeof(MSSQLAssetData), Description = "Basic Asset store tests (MS SQL Server)")] [TestFixture(typeof(SqliteConnection), typeof(SQLiteAssetData), Description = "Basic Asset store tests (SQLite)")] #else [TestFixture(Description = "Asset store tests (SQLite)")] public class SQLiteAssetTests : AssetTests<SqliteConnection, SQLiteAssetData> { } [TestFixture(Description = "Asset store tests (MySQL)")] public class MySqlAssetTests : AssetTests<MySqlConnection, MySQLAssetData> { } [TestFixture(Description = "Asset store tests (MS SQL Server)")] public class MSSQLAssetTests : AssetTests<SqlConnection, MSSQLAssetData> { } #endif public class AssetTests<TConn, TAssetData> : BasicDataServiceTest<TConn, TAssetData> where TConn : DbConnection, new() where TAssetData : AssetDataBase, new() { TAssetData m_db; public UUID uuid1 = UUID.Random(); public UUID uuid2 = UUID.Random(); public UUID uuid3 = UUID.Random(); public string critter1 = UUID.Random().ToString(); public string critter2 = UUID.Random().ToString(); public string critter3 = UUID.Random().ToString(); public byte[] data1 = new byte[100]; PropertyScrambler<AssetBase> scrambler = new PropertyScrambler<AssetBase>() .DontScramble(x => x.ID) .DontScramble(x => x.Type) .DontScramble(x => x.FullID) .DontScramble(x => x.Metadata.ID) .DontScramble(x => x.Metadata.CreatorID) .DontScramble(x => x.Metadata.ContentType) .DontScramble(x => x.Metadata.FullID) .DontScramble(x => x.Data); protected override void InitService(object service) { ClearDB(); m_db = (TAssetData)service; m_db.Initialise(m_connStr); } private void ClearDB() { DropTables("assets"); ResetMigrations("AssetStore"); } [Test] public void T001_LoadEmpty() { Assert.That(m_db.ExistsAsset(uuid1), Is.False); Assert.That(m_db.ExistsAsset(uuid2), Is.False); Assert.That(m_db.ExistsAsset(uuid3), Is.False); } [Test] public void T010_StoreReadVerifyAssets() { AssetBase a1 = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, critter1.ToString()); AssetBase a2 = new AssetBase(uuid2, "asset two", (sbyte)AssetType.Texture, critter2.ToString()); AssetBase a3 = new AssetBase(uuid3, "asset three", (sbyte)AssetType.Texture, critter3.ToString()); a1.Data = data1; a2.Data = data1; a3.Data = data1; scrambler.Scramble(a1); scrambler.Scramble(a2); scrambler.Scramble(a3); m_db.StoreAsset(a1); m_db.StoreAsset(a2); m_db.StoreAsset(a3); AssetBase a1a = m_db.GetAsset(uuid1); Assert.That(a1a, Constraints.PropertyCompareConstraint(a1)); AssetBase a2a = m_db.GetAsset(uuid2); Assert.That(a2a, Constraints.PropertyCompareConstraint(a2)); AssetBase a3a = m_db.GetAsset(uuid3); Assert.That(a3a, Constraints.PropertyCompareConstraint(a3)); scrambler.Scramble(a1a); scrambler.Scramble(a2a); scrambler.Scramble(a3a); m_db.StoreAsset(a1a); m_db.StoreAsset(a2a); m_db.StoreAsset(a3a); AssetBase a1b = m_db.GetAsset(uuid1); Assert.That(a1b, Constraints.PropertyCompareConstraint(a1a)); AssetBase a2b = m_db.GetAsset(uuid2); Assert.That(a2b, Constraints.PropertyCompareConstraint(a2a)); AssetBase a3b = m_db.GetAsset(uuid3); Assert.That(a3b, Constraints.PropertyCompareConstraint(a3a)); Assert.That(m_db.ExistsAsset(uuid1), Is.True); Assert.That(m_db.ExistsAsset(uuid2), Is.True); Assert.That(m_db.ExistsAsset(uuid3), Is.True); List<AssetMetadata> metadatas = m_db.FetchAssetMetadataSet(0, 1000); Assert.That(metadatas.Count >= 3, "FetchAssetMetadataSet() should have returned at least 3 assets!"); // It is possible that the Asset table is filled with data, in which case we don't try to find "our" // assets there: if (metadatas.Count < 1000) { AssetMetadata metadata = metadatas.Find(x => x.FullID == uuid1); Assert.That(metadata.Name, Is.EqualTo(a1b.Name)); Assert.That(metadata.Description, Is.EqualTo(a1b.Description)); Assert.That(metadata.Type, Is.EqualTo(a1b.Type)); Assert.That(metadata.Temporary, Is.EqualTo(a1b.Temporary)); Assert.That(metadata.FullID, Is.EqualTo(a1b.FullID)); } } [Test] public void T020_CheckForWeirdCreatorID() { // It is expected that eventually the CreatorID might be an arbitrary string (an URI) // rather than a valid UUID (?). This test is to make sure that the database layer does not // attempt to convert CreatorID to GUID, but just passes it both ways as a string. AssetBase a1 = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, critter1); AssetBase a2 = new AssetBase(uuid2, "asset two", (sbyte)AssetType.Texture, "This is not a GUID!"); AssetBase a3 = new AssetBase(uuid3, "asset three", (sbyte)AssetType.Texture, ""); a1.Data = data1; a2.Data = data1; a3.Data = data1; m_db.StoreAsset(a1); m_db.StoreAsset(a2); m_db.StoreAsset(a3); AssetBase a1a = m_db.GetAsset(uuid1); Assert.That(a1a, Constraints.PropertyCompareConstraint(a1)); AssetBase a2a = m_db.GetAsset(uuid2); Assert.That(a2a, Constraints.PropertyCompareConstraint(a2)); AssetBase a3a = m_db.GetAsset(uuid3); Assert.That(a3a, Constraints.PropertyCompareConstraint(a3)); } } }
// 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.Threading.Tasks; using System.Diagnostics; namespace System.IO { // This class implements a TextWriter for writing characters to a Stream. // This is designed for character output in a particular Encoding, // whereas the Stream class is designed for byte input and output. [Serializable] public class StreamWriter : TextWriter { // For UTF-8, the values of 1K for the default buffer size and 4K for the // file stream buffer size are reasonable & give very reasonable // performance for in terms of construction time for the StreamWriter and // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer, // which means we take advantage of adaptive buffering code. // The performance using UnicodeEncoding is acceptable. private const int DefaultBufferSize = 1024; // char[] private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; private const int DontCopyOnWriteLineThreshold = 512; // Bit bucket - Null has no backing store. Non closable. public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, UTF8NoBOM, MinBufferSize, true); private Stream _stream; private Encoding _encoding; private Encoder _encoder; private byte[] _byteBuffer; private char[] _charBuffer; private int _charPos; private int _charLen; private bool _autoFlush; private bool _haveWrittenPreamble; private bool _closable; // We don't guarantee thread safety on StreamWriter, but we should at // least prevent users from trying to write anything while an Async // write from the same thread is in progress. [NonSerialized] private volatile Task _asyncWriteTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress. Task t = _asyncWriteTask; if (t != null && !t.IsCompleted) throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); } // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on encoding error. // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the // internal StreamWriter's state to be irrecoverable as it would have buffered the // illegal chars and any subsequent call to Flush() would hit the encoding error again. // Even Close() will hit the exception as it would try to flush the unwritten data. // Maybe we can add a DiscardBufferedData() method to get out of such situation (like // StreamReader though for different reason). Either way, the buffered data will be lost! private static Encoding UTF8NoBOM => EncodingCache.UTF8NoBOM; internal StreamWriter() : base(null) { // Ask for CurrentCulture all the time } public StreamWriter(Stream stream) : this(stream, UTF8NoBOM, DefaultBufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, DefaultBufferSize, false) { } // Creates a new StreamWriter for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // public StreamWriter(Stream stream, Encoding encoding, int bufferSize) : this(stream, encoding, bufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) : base(null) // Ask for CurrentCulture all the time { if (stream == null || encoding == null) { throw new ArgumentNullException(stream == null ? nameof(stream) : nameof(encoding)); } if (!stream.CanWrite) { throw new ArgumentException(SR.Argument_StreamNotWritable); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); } Init(stream, encoding, bufferSize, leaveOpen); } public StreamWriter(string path) : this(path, false, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(string path, bool append) : this(path, append, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(string path, bool append, Encoding encoding) : this(path, append, encoding, DefaultBufferSize) { } public StreamWriter(string path, bool append, Encoding encoding, int bufferSize) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); Stream stream = new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan); Init(stream, encoding, bufferSize, shouldLeaveOpen: false); } private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen) { _stream = streamArg; _encoding = encodingArg; _encoder = _encoding.GetEncoder(); if (bufferSize < MinBufferSize) { bufferSize = MinBufferSize; } _charBuffer = new char[bufferSize]; _byteBuffer = new byte[_encoding.GetMaxByteCount(bufferSize)]; _charLen = bufferSize; // If we're appending to a Stream that already has data, don't write // the preamble. if (_stream.CanSeek && _stream.Position > 0) { _haveWrittenPreamble = true; } _closable = !shouldLeaveOpen; } public override void Close() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { try { // We need to flush any buffered data if we are being closed/disposed. // Also, we never close the handles for stdout & friends. So we can safely // write any buffered data to those streams even during finalization, which // is generally the right thing to do. if (_stream != null) { // Note: flush on the underlying stream can throw (ex., low disk space) if (disposing /* || (LeaveOpen && stream is __ConsoleStream) */) { CheckAsyncTaskInProgress(); Flush(true, true); } } } finally { // Dispose of our resources if this StreamWriter is closable. // Note: Console.Out and other such non closable streamwriters should be left alone if (!LeaveOpen && _stream != null) { try { // Attempt to close the stream even if there was an IO error from Flushing. // Note that Stream.Close() can potentially throw here (may or may not be // due to the same Flush error). In this case, we still need to ensure // cleaning up internal resources, hence the finally block. if (disposing) { _stream.Close(); } } finally { _stream = null; _byteBuffer = null; _charBuffer = null; _encoding = null; _encoder = null; _charLen = 0; base.Dispose(disposing); } } } } public override void Flush() { CheckAsyncTaskInProgress(); Flush(true, true); } private void Flush(bool flushStream, bool flushEncoder) { // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } // Perf boost for Flush on non-dirty writers. if (_charPos == 0 && !flushStream && !flushEncoder) { return; } if (!_haveWrittenPreamble) { _haveWrittenPreamble = true; byte[] preamble = _encoding.GetPreamble(); if (preamble.Length > 0) { _stream.Write(preamble, 0, preamble.Length); } } int count = _encoder.GetBytes(_charBuffer, 0, _charPos, _byteBuffer, 0, flushEncoder); _charPos = 0; if (count > 0) { _stream.Write(_byteBuffer, 0, count); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { _stream.Flush(); } } public virtual bool AutoFlush { get { return _autoFlush; } set { CheckAsyncTaskInProgress(); _autoFlush = value; if (value) { Flush(true, false); } } } public virtual Stream BaseStream { get { return _stream; } } internal bool LeaveOpen { get { return !_closable; } } internal bool HaveWrittenPreamble { set { _haveWrittenPreamble = value; } } public override Encoding Encoding { get { return _encoding; } } public override void Write(char value) { CheckAsyncTaskInProgress(); if (_charPos == _charLen) { Flush(false, false); } _charBuffer[_charPos] = value; _charPos++; if (_autoFlush) { Flush(true, false); } } public override void Write(char[] buffer) { // This may be faster than the one with the index & count since it // has to do less argument checking. if (buffer == null) { return; } CheckAsyncTaskInProgress(); // Threshold of 4 was chosen after running perf tests if (buffer.Length <= 4) { for (int i = 0; i < buffer.Length; i++) { if (_charPos == _charLen) { Flush(false, false); } Debug.Assert(_charLen - _charPos > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code."); _charBuffer[_charPos] = buffer[i]; _charPos++; } } else { int count = buffer.Length; int index = 0; while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code."); Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char)); _charPos += n; index += n; count -= n; } } if (_autoFlush) { Flush(true, false); } } public override void Write(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } CheckAsyncTaskInProgress(); // Threshold of 4 was chosen after running perf tests if (count <= 4) { while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } Debug.Assert(_charLen - _charPos > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code."); _charBuffer[_charPos] = buffer[index]; _charPos++; index++; count--; } } else { while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char)); _charPos += n; index += n; count -= n; } } if (_autoFlush) { Flush(true, false); } } public override void Write(string value) { if (value == null) { return; } CheckAsyncTaskInProgress(); int count = value.Length; // Threshold of 4 was chosen after running perf tests if (count <= 4) { for (int i = 0; i < count; i++) { if (_charPos == _charLen) { Flush(false, false); } Debug.Assert(_charLen - _charPos > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); _charBuffer[_charPos] = value[i]; _charPos++; } } else { int index = 0; while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, _charBuffer, _charPos, n); _charPos += n; index += n; count -= n; } } if (_autoFlush) { Flush(true, false); } } // // Optimize the most commonly used WriteLine overload. This optimization is important for System.Console in particular // because of it will make one WriteLine equal to one call to the OS instead of two in the common case. // public override void WriteLine(string value) { if (value == null) { value = String.Empty; } CheckAsyncTaskInProgress(); int count = value.Length; int index = 0; while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::WriteLine(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, _charBuffer, _charPos, n); _charPos += n; index += n; count -= n; } char[] coreNewLine = CoreNewLine; for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (_charPos == _charLen) { Flush(false, false); } _charBuffer[_charPos] = coreNewLine[i]; _charPos++; } if (_autoFlush) { Flush(true, false); } } #region Task based Async APIs public override Task WriteAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, char value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = value; charPos++; if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteAsync(string value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } if (value != null) { if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } else { return Task.CompletedTask; } } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, string value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { Debug.Assert(value != null); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(buffer, index, count); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, char[] buffer, int index, int count, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { Debug.Assert(count == 0 || (count > 0 && buffer != null)); Debug.Assert(index >= 0); Debug.Assert(count >= 0); Debug.Assert(buffer == null || (buffer != null && buffer.Length - index >= count)); while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.BlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteLineAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, null, 0, 0, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(string value) { if (value == null) { return WriteLineAsync(); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(buffer, index, count); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task FlushAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.FlushAsync(); } // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = FlushAsyncInternal(true, true, _charBuffer, _charPos); _asyncWriteTask = task; return task; } private int CharPos_Prop { set { _charPos = value; } } private bool HaveWrittenPreamble_Prop { set { _haveWrittenPreamble = value; } } private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, char[] sCharBuffer, int sCharPos) { // Perf boost for Flush on non-dirty writers. if (sCharPos == 0 && !flushStream && !flushEncoder) { return Task.CompletedTask; } Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, _haveWrittenPreamble, _encoding, _encoder, _byteBuffer, _stream); _charPos = 0; return flushTask; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, char[] charBuffer, int charPos, bool haveWrittenPreamble, Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream) { if (!haveWrittenPreamble) { _this.HaveWrittenPreamble_Prop = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) { await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false); } } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); if (count > 0) { await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { await stream.FlushAsync().ConfigureAwait(false); } } #endregion } // class StreamWriter } // namespace
using System; using System.Collections.Specialized; using System.Net; using Newtonsoft.Json; using SteamKit2; namespace SteamTrade.TradeWebAPI { /// <summary> /// This class provides the interface into the Web API for trading on the /// Steam network. /// </summary> public class TradeSession { private const string SteamCommunityDomain = "steamcommunity.com"; private const string SteamTradeUrl = "http://steamcommunity.com/trade/{0}/"; private string sessionIdEsc; private string baseTradeURL; private CookieContainer cookies; private readonly string steamLogin; private readonly string sessionId; private readonly SteamID OtherSID; /// <summary> /// Initializes a new instance of the <see cref="TradeSession"/> class. /// </summary> /// <param name="sessionId">The session id.</param> /// <param name="steamLogin">The current steam login.</param> /// <param name="otherSid">The Steam id of the other trading partner.</param> public TradeSession(string sessionId, string steamLogin, SteamID otherSid) { this.sessionId = sessionId; this.steamLogin = steamLogin; OtherSID = otherSid; Init(); } #region Trade status properties /// <summary> /// Gets the LogPos number of the current trade. /// </summary> /// <remarks>This is not automatically updated by this class.</remarks> internal int LogPos { get; set; } /// <summary> /// Gets the version number of the current trade. This increments on /// every item added or removed from a trade. /// </summary> /// <remarks>This is not automatically updated by this class.</remarks> internal int Version { get; set; } #endregion Trade status properties #region Trade Web API command methods /// <summary> /// Gets the trade status. /// </summary> /// <returns>A deserialized JSON object into <see cref="TradeStatus"/></returns> /// <remarks> /// This is the main polling method for trading and must be done at a /// periodic rate (probably around 1 second). /// </remarks> internal TradeStatus GetStatus() { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("logpos", "" + LogPos); data.Add ("version", "" + Version); string response = Fetch (baseTradeURL + "tradestatus", "POST", data); return JsonConvert.DeserializeObject<TradeStatus> (response); } /// <summary> /// Sends a message to the user over the trade chat. /// </summary> internal bool SendMessageWebCmd(string msg) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("message", msg); data.Add ("logpos", "" + LogPos); data.Add ("version", "" + Version); string result = Fetch (baseTradeURL + "chat", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Adds a specified itom by its itemid. Since each itemid is /// unique to each item, you'd first have to find the item, or /// use AddItemByDefindex instead. /// </summary> /// <returns> /// Returns false if the item doesn't exist in the Bot's inventory, /// and returns true if it appears the item was added. /// </returns> internal bool AddItemWebCmd(ulong itemid, int slot, int appid, long contextid, int amount) { var data = new NameValueCollection (); data.Add("sessionid", sessionIdEsc); data.Add("appid", "" + appid); data.Add("contextid", "" + contextid); data.Add("itemid", "" + itemid); data.Add("slot", "" + slot); data.Add("amount", "" + amount); string result = Fetch(baseTradeURL + "additem", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } internal bool AddCurrencyWebCmd(ulong currencyid, int amount, int appid, long contextid) { var data = new NameValueCollection(); data.Add("sessionid", sessionIdEsc); data.Add("appid", "" + appid); data.Add("contextid", "" + contextid); data.Add("currencyid", "" + currencyid); data.Add("amount", "" + amount); string result = Fetch(baseTradeURL + "setcurrency", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Removes an item by its itemid. Read AddItem about itemids. /// Returns false if the item isn't in the offered items, or /// true if it appears it succeeded. /// </summary> internal bool RemoveItemWebCmd(ulong itemid, int slot, int appid, long contextid, int amount) { var data = new NameValueCollection (); data.Add("sessionid", sessionIdEsc); data.Add("appid", "" + appid); data.Add("contextid", "" + contextid); data.Add("itemid", "" + itemid); data.Add("slot", "" + slot); data.Add("amount", "" + amount); string result = Fetch (baseTradeURL + "removeitem", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Sets the bot to a ready status. /// </summary> internal bool SetReadyWebCmd(bool ready) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("ready", ready ? "true" : "false"); data.Add ("version", "" + Version); string result = Fetch (baseTradeURL + "toggleready", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Accepts the trade from the user. Returns a deserialized /// JSON object. /// </summary> internal bool AcceptTradeWebCmd() { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("version", "" + Version); string response = Fetch (baseTradeURL + "confirm", "POST", data); dynamic json = JsonConvert.DeserializeObject(response); return IsSuccess(json); } /// <summary> /// Cancel the trade. This calls the OnClose handler, as well. /// </summary> internal bool CancelTradeWebCmd () { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); string result = Fetch (baseTradeURL + "cancel", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } private bool IsSuccess(dynamic json) { if(json == null) return false; try { //Sometimes, the response looks like this: {"success":false,"results":{"success":11}} //I believe this is Steam's way of asking the trade window (which is actually a webpage) to refresh, following a large successful update return (json.success == "true" || (json.results != null && json.results.success == "11")); } catch(Exception) { return false; } } #endregion Trade Web API command methods string Fetch (string url, string method, NameValueCollection data = null) { return SteamWeb.Fetch (url, method, data, cookies); } private void Init() { sessionIdEsc = Uri.UnescapeDataString(sessionId); Version = 1; cookies = new CookieContainer(); cookies.Add (new Cookie ("sessionid", sessionId, String.Empty, SteamCommunityDomain)); cookies.Add (new Cookie ("steamLogin", steamLogin, String.Empty, SteamCommunityDomain)); baseTradeURL = String.Format (SteamTradeUrl, OtherSID.ConvertToUInt64()); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature { [ExportLanguageService(typeof(AbstractChangeSignatureService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureService { public override async Task<ISymbol> GetInvocationSymbolAsync( Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.GetRoot(cancellationToken).FindToken(position != tree.Length ? position : Math.Max(0, position - 1)); var ancestorDeclarationKinds = restrictToDeclarations ? _invokableAncestorKinds.Add(SyntaxKind.Block) : _invokableAncestorKinds; SyntaxNode matchingNode = token.Parent.AncestorsAndSelf().FirstOrDefault(n => ancestorDeclarationKinds.Contains(n.Kind())); if (matchingNode == null || matchingNode.IsKind(SyntaxKind.Block)) { return null; } ISymbol symbol; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); symbol = semanticModel.GetDeclaredSymbol(matchingNode, cancellationToken); if (symbol != null) { return symbol; } if (matchingNode.IsKind(SyntaxKind.ObjectCreationExpression)) { var objectCreation = matchingNode as ObjectCreationExpressionSyntax; if (token.Parent.AncestorsAndSelf().Any(a => a == objectCreation.Type)) { var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol; if (typeSymbol != null && typeSymbol.IsKind(SymbolKind.NamedType) && (typeSymbol as ITypeSymbol).TypeKind == TypeKind.Delegate) { return typeSymbol; } } } var symbolInfo = semanticModel.GetSymbolInfo(matchingNode, cancellationToken); return symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault(); } private ImmutableArray<SyntaxKind> _invokableAncestorKinds = new[] { SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.NameMemberCref, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.DelegateDeclaration }.ToImmutableArray(); private ImmutableArray<SyntaxKind> _updatableAncestorKinds = new[] { SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.DelegateDeclaration, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.NameMemberCref }.ToImmutableArray(); private ImmutableArray<SyntaxKind> _updatableNodeKinds = new[] { SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.DelegateDeclaration, SyntaxKind.NameMemberCref, SyntaxKind.AnonymousMethodExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.SimpleLambdaExpression }.ToImmutableArray(); public override SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node) { if (_updatableNodeKinds.Contains(node.Kind())) { return node; } // TODO: file bug about this: var invocation = csnode.Ancestors().FirstOrDefault(a => a.Kind == SyntaxKind.InvocationExpression); var matchingNode = node.AncestorsAndSelf().FirstOrDefault(n => _updatableAncestorKinds.Contains(n.Kind())); if (matchingNode == null) { return null; } var nodeContainingOriginal = GetNodeContainingTargetNode(matchingNode); if (nodeContainingOriginal == null) { return null; } return node.AncestorsAndSelf().Any(n => n == nodeContainingOriginal) ? matchingNode : null; } private SyntaxNode GetNodeContainingTargetNode(SyntaxNode matchingNode) { switch (matchingNode.Kind()) { case SyntaxKind.InvocationExpression: return (matchingNode as InvocationExpressionSyntax).Expression; case SyntaxKind.ElementAccessExpression: return (matchingNode as ElementAccessExpressionSyntax).ArgumentList; case SyntaxKind.ObjectCreationExpression: return (matchingNode as ObjectCreationExpressionSyntax).Type; case SyntaxKind.ConstructorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.Attribute: case SyntaxKind.DelegateDeclaration: case SyntaxKind.NameMemberCref: return matchingNode; default: return null; } } public override SyntaxNode ChangeSignature( Document document, ISymbol declarationSymbol, SyntaxNode potentiallyUpdatedNode, SyntaxNode originalNode, SignatureChange signaturePermutation, CancellationToken cancellationToken) { var updatedNode = potentiallyUpdatedNode as CSharpSyntaxNode; // Update <param> tags. if (updatedNode.IsKind(SyntaxKind.MethodDeclaration) || updatedNode.IsKind(SyntaxKind.ConstructorDeclaration) || updatedNode.IsKind(SyntaxKind.IndexerDeclaration) || updatedNode.IsKind(SyntaxKind.DelegateDeclaration)) { var updatedLeadingTrivia = UpdateParamTagsInLeadingTrivia(updatedNode, declarationSymbol, signaturePermutation); if (updatedLeadingTrivia != null) { updatedNode = updatedNode.WithLeadingTrivia(updatedLeadingTrivia); } } // Update declarations parameter lists if (updatedNode.IsKind(SyntaxKind.MethodDeclaration)) { var method = updatedNode as MethodDeclarationSyntax; var updatedParameters = PermuteDeclaration(method.ParameterList.Parameters, signaturePermutation); return method.WithParameterList(method.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = updatedNode as ConstructorDeclarationSyntax; var updatedParameters = PermuteDeclaration(constructor.ParameterList.Parameters, signaturePermutation); return constructor.WithParameterList(constructor.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.IndexerDeclaration)) { var indexer = updatedNode as IndexerDeclarationSyntax; var updatedParameters = PermuteDeclaration(indexer.ParameterList.Parameters, signaturePermutation); return indexer.WithParameterList(indexer.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.DelegateDeclaration)) { var delegateDeclaration = updatedNode as DelegateDeclarationSyntax; var updatedParameters = PermuteDeclaration(delegateDeclaration.ParameterList.Parameters, signaturePermutation); return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.AnonymousMethodExpression)) { var anonymousMethod = updatedNode as AnonymousMethodExpressionSyntax; // Delegates may omit parameters in C# if (anonymousMethod.ParameterList == null) { return anonymousMethod; } var updatedParameters = PermuteDeclaration(anonymousMethod.ParameterList.Parameters, signaturePermutation); return anonymousMethod.WithParameterList(anonymousMethod.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.SimpleLambdaExpression)) { var lambda = updatedNode as SimpleLambdaExpressionSyntax; if (signaturePermutation.UpdatedConfiguration.ToListOfParameters().Any()) { Debug.Assert(false, "Updating a simple lambda expression without removing its parameter"); } else { // No parameters. Change to a parenthesized lambda expression var emptyParameterList = SyntaxFactory.ParameterList() .WithLeadingTrivia(lambda.Parameter.GetLeadingTrivia()) .WithTrailingTrivia(lambda.Parameter.GetTrailingTrivia()); return SyntaxFactory.ParenthesizedLambdaExpression(lambda.AsyncKeyword, emptyParameterList, lambda.ArrowToken, lambda.Body); } } if (updatedNode.IsKind(SyntaxKind.ParenthesizedLambdaExpression)) { var lambda = updatedNode as ParenthesizedLambdaExpressionSyntax; var updatedParameters = PermuteDeclaration(lambda.ParameterList.Parameters, signaturePermutation); return lambda.WithParameterList(lambda.ParameterList.WithParameters(updatedParameters)); } // Update reference site argument lists if (updatedNode.IsKind(SyntaxKind.InvocationExpression)) { var invocation = updatedNode as InvocationExpressionSyntax; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var symbolInfo = semanticModel.GetSymbolInfo(originalNode as InvocationExpressionSyntax, cancellationToken); var methodSymbol = symbolInfo.Symbol as IMethodSymbol; var isReducedExtensionMethod = false; if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ReducedExtension) { isReducedExtensionMethod = true; } var newArguments = PermuteArgumentList(document, declarationSymbol, invocation.ArgumentList.Arguments, signaturePermutation, isReducedExtensionMethod); return invocation.WithArgumentList(invocation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ObjectCreationExpression)) { var objCreation = updatedNode as ObjectCreationExpressionSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation); return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ThisConstructorInitializer) || updatedNode.IsKind(SyntaxKind.BaseConstructorInitializer)) { var objCreation = updatedNode as ConstructorInitializerSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation); return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ElementAccessExpression)) { var elementAccess = updatedNode as ElementAccessExpressionSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, elementAccess.ArgumentList.Arguments, signaturePermutation); return elementAccess.WithArgumentList(elementAccess.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.Attribute)) { var attribute = updatedNode as AttributeSyntax; var newArguments = PermuteAttributeArgumentList(document, declarationSymbol, attribute.ArgumentList.Arguments, signaturePermutation); return attribute.WithArgumentList(attribute.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } // Handle references in crefs if (updatedNode.IsKind(SyntaxKind.NameMemberCref)) { var nameMemberCref = updatedNode as NameMemberCrefSyntax; if (nameMemberCref.Parameters == null || !nameMemberCref.Parameters.Parameters.Any()) { return nameMemberCref; } var newParameters = PermuteDeclaration(nameMemberCref.Parameters.Parameters, signaturePermutation); var newCrefParameterList = nameMemberCref.Parameters.WithParameters(newParameters); return nameMemberCref.WithParameters(newCrefParameterList); } Debug.Assert(false, "Unknown reference location"); return null; } private SeparatedSyntaxList<T> PermuteDeclaration<T>(SeparatedSyntaxList<T> list, SignatureChange updatedSignature) where T : SyntaxNode { var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var newParameters = new List<T>(); foreach (var newParam in reorderedParameters) { var pos = originalParameters.IndexOf(newParam); var param = list[pos]; newParameters.Add(param); } var numSeparatorsToSkip = originalParameters.Count - reorderedParameters.Count; return SyntaxFactory.SeparatedList(newParameters, GetSeparators(list, numSeparatorsToSkip)); } private static SeparatedSyntaxList<AttributeArgumentSyntax> PermuteAttributeArgumentList( Document document, ISymbol declarationSymbol, SeparatedSyntaxList<AttributeArgumentSyntax> arguments, SignatureChange updatedSignature) { var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature); var numSeparatorsToSkip = arguments.Count - newArguments.Count; return SyntaxFactory.SeparatedList(newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip)); } private static SeparatedSyntaxList<ArgumentSyntax> PermuteArgumentList( Document document, ISymbol declarationSymbol, SeparatedSyntaxList<ArgumentSyntax> arguments, SignatureChange updatedSignature, bool isReducedExtensionMethod = false) { var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature, isReducedExtensionMethod); var numSeparatorsToSkip = arguments.Count - newArguments.Count; return SyntaxFactory.SeparatedList(newArguments.Select(a => (ArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip)); } private List<SyntaxTrivia> UpdateParamTagsInLeadingTrivia(CSharpSyntaxNode node, ISymbol declarationSymbol, SignatureChange updatedSignature) { if (!node.HasLeadingTrivia) { return null; } var paramNodes = node .DescendantNodes(descendIntoTrivia: true) .OfType<XmlElementSyntax>() .Where(e => e.StartTag.Name.ToString() == DocumentationCommentXmlNames.ParameterElementName); var permutedParamNodes = VerifyAndPermuteParamNodes(paramNodes, declarationSymbol, updatedSignature); if (permutedParamNodes == null) { return null; } return GetPermutedTrivia(node, permutedParamNodes); } private List<XmlElementSyntax> VerifyAndPermuteParamNodes(IEnumerable<XmlElementSyntax> paramNodes, ISymbol declarationSymbol, SignatureChange updatedSignature) { // Only reorder if count and order match originally. var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var declaredParameters = declarationSymbol.GetParameters(); if (paramNodes.Count() != declaredParameters.Count()) { return null; } var dictionary = new Dictionary<string, XmlElementSyntax>(); int i = 0; foreach (var paramNode in paramNodes) { var nameAttribute = paramNode.StartTag.Attributes.FirstOrDefault(a => a.Name.ToString().Equals("name", StringComparison.OrdinalIgnoreCase)); if (nameAttribute == null) { return null; } var identifier = nameAttribute.DescendantNodes(descendIntoTrivia: true).OfType<IdentifierNameSyntax>().FirstOrDefault(); if (identifier == null || identifier.ToString() != declaredParameters.ElementAt(i).Name) { return null; } dictionary.Add(originalParameters[i].Name.ToString(), paramNode); i++; } // Everything lines up, so permute them. var permutedParams = new List<XmlElementSyntax>(); foreach (var parameter in reorderedParameters) { permutedParams.Add(dictionary[parameter.Name]); } return permutedParams; } private List<SyntaxTrivia> GetPermutedTrivia(CSharpSyntaxNode node, List<XmlElementSyntax> permutedParamNodes) { var updatedLeadingTrivia = new List<SyntaxTrivia>(); var index = 0; foreach (var trivia in node.GetLeadingTrivia()) { if (!trivia.HasStructure) { updatedLeadingTrivia.Add(trivia); continue; } var structuredTrivia = trivia.GetStructure() as DocumentationCommentTriviaSyntax; if (structuredTrivia == null) { updatedLeadingTrivia.Add(trivia); continue; } var updatedNodeList = new List<XmlNodeSyntax>(); var structuredContent = structuredTrivia.Content.ToList(); for (int i = 0; i < structuredContent.Count; i++) { var content = structuredContent[i]; if (!content.IsKind(SyntaxKind.XmlElement)) { updatedNodeList.Add(content); continue; } var xmlElement = content as XmlElementSyntax; if (xmlElement.StartTag.Name.ToString() != DocumentationCommentXmlNames.ParameterElementName) { updatedNodeList.Add(content); continue; } // Found a param tag, so insert the next one from the reordered list if (index < permutedParamNodes.Count) { updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia())); index++; } else { // Inspecting a param element that we are deleting but not replacing. } } var newDocComments = SyntaxFactory.DocumentationCommentTrivia(structuredTrivia.Kind(), SyntaxFactory.List(updatedNodeList.AsEnumerable())); newDocComments = newDocComments.WithEndOfComment(structuredTrivia.EndOfComment); newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia()); var newTrivia = SyntaxFactory.Trivia(newDocComments); updatedLeadingTrivia.Add(newTrivia); } return updatedLeadingTrivia; } private static List<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip = 0) where T : SyntaxNode { var separators = new List<SyntaxToken>(); for (int i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++) { separators.Add(arguments.GetSeparator(i)); } return separators; } public override async Task<ImmutableArray<SymbolAndProjectId>> DetermineCascadedSymbolsFromDelegateInvoke( SymbolAndProjectId<IMethodSymbol> symbolAndProjectId, Document document, CancellationToken cancellationToken) { var symbol = symbolAndProjectId.Symbol; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var nodes = root.DescendantNodes().ToImmutableArray(); var convertedMethodGroups = nodes .WhereAsArray( n => { if (!n.IsKind(SyntaxKind.IdentifierName) || !semanticModel.GetMemberGroup(n, cancellationToken).Any()) { return false; } ISymbol convertedType = semanticModel.GetTypeInfo(n, cancellationToken).ConvertedType; if (convertedType != null) { convertedType = convertedType.OriginalDefinition; } if (convertedType != null) { convertedType = SymbolFinder.FindSourceDefinitionAsync(convertedType, document.Project.Solution, cancellationToken).WaitAndGetResult(cancellationToken) ?? convertedType; } return convertedType == symbol.ContainingType; }) .SelectAsArray(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol); return convertedMethodGroups.SelectAsArray(symbolAndProjectId.WithSymbol); } protected override IEnumerable<IFormattingRule> GetFormattingRules(Document document) { return new[] { new ChangeSignatureFormattingRule() }.Concat(Formatter.GetDefaultFormattingRules(document)); } } }
namespace StripeTests { using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Stripe; using Xunit; public class OrderServiceTest : BaseStripeTest { private const string OrderId = "or_123"; private readonly OrderService service; private readonly OrderCreateOptions createOptions; private readonly OrderUpdateOptions updateOptions; private readonly OrderPayOptions payOptions; private readonly OrderReturnOptions returnOptions; private readonly OrderListOptions listOptions; public OrderServiceTest( StripeMockFixture stripeMockFixture, MockHttpClientFixture mockHttpClientFixture) : base(stripeMockFixture, mockHttpClientFixture) { this.service = new OrderService(this.StripeClient); this.createOptions = new OrderCreateOptions { Currency = "usd", Items = new List<OrderItemOptions> { new OrderItemOptions { Parent = "sku_123", Quantity = 1, }, }, }; this.listOptions = new OrderListOptions { Limit = 1, }; this.payOptions = new OrderPayOptions { Customer = "cus_123", }; this.returnOptions = new OrderReturnOptions { Items = new List<OrderReturnItemOptions> { new OrderReturnItemOptions { Parent = "sku_123", Quantity = 1, }, }, }; this.updateOptions = new OrderUpdateOptions { Metadata = new Dictionary<string, string> { { "key", "value" }, }, }; } [Fact] public void Create() { var order = this.service.Create(this.createOptions); this.AssertRequest(HttpMethod.Post, "/v1/orders"); Assert.NotNull(order); Assert.Equal("order", order.Object); } [Fact] public async Task CreateAsync() { var order = await this.service.CreateAsync(this.createOptions); this.AssertRequest(HttpMethod.Post, "/v1/orders"); Assert.NotNull(order); Assert.Equal("order", order.Object); } [Fact] public void Get() { var order = this.service.Get(OrderId); this.AssertRequest(HttpMethod.Get, "/v1/orders/or_123"); Assert.NotNull(order); Assert.Equal("order", order.Object); } [Fact] public async Task GetAsync() { var order = await this.service.GetAsync(OrderId); this.AssertRequest(HttpMethod.Get, "/v1/orders/or_123"); Assert.NotNull(order); Assert.Equal("order", order.Object); } [Fact] public void List() { var orders = this.service.List(this.listOptions); this.AssertRequest(HttpMethod.Get, "/v1/orders"); Assert.NotNull(orders); Assert.Equal("list", orders.Object); Assert.Single(orders.Data); Assert.Equal("order", orders.Data[0].Object); } [Fact] public async Task ListAsync() { var orders = await this.service.ListAsync(this.listOptions); this.AssertRequest(HttpMethod.Get, "/v1/orders"); Assert.NotNull(orders); Assert.Equal("list", orders.Object); Assert.Single(orders.Data); Assert.Equal("order", orders.Data[0].Object); } [Fact] public void ListAutoPaging() { var order = this.service.ListAutoPaging(this.listOptions).First(); Assert.NotNull(order); Assert.Equal("order", order.Object); } [Fact] public async Task ListAutoPagingAsync() { var order = await this.service.ListAutoPagingAsync(this.listOptions).FirstAsync(); Assert.NotNull(order); Assert.Equal("order", order.Object); } [Fact] public void Pay() { var order = this.service.Pay(OrderId, this.payOptions); this.AssertRequest(HttpMethod.Post, "/v1/orders/or_123/pay"); Assert.NotNull(order); Assert.Equal("order", order.Object); } [Fact] public async Task PayAsync() { var order = await this.service.PayAsync(OrderId, this.payOptions); this.AssertRequest(HttpMethod.Post, "/v1/orders/or_123/pay"); Assert.NotNull(order); Assert.Equal("order", order.Object); } [Fact] public void Return() { var orderReturn = this.service.Return(OrderId, this.returnOptions); this.AssertRequest(HttpMethod.Post, "/v1/orders/or_123/returns"); Assert.NotNull(orderReturn); Assert.Equal("order_return", orderReturn.Object); } [Fact] public async Task ReturnAsync() { var orderReturn = await this.service.ReturnAsync(OrderId, this.returnOptions); this.AssertRequest(HttpMethod.Post, "/v1/orders/or_123/returns"); Assert.NotNull(orderReturn); Assert.Equal("order_return", orderReturn.Object); } [Fact] public void Update() { var order = this.service.Update(OrderId, this.updateOptions); this.AssertRequest(HttpMethod.Post, "/v1/orders/or_123"); Assert.NotNull(order); Assert.Equal("order", order.Object); } [Fact] public async Task UpdateAsync() { var order = await this.service.UpdateAsync(OrderId, this.updateOptions); this.AssertRequest(HttpMethod.Post, "/v1/orders/or_123"); Assert.NotNull(order); Assert.Equal("order", order.Object); } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using OpenSim.Region.Physics.Manager; namespace InWorldz.PhysxPhysics.Meshing { internal partial class MeshingStage { /// <summary> /// Command to retrieve a mesh from the meshing stage /// </summary> internal struct MeshingQueueItem : IMeshingQueueItem { public string PrimName; public OpenSim.Framework.PrimitiveBaseShape Shape; public OpenMetaverse.Vector3 Size; public float LOD; public MeshingCompleteDelegate CompletedDelegate; public bool IsDynamic; public byte[] SerializedShapes; public bool FromCrossing; public void Execute(MeshingStage meshingStage) { //short circuit null shapes if (Shape.PreferredPhysicsShape == OpenMetaverse.PhysicsShapeType.None) { this.CompletedDelegate(PhysicsShape.Null); return; } ulong meshHash = Shape.GetMeshKey(Size, MeshingStage.SCULPT_MESH_LOD); //check to see if we have this shape in the cache PhysicsShape phyShape; if (meshingStage.TryGetCachedShape(meshHash, Shape, IsDynamic, out phyShape)) { phyShape.AddRef(); //we are done here, call back to caller this.CompletedDelegate(phyShape); return; } int meshingBegan = Environment.TickCount; var bestShape = ShapeDeterminer.FindBestShape(Shape, IsDynamic); //first try to extract serialized shapes if (!TryExtractSerializedShapes(meshingStage, meshHash, bestShape)) { //failure, generate GenerateShapes(meshingStage, meshHash, bestShape); } if (Settings.Instance.InstrumentMeshing) { m_log.InfoFormat("[STATS]: PHYSX_MESHING_TIME,{0},{1}", bestShape, Environment.TickCount - meshingBegan); } } private bool TryExtractSerializedShapes(MeshingStage meshingStage, ulong meshHash, ShapeType bestShape) { if (SerializedShapes == null) return false; if (bestShape != ShapeType.TriMesh && bestShape != ShapeType.DecomposedConvexHulls && bestShape != ShapeType.SingleConvex) return false; //we only handle these types using (PhysX.Collection coll = meshingStage._scene.Physics.CreateCollection()) { using (MemoryStream ms = new MemoryStream(SerializedShapes)) { if (! coll.Deserialize(ms)) { m_log.Warn("[InWorldz.PhysxPhysics]: Geometry deserialization failed"); return false; } } if (coll.DeserializedObjects.Count > 0) { PhysicsShape phyShape; if (coll.DeserializedObjects[0] is PhysX.ConvexMesh) { List<PhysX.ConvexMesh> target = new List<PhysX.ConvexMesh>(coll.DeserializedObjects.Cast<PhysX.ConvexMesh>()); var geoms = new List<PhysX.ConvexMeshGeometry>(target.Select(item => new PhysX.ConvexMeshGeometry(item))); if (bestShape == ShapeType.DecomposedConvexHulls) { phyShape = CreatePhysicsShapeFromConvexSetAndCache(meshingStage, meshHash, geoms); } else if (bestShape == ShapeType.SingleConvex) { phyShape = CreatePhysicsShapeFromSingleConvexAndCache(meshingStage, meshHash, geoms[0]); } else { m_log.Warn("[InWorldz.PhysxPhysics]: Serialized geoms were convex, but best shape doesnt match"); return false; } } else if (coll.DeserializedObjects[0] is PhysX.TriangleMesh) { List<PhysX.TriangleMesh> target = new List<PhysX.TriangleMesh>(coll.DeserializedObjects.Cast<PhysX.TriangleMesh>()); var geoms = new List<PhysX.TriangleMeshGeometry>(target.Select(item => new PhysX.TriangleMeshGeometry(item))); if (target.Count == 1) { phyShape = CreatePhysicsShapeFromTrimeshAndCache(meshingStage, meshHash, geoms[0]); } else { m_log.Warn("[InWorldz.PhysxPhysics]: Oddity. Got more than one serialized trimesh back"); return false; } } else { m_log.Warn("[InWorldz.PhysxPhysics]: Oddity. Serialized geoms weren't convex or trimesh"); return false; } this.CompletedDelegate(phyShape); return true; } else { //no geom? m_log.Warn("[InWorldz.PhysxPhysics]: Oddity. Didnt find any geom even though we were supplied with a serialized collection"); return false; } } } private void GenerateShapes(MeshingStage meshingStage, ulong meshHash, ShapeType bestShape) { //if we've gotten here, and this is from a crossing, we must have the //serialized physics shape data. if for whatever reason we don't, we //need to fall back to a basic shape to prevent the crossing from //trying to pull assets while we're trying to move an object to the //new region if (FromCrossing) { bestShape = ShapeType.PrimitiveBox; } switch (bestShape) { case ShapeType.PrimitiveBox: case ShapeType.PrimitiveSphere: this.GenerateBasicShapeAndComplete(meshingStage, meshHash); break; case ShapeType.DecomposedConvexHulls: this.GenerateConvexSetAndComplete(meshingStage, meshHash); break; case ShapeType.TriMesh: this.GenerateTrimeshAndComplete(meshingStage, meshHash); break; case ShapeType.SingleConvex: this.GenerateSingleConvexAndComplete(meshingStage, meshHash); break; case ShapeType.Null: this.CompletedDelegate(PhysicsShape.Null); break; default: throw new ArgumentException("Unable to generate an appropriate PhysX shape for the given parameters"); } } private void GenerateSingleConvexAndComplete(MeshingStage meshingStage, ulong meshHash) { PhysicsShape phyShape; //we need to mesh this object into convex hulls appropriate for dynamic objects PhysX.ConvexMeshGeometry convex = meshingStage.GenerateBasicConvexHull(PrimName, Shape, Size, MeshingStage.SCULPT_MESH_LOD, IsDynamic); if (convex == null) { //meshing or one of its prereq steps failed, generate a bounding box PhysX.Geometry geom = meshingStage.GeneratePhysXBoxShape(Shape); //basic shapes are not cached phyShape = new PhysicsShape(geom, ShapeType.PrimitiveBox, meshHash); } else { phyShape = CreatePhysicsShapeFromSingleConvexAndCache(meshingStage, meshHash, convex); } //we are done here, call back to caller this.CompletedDelegate(phyShape); } private static PhysicsShape CreatePhysicsShapeFromSingleConvexAndCache(MeshingStage meshingStage, ulong meshHash, PhysX.ConvexMeshGeometry convex) { PhysicsShape phyShape; phyShape = new PhysicsShape(new List<PhysX.ConvexMeshGeometry> { convex }, meshHash, true); phyShape.AddRef(); //complex shapes are cached meshingStage.CacheShape(meshHash, phyShape, ShapeType.SingleConvex); return phyShape; } private void GenerateTrimeshAndComplete(MeshingStage meshingStage, ulong meshHash) { PhysicsShape phyShape; PhysX.TriangleMeshGeometry triMesh = meshingStage.GeneratePhysXTrimeshShape(PrimName, Shape, Size, MeshingStage.SCULPT_MESH_LOD, IsDynamic); if (triMesh == null) { //meshing or one of its prereq steps failed, generate a bounding box PhysX.Geometry geom = meshingStage.GeneratePhysXBoxShape(Shape); //basic shapes are not cached phyShape = new PhysicsShape(geom, ShapeType.PrimitiveBox, meshHash); } else { phyShape = CreatePhysicsShapeFromTrimeshAndCache(meshingStage, meshHash, triMesh); } //we are done here, call back to caller this.CompletedDelegate(phyShape); } private static PhysicsShape CreatePhysicsShapeFromTrimeshAndCache(MeshingStage meshingStage, ulong meshHash, PhysX.TriangleMeshGeometry triMesh) { PhysicsShape phyShape; phyShape = new PhysicsShape(triMesh, ShapeType.TriMesh, meshHash); phyShape.AddRef(); //complex shapes are cached meshingStage.CacheShape(meshHash, phyShape, ShapeType.TriMesh); return phyShape; } private void GenerateConvexSetAndComplete(MeshingStage meshingStage, ulong meshHash) { PhysicsShape phyShape; //we need to mesh this object into convex hulls appropriate for dynamic objects List<PhysX.ConvexMeshGeometry> convexes = meshingStage.GenerateComplexPhysXShape(meshHash, PrimName, Shape, Size, MeshingStage.SCULPT_MESH_LOD, IsDynamic); if (convexes == null) { //meshing or one of its prereq steps failed, generate a bounding box PhysX.Geometry geom = meshingStage.GeneratePhysXBoxShape(Shape); //basic shapes are not cached phyShape = new PhysicsShape(geom, ShapeType.PrimitiveBox, meshHash); } else { phyShape = CreatePhysicsShapeFromConvexSetAndCache(meshingStage, meshHash, convexes); } //we are done here, call back to caller this.CompletedDelegate(phyShape); } private static PhysicsShape CreatePhysicsShapeFromConvexSetAndCache(MeshingStage meshingStage, ulong meshHash, List<PhysX.ConvexMeshGeometry> convexes) { PhysicsShape phyShape; phyShape = new PhysicsShape(convexes, meshHash); phyShape.Complexity = convexes.Count; phyShape.AddRef(); //complex shapes are cached meshingStage.CacheShape(meshHash, phyShape, ShapeType.DecomposedConvexHulls); return phyShape; } private void GenerateBasicShapeAndComplete(MeshingStage meshingStage, ulong meshHash) { Tuple<PhysX.Geometry, ShapeType> result = meshingStage.GenerateBasicPhysXShape(Shape); PhysicsShape phyShape = new PhysicsShape(result.Item1, result.Item2, meshHash); //basic shapes are not cached //we are done here, call back to caller this.CompletedDelegate(phyShape); } } /// <summary> /// Command to indicate to the meshing stage that the given shape is no longer referenced /// by a prim /// </summary> internal struct UnrefShapeItem : IMeshingQueueItem { public PhysicsShape Shape; public bool Dynamic; public void Execute(MeshingStage meshingStage) { if (Shape != null && Shape.DecRef() == 0) { if (Shape.Type == ShapeType.PrimitiveBox || Shape.Type == ShapeType.PrimitiveSphere || Shape.Type == ShapeType.Null) { //primitive shapes are not cached Shape.Dispose(); } else { meshingStage.UncacheShape(Shape.Hash, Shape, Shape.Type); } } } } /// <summary> /// Command to mesh the given heightfield to a triangle mesh /// </summary> internal struct MeshHeightfieldItem : IMeshingQueueItem { public float[] Terrain; public TerrainMeshingCompleteDelegate CompleteCallback; public void Execute(MeshingStage meshingStage) { Tuple<PhysX.Math.Vector3[], int[]> data = meshingStage._terrainMesher.GenerateTrimeshDataFromHeightmap(Terrain); Tuple<PhysX.TriangleMesh, MemoryStream> trimeshData = meshingStage._terrainMesher.GenerateTrimeshFromIndexedTriangles(data.Item1, data.Item2); CompleteCallback(trimeshData); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using System.Collections.Generic; using NPOI.OpenXmlFormats.Wordprocessing; using System.Text; using NPOI.Util; using System.Collections; using NPOI.WP.UserModel; /** * <p>A Paragraph within a Document, Table, Header etc.</p> * * <p>A paragraph has a lot of styling information, but the * actual text (possibly along with more styling) is held on * the child {@link XWPFRun}s.</p> */ public class XWPFParagraph : IBodyElement, IRunBody, ISDTContents, IParagraph { private CT_P paragraph; protected IBody part; /** For access to the document's hyperlink, comments, tables etc */ protected XWPFDocument document; protected List<XWPFRun> runs; protected List<IRunElement> iRuns; private StringBuilder footnoteText = new StringBuilder(); public XWPFParagraph(CT_P prgrph, IBody part) { this.paragraph = prgrph; this.part = part; this.document = part.GetXWPFDocument(); if (document == null) { throw new NullReferenceException(); } // Build up the character runs runs = new List<XWPFRun>(); iRuns = new List<IRunElement>(); BuildRunsInOrderFromXml(paragraph.Items); // Look for bits associated with the runs foreach (XWPFRun run in runs) { CT_R r = run.GetCTR(); if (document != null) { for (int i = 0; i < r.Items.Count; i++) { object o = r.Items[i]; if (o is CT_FtnEdnRef) { CT_FtnEdnRef ftn = (CT_FtnEdnRef)o; footnoteText.Append("[").Append(ftn.id).Append(": "); XWPFFootnote footnote = null; if (r.ItemsElementName.Count > i && r.ItemsElementName[i] == RunItemsChoiceType.endnoteReference) { footnote = document.GetEndnoteByID(int.Parse(ftn.id)); if (footnote == null) footnote = document.GetFootnoteByID(int.Parse(ftn.id)); } else { footnote = document.GetFootnoteByID(int.Parse(ftn.id)); if (footnote == null) footnote = document.GetEndnoteByID(int.Parse(ftn.id)); } if (footnote != null) { bool first = true; foreach (XWPFParagraph p in footnote.Paragraphs) { if (!first) { footnoteText.Append("\n"); first = false; } footnoteText.Append(p.Text); } } footnoteText.Append("]"); } } } } } /** * Identifies (in order) the parts of the paragraph / * sub-paragraph that correspond to character text * runs, and builds the appropriate runs for these. */ private void BuildRunsInOrderFromXml(ArrayList items) { foreach (object o in items) { if (o is CT_R) { XWPFRun r = new XWPFRun((CT_R)o, this); runs.Add(r); iRuns.Add(r); } if (o is CT_Hyperlink1) { CT_Hyperlink1 link = (CT_Hyperlink1)o; foreach (CT_R r in link.GetRList()) { //runs.Add(new XWPFHyperlinkRun(link, r, this)); XWPFHyperlinkRun hr = new XWPFHyperlinkRun(link, r, this); runs.Add(hr); iRuns.Add(hr); } } if (o is CT_SdtBlock) { XWPFSDT cc = new XWPFSDT((CT_SdtBlock)o, part); iRuns.Add(cc); } if (o is CT_SdtRun) { XWPFSDT cc = new XWPFSDT((CT_SdtRun)o, part); iRuns.Add(cc); } if (o is CT_RunTrackChange) { foreach (CT_R r in ((CT_RunTrackChange)o).GetRList()) { XWPFRun cr = new XWPFRun(r, this); runs.Add(cr); iRuns.Add(cr); } } if (o is CT_SimpleField) { foreach (CT_R r in ((CT_SimpleField)o).GetRList()) { XWPFRun cr = new XWPFRun(r, this); runs.Add(cr); iRuns.Add(cr); } } if (o is CT_SmartTagRun) { // Smart Tags can be nested many times. // This implementation does not preserve the tagging information BuildRunsInOrderFromXml((o as CT_SmartTagRun).Items); } } } internal CT_P GetCTP() { return paragraph; } public IList<XWPFRun> Runs { get { return runs.AsReadOnly(); } } /** * Return literal runs and sdt/content control objects. * @return List<IRunElement> */ public List<IRunElement> IRuns { get { return iRuns; } } public bool IsEmpty { get { //!paragraph.getDomNode().hasChildNodes(); //inner xml include objects holded by Items and pPr object //should use children of pPr node, but we didn't keep reference to it. //return paragraph.Items.Count == 0 && (paragraph.pPr == null || // paragraph.pPr != null && paragraph.pPr.rPr == null && paragraph.pPr.sectPr == null && paragraph.pPr.pPrChange == null // ); return paragraph.Items.Count == 0 && (paragraph.pPr == null || paragraph.pPr.IsEmpty); } } public XWPFDocument Document { get { return document; } } /** * Return the textual content of the paragraph, including text from pictures * and std element in it. */ public String Text { get { StringBuilder out1 = new StringBuilder(); foreach (IRunElement run in iRuns) { if (run is XWPFSDT) { out1.Append(((XWPFSDT)run).Content.Text); } else { out1.Append(run.ToString()); } } out1.Append(footnoteText); return out1.ToString(); } } /** * Return styleID of the paragraph if style exist for this paragraph * if not, null will be returned * @return styleID as String */ public String StyleID { get { if (paragraph.pPr != null) { if (paragraph.pPr.pStyle != null) { if (paragraph.pPr.pStyle.val != null) return paragraph.pPr.pStyle.val; } } return null; } } /** * If style exist for this paragraph * NumId of the paragraph will be returned. * If style not exist null will be returned * @return NumID as Bigint */ public string GetNumID() { if (paragraph.pPr != null) { if (paragraph.pPr.numPr != null) { if (paragraph.pPr.numPr.numId != null) return paragraph.pPr.numPr.numId.val; } } return null; } /** * Returns Ilvl of the numeric style for this paragraph. * Returns null if this paragraph does not have numeric style. * @return Ilvl as BigInteger */ public string GetNumIlvl() { if (paragraph.pPr != null) { if (paragraph.pPr.numPr != null) { if (paragraph.pPr.numPr.ilvl != null) return paragraph.pPr.numPr.ilvl.val; } } return null; } /** * Returns numbering format for this paragraph, eg bullet or * lowerLetter. * Returns null if this paragraph does not have numeric style. */ public String GetNumFmt() { string numID = GetNumID(); XWPFNumbering numbering = document.GetNumbering(); if (numID != null && numbering != null) { XWPFNum num = numbering.GetNum(numID); if (num != null) { string ilvl = GetNumIlvl(); string abstractNumId = num.GetCTNum().abstractNumId.val; CT_AbstractNum anum = numbering.GetAbstractNum(abstractNumId).GetAbstractNum(); CT_Lvl level = null; for (int i = 0; i < anum.lvl.Count; i++) { CT_Lvl lvl = anum.lvl[i]; if (lvl.ilvl.Equals(ilvl)) { level = lvl; break; } } if (level != null && level.numFmt != null) return level.numFmt.val.ToString(); } } return null; } /** * Returns the text that should be used around the paragraph level numbers. * * @return a string (e.g. "%1.") or null if the value is not found. */ public String NumLevelText { get { string numID = GetNumID(); XWPFNumbering numbering = document.CreateNumbering(); if (numID != null && numbering != null) { XWPFNum num = numbering.GetNum(numID); if (num != null) { string ilvl = GetNumIlvl(); CT_Num ctNum = num.GetCTNum(); if (ctNum == null) return null; CT_DecimalNumber ctDecimalNumber = ctNum.abstractNumId; if (ctDecimalNumber == null) return null; string abstractNumId = ctDecimalNumber.val; if (abstractNumId == null) return null; XWPFAbstractNum xwpfAbstractNum = numbering.GetAbstractNum(abstractNumId); if (xwpfAbstractNum == null) return null; CT_AbstractNum anum = xwpfAbstractNum.GetCTAbstractNum(); if (anum == null) return null; CT_Lvl level = null; for (int i = 0; i < anum.SizeOfLvlArray(); i++) { CT_Lvl lvl = anum.GetLvlArray(i); if (lvl != null && lvl.ilvl != null && lvl.ilvl.Equals(ilvl)) { level = lvl; break; } } if (level != null && level.lvlText != null && level.lvlText.val != null) return level.lvlText.val.ToString(); } } return null; } } /** * Gets the numstartOverride for the paragraph numbering for this paragraph. * @return returns the overridden start number or null if there is no override for this paragraph. */ public string GetNumStartOverride() { string numID = GetNumID(); XWPFNumbering numbering = document.CreateNumbering(); if (numID != null && numbering != null) { XWPFNum num = numbering.GetNum(numID); if (num != null) { CT_Num ctNum = num.GetCTNum(); if (ctNum == null) { return null; } string ilvl = GetNumIlvl(); CT_NumLvl level = null; for (int i = 0; i < ctNum.SizeOfLvlOverrideArray(); i++) { CT_NumLvl ctNumLvl = ctNum.GetLvlOverrideArray(i); if (ctNumLvl != null && ctNumLvl.ilvl != null && ctNumLvl.ilvl.Equals(ilvl)) { level = ctNumLvl; break; } } if (level != null && level.startOverride != null) { return level.startOverride.val; } } } return null; } /** * SetNumID of Paragraph * @param numPos */ public void SetNumID(string numId) { if (paragraph.pPr == null) paragraph.AddNewPPr(); if (paragraph.pPr.numPr == null) paragraph.pPr.AddNewNumPr(); if (paragraph.pPr.numPr.numId == null) { paragraph.pPr.numPr.AddNewNumId(); } paragraph.pPr.numPr.ilvl = new CT_DecimalNumber(); paragraph.pPr.numPr.ilvl.val = "0"; paragraph.pPr.numPr.numId.val = numId; } /// <summary> /// Set NumID and level of Paragraph /// </summary> /// <param name="numId"></param> /// <param name="ilvl"></param> public void SetNumID(string numId, string ilvl) { if (paragraph.pPr == null) paragraph.AddNewPPr(); if (paragraph.pPr.numPr == null) paragraph.pPr.AddNewNumPr(); if (paragraph.pPr.numPr.numId == null) { paragraph.pPr.numPr.AddNewNumId(); } paragraph.pPr.numPr.ilvl = new CT_DecimalNumber(); paragraph.pPr.numPr.ilvl.val = ilvl; paragraph.pPr.numPr.numId.val = (numId); } /** * Returns the text of the paragraph, but not of any objects in the * paragraph */ public String ParagraphText { get { StringBuilder text = new StringBuilder(); foreach (XWPFRun run in runs) { text.Append(run.ToString()); } return text.ToString(); } } /** * Returns any text from any suitable pictures in the paragraph */ public String PictureText { get { StringBuilder text = new StringBuilder(); foreach (XWPFRun run in runs) { text.Append(run.PictureText); } return text.ToString(); } } /** * Returns the footnote text of the paragraph * * @return the footnote text or empty string if the paragraph does not have footnotes */ public String FootnoteText { get { return footnoteText.ToString(); } } /** * Returns the paragraph alignment which shall be applied to text in this * paragraph. * <p> * If this element is not Set on a given paragraph, its value is determined * by the Setting previously Set at any level of the style hierarchy (i.e. * that previous Setting remains unChanged). If this Setting is never * specified in the style hierarchy, then no alignment is applied to the * paragraph. * </p> * * @return the paragraph alignment of this paragraph. */ public ParagraphAlignment Alignment { get { CT_PPr pr = GetCTPPr(); return pr == null || !pr.IsSetJc() ? ParagraphAlignment.LEFT : EnumConverter.ValueOf<ParagraphAlignment, ST_Jc>(pr.jc.val); } set { CT_PPr pr = GetCTPPr(); CT_Jc jc = pr.IsSetJc() ? pr.jc : pr.AddNewJc(); jc.val = EnumConverter.ValueOf<ST_Jc, ParagraphAlignment>(value); } } /** * @return The raw alignment value, {@link #getAlignment()} is suggested */ public int FontAlignment { get { return (int)Alignment; } set { Alignment = (ParagraphAlignment)value; } } /** * Returns the text vertical alignment which shall be applied to text in * this paragraph. * <p> * If the line height (before any Added spacing) is larger than one or more * characters on the line, all characters will be aligned to each other as * specified by this element. * </p> * <p> * If this element is omitted on a given paragraph, its value is determined * by the Setting previously Set at any level of the style hierarchy (i.e. * that previous Setting remains unChanged). If this Setting is never * specified in the style hierarchy, then the vertical alignment of all * characters on the line shall be automatically determined by the consumer. * </p> * * @return the vertical alignment of this paragraph. */ public TextAlignment VerticalAlignment { get { CT_PPr pr = GetCTPPr(); return (pr == null || !pr.IsSetTextAlignment()) ? TextAlignment.AUTO : EnumConverter.ValueOf<TextAlignment, ST_TextAlignment>(pr.textAlignment.val); } set { CT_PPr pr = GetCTPPr(); CT_TextAlignment textAlignment = pr.IsSetTextAlignment() ? pr .textAlignment : pr.AddNewTextAlignment(); //STTextAlignment.Enum en = STTextAlignment.Enum // .forInt(valign.Value); textAlignment.val = EnumConverter.ValueOf<ST_TextAlignment, TextAlignment>(value); } } /// <summary> /// the top border for the paragraph /// </summary> public Borders BorderTop { get { CT_PBdr border = GetCTPBrd(false); CT_Border ct = null; if (border != null) { ct = border.top; } ST_Border ptrn = (ct != null) ? ct.val : ST_Border.none; return EnumConverter.ValueOf<Borders, ST_Border>(ptrn); } set { CT_PBdr ct = GetCTPBrd(true); if (ct == null) { throw new RuntimeException("invalid paragraph state"); } CT_Border pr = ct.IsSetTop() ? ct.top : ct.AddNewTop(); if (value == Borders.None) ct.UnsetTop(); else pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value); } } /// <summary> ///Specifies the border which shall be displayed below a Set of /// paragraphs which have the same Set of paragraph border Settings. /// </summary> /// <returns>the bottom border for the paragraph</returns> public Borders BorderBottom { get { CT_PBdr border = GetCTPBrd(false); CT_Border ct = null; if (border != null) { ct = border.bottom; } ST_Border ptrn = ct != null ? ct.val : ST_Border.none; return EnumConverter.ValueOf<Borders, ST_Border>(ptrn); } set { CT_PBdr ct = GetCTPBrd(true); CT_Border pr = ct.IsSetBottom() ? ct.bottom : ct.AddNewBottom(); if (value == Borders.None) ct.UnsetBottom(); else pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value); } } /// <summary> /// Specifies the border which shall be displayed on the left side of the /// page around the specified paragraph. /// </summary> /// <returns>the left border for the paragraph</returns> public Borders BorderLeft { get { CT_PBdr border = GetCTPBrd(false); CT_Border ct = null; if (border != null) { ct = border.left; } ST_Border ptrn = ct != null ? ct.val : ST_Border.none; return EnumConverter.ValueOf<Borders, ST_Border>(ptrn); } set { CT_PBdr ct = GetCTPBrd(true); CT_Border pr = ct.IsSetLeft() ? ct.left : ct.AddNewLeft(); if (value == Borders.None) ct.UnsetLeft(); else pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value); } } /** * Specifies the border which shall be displayed on the right side of the * page around the specified paragraph. * * @return ParagraphBorder - the right border for the paragraph * @see #setBorderRight(Borders) * @see Borders for a list of all possible borders */ public Borders BorderRight { get { CT_PBdr border = GetCTPBrd(false); CT_Border ct = null; if (border != null) { ct = border.right; } ST_Border ptrn = ct != null ? ct.val : ST_Border.none; return EnumConverter.ValueOf<Borders, ST_Border>(ptrn); } set { CT_PBdr ct = GetCTPBrd(true); CT_Border pr = ct.IsSetRight() ? ct.right : ct.AddNewRight(); if (value == Borders.None) ct.UnsetRight(); else pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value); } } public ST_Shd FillPattern { get { if (!this.GetCTPPr().IsSetShd()) return ST_Shd.nil; return this.GetCTPPr().shd.val; } set { CT_Shd ctShd = null; if (!this.GetCTPPr().IsSetShd()) { ctShd = this.GetCTPPr().AddNewShd(); } else { ctShd = this.GetCTPPr().shd; } ctShd.val = value; } } public string FillBackgroundColor { get { if (!this.GetCTPPr().IsSetShd()) return null; return this.GetCTPPr().shd.fill; } set { CT_Shd ctShd = null; if (!this.GetCTPPr().IsSetShd()) { ctShd = this.GetCTPPr().AddNewShd(); } else { ctShd = this.GetCTPPr().shd; } ctShd.color = "auto"; ctShd.fill = value; } } /** * Specifies the border which shall be displayed between each paragraph in a * Set of paragraphs which have the same Set of paragraph border Settings. * * @return ParagraphBorder - the between border for the paragraph * @see #setBorderBetween(Borders) * @see Borders for a list of all possible borders */ public Borders BorderBetween { get { CT_PBdr border = GetCTPBrd(false); CT_Border ct = null; if (border != null) { ct = border.between; } ST_Border ptrn = ct != null ? ct.val : ST_Border.none; return EnumConverter.ValueOf<Borders, ST_Border>(ptrn); } set { CT_PBdr ct = GetCTPBrd(true); CT_Border pr = ct.IsSetBetween() ? ct.between : ct.AddNewBetween(); if (value == Borders.None) ct.UnsetBetween(); else pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value); } } /** * Specifies that when rendering this document in a paginated * view, the contents of this paragraph are rendered on the start of a new * page in the document. * <p> * If this element is omitted on a given paragraph, * its value is determined by the Setting previously Set at any level of the * style hierarchy (i.e. that previous Setting remains unChanged). If this * Setting is never specified in the style hierarchy, then this property * shall not be applied. Since the paragraph is specified to start on a new * page, it begins page two even though it could have fit on page one. * </p> * * @return bool - if page break is Set */ public bool IsPageBreak { get { CT_PPr ppr = GetCTPPr(); CT_OnOff ct_pageBreak = ppr.IsSetPageBreakBefore() ? ppr .pageBreakBefore : null; if (ct_pageBreak != null && ct_pageBreak.val) { return true; } return false; } set { CT_PPr ppr = GetCTPPr(); CT_OnOff ct_pageBreak = ppr.IsSetPageBreakBefore() ? ppr .pageBreakBefore : ppr.AddNewPageBreakBefore(); ct_pageBreak.val = value; } } /** * Specifies the spacing that should be Added After the last line in this * paragraph in the document in absolute units. * * @return int - value representing the spacing After the paragraph */ public int SpacingAfter { get { CT_Spacing spacing = GetCTSpacing(false); return (spacing != null && spacing.IsSetAfter()) ? (int)spacing.after : -1; } set { CT_Spacing spacing = GetCTSpacing(true); if (spacing != null) { //BigInteger bi = new BigInteger(spaces); spacing.after = (ulong)value; } } } /** * Specifies the spacing that should be Added After the last line in this * paragraph in the document in absolute units. * * @return bigint - value representing the spacing After the paragraph * @see #setSpacingAfterLines(int) */ public int SpacingAfterLines { get { CT_Spacing spacing = GetCTSpacing(false); return (spacing != null && spacing.IsSetAfterLines()) ? int.Parse(spacing.afterLines) : -1; } set { CT_Spacing spacing = GetCTSpacing(true); //BigInteger bi = new BigInteger("" + spaces); spacing.afterLines = value.ToString(); } } /** * Specifies the spacing that should be Added above the first line in this * paragraph in the document in absolute units. * * @return the spacing that should be Added above the first line * @see #setSpacingBefore(int) */ public int SpacingBefore { get { CT_Spacing spacing = GetCTSpacing(false); return (spacing != null && spacing.IsSetBefore()) ? (int)spacing.before : -1; } set { CT_Spacing spacing = GetCTSpacing(true); //BigInteger bi = new BigInteger("" + spaces); spacing.before = (ulong)value; } } /** * Specifies the spacing that should be Added before the first line in this paragraph in the * document in line units. * The value of this attribute is specified in one hundredths of a line. * * @return the spacing that should be Added before the first line in this paragraph * @see #setSpacingBeforeLines(int) */ public int SpacingBeforeLines { get { CT_Spacing spacing = GetCTSpacing(false); return (spacing != null && spacing.IsSetBeforeLines()) ? int.Parse(spacing.beforeLines) : -1; } set { CT_Spacing spacing = GetCTSpacing(true); //BigInteger bi = new BigInteger("" + spaces); spacing.beforeLines = value.ToString(); } } /** * Specifies how the spacing between lines is calculated as stored in the * line attribute. If this attribute is omitted, then it shall be assumed to * be of a value auto if a line attribute value is present. * * @return rule * @see LineSpacingRule * @see #setSpacingLineRule(LineSpacingRule) */ public LineSpacingRule SpacingLineRule { get { CT_Spacing spacing = GetCTSpacing(false); return (spacing != null && spacing.IsSetLineRule()) ? EnumConverter.ValueOf<LineSpacingRule, ST_LineSpacingRule>(spacing.lineRule) : LineSpacingRule.AUTO; } set { CT_Spacing spacing = GetCTSpacing(true); spacing.lineRule = EnumConverter.ValueOf<ST_LineSpacingRule, LineSpacingRule>(value); } } /** * Specifies the indentation which shall be placed between the left text * margin for this paragraph and the left edge of that paragraph's content * in a left to right paragraph, and the right text margin and the right * edge of that paragraph's text in a right to left paragraph * <p> * If this attribute is omitted, its value shall be assumed to be zero. * Negative values are defined such that the text is Moved past the text margin, * positive values Move the text inside the text margin. * </p> * * @return indentation or null if indentation is not Set */ public int IndentationLeft { get { CT_Ind indentation = GetCTInd(false); return (indentation != null && indentation.IsSetLeft()) ? int.Parse(indentation.left) : -1; } set { CT_Ind indent = GetCTInd(true); //BigInteger bi = new BigInteger("" + indentation); indent.left = value.ToString(); } } /** * Specifies the indentation which shall be placed between the right text * margin for this paragraph and the right edge of that paragraph's content * in a left to right paragraph, and the right text margin and the right * edge of that paragraph's text in a right to left paragraph * <p> * If this attribute is omitted, its value shall be assumed to be zero. * Negative values are defined such that the text is Moved past the text margin, * positive values Move the text inside the text margin. * </p> * * @return indentation or null if indentation is not Set */ public int IndentationRight { get { CT_Ind indentation = GetCTInd(false); return (indentation != null && indentation.IsSetRight()) ? int.Parse(indentation.right) : -1; } set { CT_Ind indent = GetCTInd(true); //BigInteger bi = new BigInteger("" + indentation); indent.right = value.ToString(); } } /** * Specifies the indentation which shall be Removed from the first line of * the parent paragraph, by moving the indentation on the first line back * towards the beginning of the direction of text flow. * This indentation is * specified relative to the paragraph indentation which is specified for * all other lines in the parent paragraph. * The firstLine and hanging * attributes are mutually exclusive, if both are specified, then the * firstLine value is ignored. * * @return indentation or null if indentation is not Set */ public int IndentationHanging { get { CT_Ind indentation = GetCTInd(false); return (indentation != null && indentation.IsSetHanging()) ? (int)indentation.hanging : -1; } set { CT_Ind indent = GetCTInd(true); //BigInteger bi = new BigInteger("" + indentation); indent.hanging = (ulong)value; } } /** * Specifies the Additional indentation which shall be applied to the first * line of the parent paragraph. This Additional indentation is specified * relative to the paragraph indentation which is specified for all other * lines in the parent paragraph. * The firstLine and hanging attributes are * mutually exclusive, if both are specified, then the firstLine value is * ignored. * If the firstLineChars attribute is also specified, then this * value is ignored. * If this attribute is omitted, then its value shall be * assumed to be zero (if needed). * * @return indentation or null if indentation is not Set */ public int IndentationFirstLine { get { CT_Ind indentation = GetCTInd(false); return (indentation != null && indentation.IsSetFirstLine()) ? (int)indentation.firstLine : -1; } set { CT_Ind indent = GetCTInd(true); //BigInteger bi = new BigInteger("" + indentation); indent.firstLine = (long)value; } } public int IndentFromLeft { get { return IndentationLeft; } set { IndentationLeft = value; } } public int IndentFromRight { get { return IndentationRight; } set { IndentationRight = value; } } public int FirstLineIndent { get { return IndentationFirstLine; } set { IndentationFirstLine = (value); } } /** * This element specifies whether a consumer shall break Latin text which * exceeds the text extents of a line by breaking the word across two lines * (breaking on the character level) or by moving the word to the following * line (breaking on the word level). * * @return bool */ public bool IsWordWrapped { get { CT_OnOff wordWrap = GetCTPPr().IsSetWordWrap() ? GetCTPPr() .wordWrap : null; if (wordWrap != null) { return wordWrap.val; } return false; } set { CT_OnOff wordWrap = GetCTPPr().IsSetWordWrap() ? GetCTPPr() .wordWrap : GetCTPPr().AddNewWordWrap(); if (value) wordWrap.val = true; else wordWrap.UnSetVal(); } } [Obsolete] public bool IsWordWrap { get { return IsWordWrapped; } set { IsWordWrapped = value; } } /** * @return the style of the paragraph */ public String Style { get { CT_PPr pr = GetCTPPr(); CT_String style = pr.IsSetPStyle() ? pr.pStyle : null; return style != null ? style.val : null; } set { CT_PPr pr = GetCTPPr(); CT_String style = pr.pStyle != null ? pr.pStyle : pr.AddNewPStyle(); style.val = value; } } /** * Get a <b>copy</b> of the currently used CTPBrd, if none is used, return * a new instance. */ private CT_PBdr GetCTPBrd(bool create) { CT_PPr pr = GetCTPPr(); CT_PBdr ct = pr.IsSetPBdr() ? pr.pBdr : null; if (create && ct == null) ct = pr.AddNewPBdr(); return ct; } /** * Get a <b>copy</b> of the currently used CTSpacing, if none is used, * return a new instance. */ private CT_Spacing GetCTSpacing(bool create) { CT_PPr pr = GetCTPPr(); CT_Spacing ct = pr.spacing == null ? null : pr.spacing; if (create && ct == null) ct = pr.AddNewSpacing(); return ct; } /** * Get a <b>copy</b> of the currently used CTPInd, if none is used, return * a new instance. */ private CT_Ind GetCTInd(bool create) { CT_PPr pr = GetCTPPr(); CT_Ind ct = pr.ind == null ? null : pr.ind; if (create && ct == null) ct = pr.AddNewInd(); return ct; } /** * Get a <b>copy</b> of the currently used CTPPr, if none is used, return * a new instance. */ internal CT_PPr GetCTPPr() { CT_PPr pr = paragraph.pPr == null ? paragraph.AddNewPPr() : paragraph.pPr; return pr; } /** * add a new run at the end of the position of * the content of parameter run * @param run */ protected internal void AddRun(CT_R Run) { int pos; pos = paragraph.GetRList().Count; paragraph.AddNewR(); paragraph.SetRArray(pos, Run); } /// <summary> /// Replace text inside each run (cross run is not supported yet) /// </summary> /// <param name="oldText">target text</param> /// <param name="newText">replacement text</param> public void ReplaceText(string oldText, string newText) { for (int i = 0; i < this.runs.Count; i++) { this.runs[i].ReplaceText(oldText, newText); } } /// <summary> /// this methods parse the paragraph and search for the string searched. /// If it finds the string, it will return true and the position of the String will be saved in the parameter startPos. /// </summary> /// <param name="searched"></param> /// <param name="startPos"></param> /// <returns></returns> public TextSegement SearchText(String searched, PositionInParagraph startPos) { int startRun = startPos.Run, startText = startPos.Text, startChar = startPos.Char; int beginRunPos = 0, candCharPos = 0; bool newList = false; for (int runPos = startRun; runPos < paragraph.GetRList().Count; runPos++) { int beginTextPos = 0, beginCharPos = 0, textPos = 0, charPos = 0; CT_R ctRun = paragraph.GetRList()[runPos]; foreach (object o in ctRun.Items) { if (o is CT_Text) { if (textPos >= startText) { String candidate = ((CT_Text)o).Value; if (runPos == startRun) charPos = startChar; else charPos = 0; for (; charPos < candidate.Length; charPos++) { if ((candidate[charPos] == searched[0]) && (candCharPos == 0)) { beginTextPos = textPos; beginCharPos = charPos; beginRunPos = runPos; newList = true; } if (candidate[charPos] == searched[candCharPos]) { if (candCharPos + 1 < searched.Length) { candCharPos++; } else if (newList) { TextSegement segement = new TextSegement(); segement.BeginRun = (beginRunPos); segement.BeginText = (beginTextPos); segement.BeginChar = (beginCharPos); segement.EndRun = (runPos); segement.EndText = (textPos); segement.EndChar = (charPos); return segement; } } else candCharPos = 0; } } textPos++; } else if (o is CT_ProofErr) { //c.RemoveXml(); } else if (o is CT_RPr) { //do nothing } else candCharPos = 0; } } return null; } /** * Appends a new run to this paragraph * * @return a new text run */ public XWPFRun CreateRun() { XWPFRun xwpfRun = new XWPFRun(paragraph.AddNewR(), this); runs.Add(xwpfRun); iRuns.Add(xwpfRun); return xwpfRun; } /** * insert a new Run in RunArray * @param pos * @return the inserted run */ public XWPFRun InsertNewRun(int pos) { if (pos >= 0 && pos <= paragraph.SizeOfRArray()) { CT_R ctRun = paragraph.InsertNewR(pos); XWPFRun newRun = new XWPFRun(ctRun, this); // To update the iRuns, find where we're going // in the normal Runs, and go in there int iPos = iRuns.Count; if (pos < runs.Count) { XWPFRun oldAtPos = runs[(pos)]; int oldAt = iRuns.IndexOf(oldAtPos); if (oldAt != -1) { iPos = oldAt; } } iRuns.Insert(iPos, newRun); // Runs itself is easy to update runs.Insert(pos, newRun); return newRun; } return null; } /** * Get a Text * @param segment */ public String GetText(TextSegement segment) { int RunBegin = segment.BeginRun; int textBegin = segment.BeginText; int charBegin = segment.BeginChar; int RunEnd = segment.EndRun; int textEnd = segment.EndText; int charEnd = segment.EndChar; StringBuilder text = new StringBuilder(); for (int i = RunBegin; i <= RunEnd; i++) { int startText = 0, endText = paragraph.GetRList()[i].GetTList().Count - 1; if (i == RunBegin) startText = textBegin; if (i == RunEnd) endText = textEnd; for (int j = startText; j <= endText; j++) { String tmpText = paragraph.GetRList()[i].GetTArray(j).Value; int startChar = 0, endChar = tmpText.Length - 1; if ((j == textBegin) && (i == RunBegin)) startChar = charBegin; if ((j == textEnd) && (i == RunEnd)) { endChar = charEnd; } text.Append(tmpText.Substring(startChar, endChar - startChar + 1)); } } return text.ToString(); } /** * Removes a Run at the position pos in the paragraph * @param pos * @return true if the run was Removed */ public bool RemoveRun(int pos) { if (pos >= 0 && pos < paragraph.SizeOfRArray()) { // Remove the run from our high level lists XWPFRun run = runs[(pos)]; runs.RemoveAt(pos); iRuns.Remove(run); // Remove the run from the low-level XML GetCTP().RemoveR(pos); return true; } return false; } /** * returns the type of the BodyElement Paragraph * @see NPOI.XWPF.UserModel.IBodyElement#getElementType() */ public BodyElementType ElementType { get { return BodyElementType.PARAGRAPH; } } public IBody Body { get { return part; } } /** * returns the part of the bodyElement * @see NPOI.XWPF.UserModel.IBody#getPart() */ public POIXMLDocumentPart Part { get { if (part != null) { return part.Part; } return null; } } /** * returns the partType of the bodyPart which owns the bodyElement * * @see NPOI.XWPF.UserModel.IBody#getPartType() */ public BodyType PartType { get { return part.PartType; } } /** * Adds a new Run to the Paragraph * * @param r */ public void AddRun(XWPFRun r) { if (!runs.Contains(r)) { runs.Add(r); } } /** * return the XWPFRun-Element which owns the CTR Run-Element * * @param r */ public XWPFRun GetRun(CT_R r) { for (int i = 0; i < runs.Count; i++) { if (runs[i].GetCTR() == r) { return runs[i]; } } return null; } }//end class }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Text; using System.Threading; using System.Xml; namespace System.Security.Cryptography.Xml { internal class Utils { // The maximum number of characters in an XML document (0 means no limit). internal const int MaxCharactersInDocument = 0; // The entity expansion limit. This is used to prevent entity expansion denial of service attacks. internal const long MaxCharactersFromEntities = (long)1e7; // The default XML Dsig recursion limit. // This should be within limits of real world scenarios. // Keeping this number low will preserve some stack space internal const int XmlDsigSearchDepth = 20; private Utils() { } private static bool HasNamespace(XmlElement element, string prefix, string value) { if (IsCommittedNamespace(element, prefix, value)) return true; if (element.Prefix == prefix && element.NamespaceURI == value) return true; return false; } // A helper function that determines if a namespace node is a committed attribute internal static bool IsCommittedNamespace(XmlElement element, string prefix, string value) { if (element == null) throw new ArgumentNullException(nameof(element)); string name = ((prefix.Length > 0) ? "xmlns:" + prefix : "xmlns"); if (element.HasAttribute(name) && element.GetAttribute(name) == value) return true; return false; } internal static bool IsRedundantNamespace(XmlElement element, string prefix, string value) { if (element == null) throw new ArgumentNullException(nameof(element)); XmlNode ancestorNode = ((XmlNode)element).ParentNode; while (ancestorNode != null) { XmlElement ancestorElement = ancestorNode as XmlElement; if (ancestorElement != null) if (HasNamespace(ancestorElement, prefix, value)) return true; ancestorNode = ancestorNode.ParentNode; } return false; } internal static string GetAttribute(XmlElement element, string localName, string namespaceURI) { string s = (element.HasAttribute(localName) ? element.GetAttribute(localName) : null); if (s == null && element.HasAttribute(localName, namespaceURI)) s = element.GetAttribute(localName, namespaceURI); return s; } internal static bool HasAttribute(XmlElement element, string localName, string namespaceURI) { return element.HasAttribute(localName) || element.HasAttribute(localName, namespaceURI); } internal static bool IsNamespaceNode(XmlNode n) { return n.NodeType == XmlNodeType.Attribute && (n.Prefix.Equals("xmlns") || (n.Prefix.Length == 0 && n.LocalName.Equals("xmlns"))); } internal static bool IsXmlNamespaceNode(XmlNode n) { return n.NodeType == XmlNodeType.Attribute && n.Prefix.Equals("xml"); } // We consider xml:space style attributes as default namespace nodes since they obey the same propagation rules internal static bool IsDefaultNamespaceNode(XmlNode n) { bool b1 = n.NodeType == XmlNodeType.Attribute && n.Prefix.Length == 0 && n.LocalName.Equals("xmlns"); bool b2 = IsXmlNamespaceNode(n); return b1 || b2; } internal static bool IsEmptyDefaultNamespaceNode(XmlNode n) { return IsDefaultNamespaceNode(n) && n.Value.Length == 0; } internal static string GetNamespacePrefix(XmlAttribute a) { Debug.Assert(IsNamespaceNode(a) || IsXmlNamespaceNode(a)); return a.Prefix.Length == 0 ? string.Empty : a.LocalName; } internal static bool HasNamespacePrefix(XmlAttribute a, string nsPrefix) { return GetNamespacePrefix(a).Equals(nsPrefix); } internal static bool IsNonRedundantNamespaceDecl(XmlAttribute a, XmlAttribute nearestAncestorWithSamePrefix) { if (nearestAncestorWithSamePrefix == null) return !IsEmptyDefaultNamespaceNode(a); else return !nearestAncestorWithSamePrefix.Value.Equals(a.Value); } internal static bool IsXmlPrefixDefinitionNode(XmlAttribute a) { return false; // return a.Prefix.Equals("xmlns") && a.LocalName.Equals("xml") && a.Value.Equals(NamespaceUrlForXmlPrefix); } internal static string DiscardWhiteSpaces(string inputBuffer) { return DiscardWhiteSpaces(inputBuffer, 0, inputBuffer.Length); } internal static string DiscardWhiteSpaces(string inputBuffer, int inputOffset, int inputCount) { int i, iCount = 0; for (i = 0; i < inputCount; i++) if (Char.IsWhiteSpace(inputBuffer[inputOffset + i])) iCount++; char[] rgbOut = new char[inputCount - iCount]; iCount = 0; for (i = 0; i < inputCount; i++) if (!Char.IsWhiteSpace(inputBuffer[inputOffset + i])) { rgbOut[iCount++] = inputBuffer[inputOffset + i]; } return new string(rgbOut); } internal static void SBReplaceCharWithString(StringBuilder sb, char oldChar, string newString) { int i = 0; int newStringLength = newString.Length; while (i < sb.Length) { if (sb[i] == oldChar) { sb.Remove(i, 1); sb.Insert(i, newString); i += newStringLength; } else i++; } } internal static XmlReader PreProcessStreamInput(Stream inputStream, XmlResolver xmlResolver, string baseUri) { XmlReaderSettings settings = GetSecureXmlReaderSettings(xmlResolver); XmlReader reader = XmlReader.Create(inputStream, settings, baseUri); return reader; } internal static XmlReaderSettings GetSecureXmlReaderSettings(XmlResolver xmlResolver) { XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = xmlResolver; settings.DtdProcessing = DtdProcessing.Parse; settings.MaxCharactersFromEntities = MaxCharactersFromEntities; settings.MaxCharactersInDocument = MaxCharactersInDocument; return settings; } internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlResolver xmlResolver, string baseUri) { if (document == null) throw new ArgumentNullException(nameof(document)); MyXmlDocument doc = new MyXmlDocument(); doc.PreserveWhitespace = document.PreserveWhitespace; // Normalize the document using (TextReader stringReader = new StringReader(document.OuterXml)) { XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = xmlResolver; settings.DtdProcessing = DtdProcessing.Parse; settings.MaxCharactersFromEntities = MaxCharactersFromEntities; settings.MaxCharactersInDocument = MaxCharactersInDocument; XmlReader reader = XmlReader.Create(stringReader, settings, baseUri); doc.Load(reader); } return doc; } internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string baseUri) { if (elem == null) throw new ArgumentNullException(nameof(elem)); MyXmlDocument doc = new MyXmlDocument(); doc.PreserveWhitespace = true; // Normalize the document using (TextReader stringReader = new StringReader(elem.OuterXml)) { XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = xmlResolver; settings.DtdProcessing = DtdProcessing.Parse; settings.MaxCharactersFromEntities = MaxCharactersFromEntities; settings.MaxCharactersInDocument = MaxCharactersInDocument; XmlReader reader = XmlReader.Create(stringReader, settings, baseUri); doc.Load(reader); } return doc; } internal static XmlDocument DiscardComments(XmlDocument document) { XmlNodeList nodeList = document.SelectNodes("//comment()"); if (nodeList != null) { foreach (XmlNode node1 in nodeList) { node1.ParentNode.RemoveChild(node1); } } return document; } internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComments) { CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); CanonicalXmlNodeList elementList = new CanonicalXmlNodeList(); CanonicalXmlNodeList attribList = new CanonicalXmlNodeList(); CanonicalXmlNodeList namespaceList = new CanonicalXmlNodeList(); int index = 0; elementList.Add(node); do { XmlNode rootNode = (XmlNode)elementList[index]; // Add the children nodes XmlNodeList childNodes = rootNode.ChildNodes; if (childNodes != null) { foreach (XmlNode node1 in childNodes) { if (includeComments || (!(node1 is XmlComment))) { elementList.Add(node1); } } } // Add the attribute nodes XmlAttributeCollection attribNodes = rootNode.Attributes; if (attribNodes != null) { foreach (XmlNode attribNode in rootNode.Attributes) { if (attribNode.LocalName == "xmlns" || attribNode.Prefix == "xmlns") namespaceList.Add(attribNode); else attribList.Add(attribNode); } } index++; } while (index < elementList.Count); foreach (XmlNode elementNode in elementList) { nodeList.Add(elementNode); } foreach (XmlNode attribNode in attribList) { nodeList.Add(attribNode); } foreach (XmlNode namespaceNode in namespaceList) { nodeList.Add(namespaceNode); } return nodeList; } internal static bool NodeInList(XmlNode node, XmlNodeList nodeList) { foreach (XmlNode nodeElem in nodeList) { if (nodeElem == node) return true; } return false; } internal static string GetIdFromLocalUri(string uri, out bool discardComments) { string idref = uri.Substring(1); // initialize the return value discardComments = true; // Deal with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal)) { int startId = idref.IndexOf("id(", StringComparison.Ordinal); int endId = idref.IndexOf(")", StringComparison.Ordinal); if (endId < 0 || endId < startId + 3) throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); idref = idref.Substring(startId + 3, endId - startId - 3); idref = idref.Replace("\'", ""); idref = idref.Replace("\"", ""); discardComments = false; } return idref; } internal static string ExtractIdFromLocalUri(string uri) { string idref = uri.Substring(1); // Deal with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal)) { int startId = idref.IndexOf("id(", StringComparison.Ordinal); int endId = idref.IndexOf(")", StringComparison.Ordinal); if (endId < 0 || endId < startId + 3) throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); idref = idref.Substring(startId + 3, endId - startId - 3); idref = idref.Replace("\'", ""); idref = idref.Replace("\"", ""); } return idref; } // This removes all children of an element. internal static void RemoveAllChildren(XmlElement inputElement) { XmlNode child = inputElement.FirstChild; XmlNode sibling = null; while (child != null) { sibling = child.NextSibling; inputElement.RemoveChild(child); child = sibling; } } // Writes one stream (starting from the current position) into // an output stream, connecting them up and reading until // hitting the end of the input stream. // returns the number of bytes copied internal static long Pump(Stream input, Stream output) { // Use MemoryStream's WriteTo(Stream) method if possible MemoryStream inputMS = input as MemoryStream; if (inputMS != null && inputMS.Position == 0) { inputMS.WriteTo(output); return inputMS.Length; } const int count = 4096; byte[] bytes = new byte[count]; int numBytes; long totalBytes = 0; while ((numBytes = input.Read(bytes, 0, count)) > 0) { output.Write(bytes, 0, numBytes); totalBytes += numBytes; } return totalBytes; } internal static Hashtable TokenizePrefixListString(string s) { Hashtable set = new Hashtable(); if (s != null) { string[] prefixes = s.Split(null); foreach (string prefix in prefixes) { if (prefix.Equals("#default")) { set.Add(string.Empty, true); } else if (prefix.Length > 0) { set.Add(prefix, true); } } } return set; } internal static string EscapeWhitespaceData(string data) { StringBuilder sb = new StringBuilder(); sb.Append(data); Utils.SBReplaceCharWithString(sb, (char)13, "&#xD;"); return sb.ToString(); ; } internal static string EscapeTextData(string data) { StringBuilder sb = new StringBuilder(); sb.Append(data); sb.Replace("&", "&amp;"); sb.Replace("<", "&lt;"); sb.Replace(">", "&gt;"); SBReplaceCharWithString(sb, (char)13, "&#xD;"); return sb.ToString(); ; } internal static string EscapeCData(string data) { return EscapeTextData(data); } internal static string EscapeAttributeValue(string value) { StringBuilder sb = new StringBuilder(); sb.Append(value); sb.Replace("&", "&amp;"); sb.Replace("<", "&lt;"); sb.Replace("\"", "&quot;"); SBReplaceCharWithString(sb, (char)9, "&#x9;"); SBReplaceCharWithString(sb, (char)10, "&#xA;"); SBReplaceCharWithString(sb, (char)13, "&#xD;"); return sb.ToString(); } internal static XmlDocument GetOwnerDocument(XmlNodeList nodeList) { foreach (XmlNode node in nodeList) { if (node.OwnerDocument != null) return node.OwnerDocument; } return null; } internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespaces) { if (namespaces != null) { foreach (XmlNode attrib in namespaces) { string name = ((attrib.Prefix.Length > 0) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName); // Skip the attribute if one with the same qualified name already exists if (elem.HasAttribute(name) || (name.Equals("xmlns") && elem.Prefix.Length == 0)) continue; XmlAttribute nsattrib = (XmlAttribute)elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = attrib.Value; elem.SetAttributeNode(nsattrib); } } } internal static void AddNamespaces(XmlElement elem, Hashtable namespaces) { if (namespaces != null) { foreach (string key in namespaces.Keys) { if (elem.HasAttribute(key)) continue; XmlAttribute nsattrib = (XmlAttribute)elem.OwnerDocument.CreateAttribute(key); nsattrib.Value = namespaces[key] as string; elem.SetAttributeNode(nsattrib); } } } // This method gets the attributes that should be propagated internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem) { if (elem == null) return null; CanonicalXmlNodeList namespaces = new CanonicalXmlNodeList(); XmlNode ancestorNode = elem; if (ancestorNode == null) return null; bool bDefNamespaceToAdd = true; while (ancestorNode != null) { XmlElement ancestorElement = ancestorNode as XmlElement; if (ancestorElement == null) { ancestorNode = ancestorNode.ParentNode; continue; } if (!Utils.IsCommittedNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { string name = ((ancestorElement.Prefix.Length > 0) ? "xmlns:" + ancestorElement.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = ancestorElement.NamespaceURI; namespaces.Add(nsattrib); } } if (ancestorElement.HasAttributes) { XmlAttributeCollection attribs = ancestorElement.Attributes; foreach (XmlAttribute attrib in attribs) { // Add a default namespace if necessary if (bDefNamespaceToAdd && attrib.LocalName == "xmlns") { XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute("xmlns"); nsattrib.Value = attrib.Value; namespaces.Add(nsattrib); bDefNamespaceToAdd = false; continue; } // retain the declarations of type 'xml:*' as well if (attrib.Prefix == "xmlns" || attrib.Prefix == "xml") { namespaces.Add(attrib); continue; } if (attrib.NamespaceURI.Length > 0) { if (!Utils.IsCommittedNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { string name = ((attrib.Prefix.Length > 0) ? "xmlns:" + attrib.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = attrib.NamespaceURI; namespaces.Add(nsattrib); } } } } } ancestorNode = ancestorNode.ParentNode; } return namespaces; } // output of this routine is always big endian internal static byte[] ConvertIntToByteArray(int dwInput) { byte[] rgbTemp = new byte[8]; // int can never be greater than Int64 int t1; // t1 is remaining value to account for int t2; // t2 is t1 % 256 int i = 0; if (dwInput == 0) return new byte[1]; t1 = dwInput; while (t1 > 0) { t2 = t1 % 256; rgbTemp[i] = (byte)t2; t1 = (t1 - t2) / 256; i++; } // Now, copy only the non-zero part of rgbTemp and reverse byte[] rgbOutput = new byte[i]; // copy and reverse in one pass for (int j = 0; j < i; j++) { rgbOutput[j] = rgbTemp[i - j - 1]; } return rgbOutput; } internal static int GetHexArraySize(byte[] hex) { int index = hex.Length; while (index-- > 0) { if (hex[index] != 0) break; } return index + 1; } internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType) { X509Certificate2Collection collection = new X509Certificate2Collection(); ArrayList decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null); if (keyInfoX509Data.Certificates != null) { foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates) { switch (certUsageType) { case CertUsageType.Verification: collection.Add(certificate); break; case CertUsageType.Decryption: decryptionIssuerSerials.Add(new X509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber)); break; } } } if (keyInfoX509Data.SubjectNames == null && keyInfoX509Data.IssuerSerials == null && keyInfoX509Data.SubjectKeyIds == null && decryptionIssuerSerials == null) return collection; // Open LocalMachine and CurrentUser "Other People"/"My" stores. X509Store[] stores = new X509Store[2]; string storeName = (certUsageType == CertUsageType.Verification ? "AddressBook" : "My"); stores[0] = new X509Store(storeName, StoreLocation.CurrentUser); stores[1] = new X509Store(storeName, StoreLocation.LocalMachine); for (int index = 0; index < stores.Length; index++) { if (stores[index] != null) { X509Certificate2Collection filters = null; // We don't care if we can't open the store. try { stores[index].Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); filters = stores[index].Certificates; stores[index].Close(); if (keyInfoX509Data.SubjectNames != null) { foreach (string subjectName in keyInfoX509Data.SubjectNames) { filters = filters.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false); } } if (keyInfoX509Data.IssuerSerials != null) { foreach (X509IssuerSerial issuerSerial in keyInfoX509Data.IssuerSerials) { filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false); filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false); } } if (keyInfoX509Data.SubjectKeyIds != null) { foreach (byte[] ski in keyInfoX509Data.SubjectKeyIds) { string hex = EncodeHexString(ski); filters = filters.Find(X509FindType.FindBySubjectKeyIdentifier, hex, false); } } if (decryptionIssuerSerials != null) { foreach (X509IssuerSerial issuerSerial in decryptionIssuerSerials) { filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false); filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false); } } } catch (CryptographicException) { } if (filters != null) collection.AddRange(filters); } } return collection; } private static readonly char[] s_hexValues = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; internal static string EncodeHexString(byte[] sArray) { return EncodeHexString(sArray, 0, (uint)sArray.Length); } internal static string EncodeHexString(byte[] sArray, uint start, uint end) { string result = null; if (sArray != null) { char[] hexOrder = new char[(end - start) * 2]; uint digit; for (uint i = start, j = 0; i < end; i++) { digit = (uint)((sArray[i] & 0xf0) >> 4); hexOrder[j++] = s_hexValues[digit]; digit = (uint)(sArray[i] & 0x0f); hexOrder[j++] = s_hexValues[digit]; } result = new String(hexOrder); } return result; } internal static byte[] DecodeHexString(string s) { string hexString = Utils.DiscardWhiteSpaces(s); uint cbHex = (uint)hexString.Length / 2; byte[] hex = new byte[cbHex]; int i = 0; for (int index = 0; index < cbHex; index++) { hex[index] = (byte)((HexToByte(hexString[i]) << 4) | HexToByte(hexString[i + 1])); i += 2; } return hex; } internal static byte HexToByte(char val) { if (val <= '9' && val >= '0') return (byte)(val - '0'); else if (val >= 'a' && val <= 'f') return (byte)((val - 'a') + 10); else if (val >= 'A' && val <= 'F') return (byte)((val - 'A') + 10); else return 0xFF; } internal static bool IsSelfSigned(X509Chain chain) { X509ChainElementCollection elements = chain.ChainElements; if (elements.Count != 1) return false; X509Certificate2 certificate = elements[0].Certificate; if (String.Compare(certificate.SubjectName.Name, certificate.IssuerName.Name, StringComparison.OrdinalIgnoreCase) == 0) return true; return false; } internal static AsymmetricAlgorithm GetAnyPublicKey(X509Certificate2 certificate) { // TODO: Add ?? certificate.GetDSAPublicKey(), when available (dotnet/corefx#11802). return certificate.GetRSAPublicKey(); } } }
using MySqlConnector.Logging; using MySqlConnector.Protocol; using MySqlConnector.Protocol.Serialization; using MySqlConnector.Utilities; namespace MySqlConnector.Core; internal sealed class SingleCommandPayloadCreator : ICommandPayloadCreator { public static ICommandPayloadCreator Instance { get; } = new SingleCommandPayloadCreator(); // This is chosen to be something very unlikely to appear as a column name in a user's query. If a result set is read // with this as the first column name, the result set will be treated as 'out' parameters for the previous command. public static string OutParameterSentinelColumnName => "\uE001\b\x0B"; public bool WriteQueryCommand(ref CommandListPosition commandListPosition, IDictionary<string, CachedProcedure?> cachedProcedures, ByteBufferWriter writer, bool appendSemicolon) { if (commandListPosition.CommandIndex == commandListPosition.Commands.Count) return false; var command = commandListPosition.Commands[commandListPosition.CommandIndex]; var preparedStatements = command.TryGetPreparedStatements(); if (preparedStatements is null) { if (Log.IsTraceEnabled()) Log.Trace("Session{0} Preparing command payload; CommandText: {1}", command.Connection!.Session.Id, command.CommandText); writer.Write((byte) CommandKind.Query); var supportsQueryAttributes = command.Connection!.Session.SupportsQueryAttributes; if (supportsQueryAttributes) { // attribute count var attributes = command.RawAttributes; writer.WriteLengthEncodedInteger((uint) (attributes?.Count ?? 0)); // attribute set count (always 1) writer.Write((byte) 1); if (attributes?.Count > 0) WriteBinaryParameters(writer, attributes.Select(x => x.ToParameter()).ToArray(), command, true, 0); } else if (command.RawAttributes?.Count > 0) { Log.Warn("Session{0} has query attributes but server doesn't support them; CommandText: {1}", command.Connection!.Session.Id, command.CommandText); } WriteQueryPayload(command, cachedProcedures, writer, appendSemicolon); commandListPosition.CommandIndex++; } else { writer.Write((byte) CommandKind.StatementExecute); WritePreparedStatement(command, preparedStatements.Statements[commandListPosition.PreparedStatementIndex], writer); // advance to next prepared statement or next command if (++commandListPosition.PreparedStatementIndex == preparedStatements.Statements.Count) { commandListPosition.CommandIndex++; commandListPosition.PreparedStatementIndex = 0; } } return true; } /// <summary> /// Writes the text of <paramref name="command"/> to <paramref name="writer"/>, encoded in UTF-8. /// </summary> /// <param name="command">The command.</param> /// <param name="cachedProcedures">The cached procedures.</param> /// <param name="writer">The output writer.</param> /// <param name="appendSemicolon">Whether a statement-separating semicolon should be appended if it's missing.</param> /// <returns><c>true</c> if a complete command was written; otherwise, <c>false</c>.</returns> public static bool WriteQueryPayload(IMySqlCommand command, IDictionary<string, CachedProcedure?> cachedProcedures, ByteBufferWriter writer, bool appendSemicolon) => (command.CommandType == CommandType.StoredProcedure) ? WriteStoredProcedure(command, cachedProcedures, writer) : WriteCommand(command, writer, appendSemicolon); private static void WritePreparedStatement(IMySqlCommand command, PreparedStatement preparedStatement, ByteBufferWriter writer) { var parameterCollection = command.RawParameters; if (Log.IsTraceEnabled()) Log.Trace("Session{0} Preparing command payload; CommandId: {1}; CommandText: {2}", command.Connection!.Session.Id, preparedStatement.StatementId, command.CommandText); var attributes = command.RawAttributes; var supportsQueryAttributes = command.Connection!.Session.SupportsQueryAttributes; writer.Write(preparedStatement.StatementId); // NOTE: documentation is not updated yet, but due to bugs in MySQL Server 8.0.23-8.0.25, the PARAMETER_COUNT_AVAILABLE (0x08) // flag has to be set in the 'flags' block in order for query attributes to be sent with a prepared statement. var sendQueryAttributes = supportsQueryAttributes && command.Connection.Session.ServerVersion.Version is not { Major: 8, Minor: 0, Build: >= 23 and <= 25 }; writer.Write((byte) (sendQueryAttributes ? 8 : 0)); writer.Write(1); var commandParameterCount = preparedStatement.Statement.ParameterNames?.Count ?? 0; var attributeCount = attributes?.Count ?? 0; if (sendQueryAttributes) { writer.WriteLengthEncodedInteger((uint) (commandParameterCount + attributeCount)); } else { if (supportsQueryAttributes && commandParameterCount > 0) writer.WriteLengthEncodedInteger((uint) commandParameterCount); if (attributeCount > 0) { Log.Warn("Session{0} has attributes for CommandId {1} but the server does not support them", command.Connection!.Session.Id, preparedStatement.StatementId); attributeCount = 0; } } if (commandParameterCount > 0 || attributeCount > 0) { // TODO: How to handle incorrect number of parameters? // build subset of parameters for this statement var parameters = new MySqlParameter[commandParameterCount + attributeCount]; for (var i = 0; i < commandParameterCount; i++) { var parameterName = preparedStatement.Statement.ParameterNames![i]; var parameterIndex = parameterName is not null ? (parameterCollection?.NormalizedIndexOf(parameterName) ?? -1) : preparedStatement.Statement.ParameterIndexes[i]; if (parameterIndex == -1 && parameterName is not null) throw new MySqlException("Parameter '{0}' must be defined.".FormatInvariant(parameterName)); else if (parameterIndex < 0 || parameterIndex >= (parameterCollection?.Count ?? 0)) throw new MySqlException("Parameter index {0} is invalid when only {1} parameter{2} defined.".FormatInvariant(parameterIndex, parameterCollection?.Count ?? 0, parameterCollection?.Count == 1 ? " is" : "s are")); parameters[i] = parameterCollection![parameterIndex]; } for (var i = 0; i < attributeCount; i++) parameters[commandParameterCount + i] = attributes![i].ToParameter(); WriteBinaryParameters(writer, parameters, command, supportsQueryAttributes, commandParameterCount); } } private static void WriteBinaryParameters(ByteBufferWriter writer, MySqlParameter[] parameters, IMySqlCommand command, bool supportsQueryAttributes, int parameterCount) { // write null bitmap byte nullBitmap = 0; for (var i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; if (parameter.Value is null || parameter.Value == DBNull.Value) nullBitmap |= (byte) (1 << (i % 8)); if (i % 8 == 7) { writer.Write(nullBitmap); nullBitmap = 0; } } if (parameters.Length % 8 != 0) writer.Write(nullBitmap); // write "new parameters bound" flag writer.Write((byte) 1); for (var index = 0; index < parameters.Length; index++) { // override explicit MySqlDbType with inferred type from the Value var parameter = parameters[index]; var mySqlDbType = parameter.MySqlDbType; var typeMapping = (parameter.Value is null || parameter.Value == DBNull.Value) ? null : TypeMapper.Instance.GetDbTypeMapping(parameter.Value.GetType()); if (typeMapping is not null) { var dbType = typeMapping.DbTypes[0]; mySqlDbType = TypeMapper.Instance.GetMySqlDbTypeForDbType(dbType); } writer.Write(TypeMapper.ConvertToColumnTypeAndFlags(mySqlDbType, command.Connection!.GuidFormat)); if (supportsQueryAttributes) { if (index < parameterCount) writer.Write((byte) 0); // empty string else writer.WriteLengthEncodedString(parameter.ParameterName); } } var options = command.CreateStatementPreparerOptions(); foreach (var parameter in parameters) parameter.AppendBinary(writer, options); } private static bool WriteStoredProcedure(IMySqlCommand command, IDictionary<string, CachedProcedure?> cachedProcedures, ByteBufferWriter writer) { var parameterCollection = command.RawParameters; var cachedProcedure = cachedProcedures[command.CommandText!]; if (cachedProcedure is not null) parameterCollection = cachedProcedure.AlignParamsWithDb(parameterCollection); MySqlParameter? returnParameter = null; var outParameters = new MySqlParameterCollection(); var outParameterNames = new List<string>(); var inParameters = new MySqlParameterCollection(); var argParameterNames = new List<string>(); var inOutSetParameters = ""; for (var i = 0; i < (parameterCollection?.Count ?? 0); i++) { var param = parameterCollection![i]; var inName = "@inParam" + i; var outName = "@outParam" + i; switch (param.Direction) { case ParameterDirection.Input: case ParameterDirection.InputOutput: var inParam = param.WithParameterName(inName); inParameters.Add(inParam); if (param.Direction == ParameterDirection.InputOutput) { inOutSetParameters += $"SET {outName}={inName}; "; goto case ParameterDirection.Output; } argParameterNames.Add(inName); break; case ParameterDirection.Output: outParameters.Add(param); outParameterNames.Add(outName); argParameterNames.Add(outName); break; case ParameterDirection.ReturnValue: returnParameter = param; break; } } // if a return param is set, assume it is a function; otherwise, assume stored procedure var commandText = command.CommandText + "(" + string.Join(", ", argParameterNames) + ");"; if (returnParameter is null) { commandText = inOutSetParameters + "CALL " + commandText; if (outParameters.Count > 0 && (command.CommandBehavior & CommandBehavior.SchemaOnly) == 0) { commandText += "SELECT '" + OutParameterSentinelColumnName + "' AS '" + OutParameterSentinelColumnName + "', " + string.Join(", ", outParameterNames); } } else { commandText = "SELECT " + commandText; } command.OutParameters = outParameters; command.ReturnParameter = returnParameter; var preparer = new StatementPreparer(commandText, inParameters, command.CreateStatementPreparerOptions()); return preparer.ParseAndBindParameters(writer); } private static bool WriteCommand(IMySqlCommand command, ByteBufferWriter writer, bool appendSemicolon) { var isSchemaOnly = (command.CommandBehavior & CommandBehavior.SchemaOnly) != 0; var isSingleRow = (command.CommandBehavior & CommandBehavior.SingleRow) != 0; if (isSchemaOnly) { ReadOnlySpan<byte> setSqlSelectLimit0 = new byte[] { 83, 69, 84, 32, 115, 113, 108, 95, 115, 101, 108, 101, 99, 116, 95, 108, 105, 109, 105, 116, 61, 48, 59, 10 }; // SET sql_select_limit=0;\n writer.Write(setSqlSelectLimit0); } else if (isSingleRow) { ReadOnlySpan<byte> setSqlSelectLimit1 = new byte[] { 83, 69, 84, 32, 115, 113, 108, 95, 115, 101, 108, 101, 99, 116, 95, 108, 105, 109, 105, 116, 61, 49, 59, 10 }; // SET sql_select_limit=1;\n writer.Write(setSqlSelectLimit1); } var preparer = new StatementPreparer(command.CommandText!, command.RawParameters, command.CreateStatementPreparerOptions() | ((appendSemicolon || isSchemaOnly || isSingleRow) ? StatementPreparerOptions.AppendSemicolon : StatementPreparerOptions.None)); var isComplete = preparer.ParseAndBindParameters(writer); if (isComplete && (isSchemaOnly || isSingleRow)) { ReadOnlySpan<byte> clearSqlSelectLimit = new byte[] { 10, 83, 69, 84, 32, 115, 113, 108, 95, 115, 101, 108, 101, 99, 116, 95, 108, 105, 109, 105, 116, 61, 100, 101, 102, 97, 117, 108, 116, 59 }; // \nSET sql_select_limit=default; writer.Write(clearSqlSelectLimit); } return isComplete; } private static readonly IMySqlConnectorLogger Log = MySqlConnectorLogManager.CreateLogger(nameof(SingleCommandPayloadCreator)); }
//------------------------------------------------------------------------------ // <copyright file="PrintDocument.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Drawing.Printing { using Microsoft.Win32; using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Reflection; using System.Security; using System.Security.Permissions; using System.IO; using System.Runtime.Versioning; /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument"]/*' /> /// <devdoc> /// <para>Defines a reusable object that sends output to the /// printer.</para> /// </devdoc> [ ToolboxItemFilter("System.Drawing.Printing"), DefaultProperty("DocumentName"), SRDescription(SR.PrintDocumentDesc), DefaultEvent("PrintPage") ] public class PrintDocument : Component { private string documentName = "document"; private PrintEventHandler beginPrintHandler; private PrintEventHandler endPrintHandler; private PrintPageEventHandler printPageHandler; private QueryPageSettingsEventHandler queryHandler; private PrinterSettings printerSettings = new PrinterSettings(); private PageSettings defaultPageSettings; private PrintController printController; private bool originAtMargins; private bool userSetPageSettings; /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.PrintDocument"]/*' /> /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Drawing.Printing.PrintDocument'/> /// class.</para> /// </devdoc> public PrintDocument() { defaultPageSettings = new PageSettings(printerSettings); } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.DefaultPageSettings"]/*' /> /// <devdoc> /// <para>Gets or sets the /// default /// page settings for the document being printed.</para> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(SR.PDOCdocumentPageSettingsDescr) ] public PageSettings DefaultPageSettings { get { return defaultPageSettings;} set { if (value == null) value = new PageSettings(); defaultPageSettings = value; userSetPageSettings = true; } } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.DocumentName"]/*' /> /// <devdoc> /// <para>Gets or sets the name to display to the user while printing the document; /// for example, in a print status dialog or a printer /// queue.</para> /// </devdoc> [ DefaultValue("document"), SRDescription(SR.PDOCdocumentNameDescr) ] public string DocumentName { get { return documentName;} set { if (value == null) value = ""; documentName = value; } } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OriginAtMargins"]/*' /> // If true, positions the origin of the graphics object // associated with the page at the point just inside // the user-specified margins of the page. // If false, the graphics origin is at the top-left // corner of the printable area of the page. // [ DefaultValue(false), SRDescription(SR.PDOCoriginAtMarginsDescr) ] public bool OriginAtMargins { get { return originAtMargins; } set { originAtMargins = value; } } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.PrintController"]/*' /> /// <devdoc> /// <para>Gets or sets the <see cref='System.Drawing.Printing.PrintController'/> /// that guides the printing process.</para> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(SR.PDOCprintControllerDescr) ] public PrintController PrintController { get { IntSecurity.SafePrinting.Demand(); if (printController == null) { printController = new StandardPrintController(); new ReflectionPermission(PermissionState.Unrestricted).Assert(); try { try { // SECREVIEW 332064: this is here because System.Drawing doesnt want a dependency on // System.Windows.Forms. Since this creates a public type in another assembly, this // appears to be OK. Type type = Type.GetType("System.Windows.Forms.PrintControllerWithStatusDialog, " + AssemblyRef.SystemWindowsForms); printController = (PrintController) Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, new object[] { printController}, null); } catch (TypeLoadException) { Debug.Fail("Can't find System.Windows.Forms.PrintControllerWithStatusDialog, proceeding with StandardPrintController"); } catch (TargetInvocationException) { Debug.Fail("Can't find System.Windows.Forms.PrintControllerWithStatusDialog, proceeding with StandardPrintController"); } catch (MissingMethodException) { Debug.Fail("Can't find System.Windows.Forms.PrintControllerWithStatusDialog, proceeding with StandardPrintController"); } catch (MethodAccessException) { Debug.Fail("Can't find System.Windows.Forms.PrintControllerWithStatusDialog, proceeding with StandardPrintController"); } catch (MemberAccessException) { Debug.Fail("Can't find System.Windows.Forms.PrintControllerWithStatusDialog, proceeding with StandardPrintController"); } catch (FileNotFoundException) { Debug.Fail("Can't find System.Windows.Forms.PrintControllerWithStatusDialog, proceeding with StandardPrintController"); } } finally { CodeAccessPermission.RevertAssert(); } } return printController; } set { IntSecurity.SafePrinting.Demand(); printController = value; } } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.PrinterSettings"]/*' /> /// <devdoc> /// <para> Gets or sets the printer on which the /// document is printed.</para> /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(SR.PDOCprinterSettingsDescr) ] public PrinterSettings PrinterSettings { get { return printerSettings;} set { if (value == null) value = new PrinterSettings(); printerSettings = value; // reset the PageSettings that match the PrinterSettings only if we have created the defaultPageSettings.. if (!userSetPageSettings) { defaultPageSettings = printerSettings.DefaultPageSettings; } } } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.BeginPrint"]/*' /> /// <devdoc> /// <para>Occurs when the <see cref='System.Drawing.Printing.PrintDocument.Print'/> method is called, before /// the /// first page prints.</para> /// </devdoc> [SRDescription(SR.PDOCbeginPrintDescr)] public event PrintEventHandler BeginPrint { add { beginPrintHandler += value; } remove { beginPrintHandler -= value; } } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.EndPrint"]/*' /> /// <devdoc> /// <para>Occurs when <see cref='System.Drawing.Printing.PrintDocument.Print'/> is /// called, after the last page is printed.</para> /// </devdoc> [SRDescription(SR.PDOCendPrintDescr)] public event PrintEventHandler EndPrint { add { endPrintHandler += value; } remove { endPrintHandler -= value; } } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.PrintPage"]/*' /> /// <devdoc> /// <para>Occurs when a page is printed. </para> /// </devdoc> [SRDescription(SR.PDOCprintPageDescr)] public event PrintPageEventHandler PrintPage { add { printPageHandler += value; } remove { printPageHandler -= value; } } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.QueryPageSettings"]/*' /> /// <devdoc> /// <para>Occurs</para> /// </devdoc> [SRDescription(SR.PDOCqueryPageSettingsDescr)] public event QueryPageSettingsEventHandler QueryPageSettings { add { queryHandler += value; } remove { queryHandler -= value; } } internal void _OnBeginPrint(PrintEventArgs e) { OnBeginPrint(e); } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OnBeginPrint"]/*' /> /// <devdoc> /// <para>Raises the <see cref='E:System.Drawing.Printing.PrintDocument.BeginPrint'/> /// event.</para> /// </devdoc> protected virtual void OnBeginPrint(PrintEventArgs e) { if (beginPrintHandler != null) beginPrintHandler(this, e); } internal void _OnEndPrint(PrintEventArgs e) { OnEndPrint(e); } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OnEndPrint"]/*' /> /// <devdoc> /// <para>Raises the <see cref='E:System.Drawing.Printing.PrintDocument.EndPrint'/> /// event.</para> /// </devdoc> protected virtual void OnEndPrint(PrintEventArgs e) { if (endPrintHandler != null) endPrintHandler(this, e); } internal void _OnPrintPage(PrintPageEventArgs e) { OnPrintPage(e); } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OnPrintPage"]/*' /> /// <devdoc> /// <para>Raises the <see cref='E:System.Drawing.Printing.PrintDocument.PrintPage'/> /// event.</para> /// </devdoc> // protected virtual void OnPrintPage(PrintPageEventArgs e) { if (printPageHandler != null) printPageHandler(this, e); } internal void _OnQueryPageSettings(QueryPageSettingsEventArgs e) { OnQueryPageSettings(e); } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.OnQueryPageSettings"]/*' /> /// <devdoc> /// <para>Raises the <see cref='E:System.Drawing.Printing.PrintDocument.QueryPageSettings'/> event.</para> /// </devdoc> protected virtual void OnQueryPageSettings(QueryPageSettingsEventArgs e) { if (queryHandler != null) queryHandler(this, e); } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.Print"]/*' /> /// <devdoc> /// <para> /// Prints the document. /// </para> /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public void Print() { // It is possible to SetPrinterName using signed secured dll which can be used to by-pass Printing security model. // hence here check if the PrinterSettings.IsDefaultPrinter and if not demand AllPrinting. // Refer : VsWhidbey : 235920 if (!this.PrinterSettings.IsDefaultPrinter && !this.PrinterSettings.PrintDialogDisplayed) { IntSecurity.AllPrinting.Demand(); } PrintController controller = PrintController; controller.Print(this); } /// <include file='doc\PrintDocument.uex' path='docs/doc[@for="PrintDocument.ToString"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Provides some interesting information about the PrintDocument in /// String form. /// </para> /// </devdoc> public override string ToString() { return "[PrintDocument " + DocumentName + "]"; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Census Student Data /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SCEN_ST : EduHubEntity { /// <inheritdoc /> public override DateTime? EntityLastModified { get { return null; } } #region Field Properties /// <summary> /// &lt;No documentation available&gt; /// </summary> public int ID { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string C_SOURCE { get; internal set; } /// <summary> /// Student Key of the student on the day that the Census process is run. /// [Uppercase Alphanumeric (10)] /// </summary> public string STKEY { get; internal set; } /// <summary> /// Automatically generated number /// </summary> public int? REGISTRATION { get; internal set; } /// <summary> /// Surname of the student /// [Uppercase Alphanumeric (30)] /// </summary> public string SURNAME { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (20)] /// </summary> public string FIRST_NAME { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (20)] /// </summary> public string SECOND_NAME { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string GENDER { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (6)] /// </summary> public string C_AGE_1st_JAN { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (6)] /// </summary> public string C_AGE_1st_JULY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public DateTime? AUSSIE_SCHOOL { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public DateTime? BIRTHDATE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DISABILITY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (6)] /// </summary> public string DISABILITY_ID { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public DateTime? ENTRY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string STATUS { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (3)] /// </summary> public string HOME_GROUP { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (3)] /// </summary> public string KGC_HOME_GROUP { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (7)] /// </summary> public string HOME_LANG { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string KGL_ASCL { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (75)] /// </summary> public string KGL_DESCRIPTION { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (7)] /// </summary> public string LOTE_HOME_CODE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string KGL_LOTE_HOME_ASCL { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Alphanumeric (75)] /// </summary> public string KGL_LOTE_HOME_DESCRIPTION { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string IMMUNIZE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DIPTHERIA_S { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string TETANUS_S { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string POLIO_S { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string PERTUSSIS_S { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string HAEMOPHILUSB_S { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string MMR_S { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string IMMUN_CERT_STATUS { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string KOORIE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string C_MOBILITY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string SGB_FUNDED { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (6)] /// </summary> public string BIRTH_COUNTRY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string KGT_SACC { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (40)] /// </summary> public string KGT_DESCRIPTION { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string KGT_ENGLISH_SPEAKING { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string RESIDENT_STATUS { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string PERMANENT_BASIS { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (3)] /// </summary> public string VISA_SUBCLASS { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string VISA_STAT_CODE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (3)] /// </summary> public string KCV_VISA_SUBCLASS { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string KCV_SGB_FUNDED { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string KCV_CHECK_STAT_CODE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string KCV_VISA_RESIDENCY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (5)] /// </summary> public string C_SRP_STATUS { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public DateTime? EXIT_DATE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public short? KCY_NUM_EQVT { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string SCHOOL_YEAR { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string KCY_KCYKEY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string LIVING_ARR { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string C_LIVING_ARR { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (8)] /// </summary> public string PREVIOUS_SCHOOL { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (2)] /// </summary> public string SKGS_PREVIOUS_SCHOOL_ENTITY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string SKGS_PREVIOUS_SCHOOL_ID { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (2)] /// </summary> public string C_FEEDER_ENTITY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string C_FEEDER_SCHOOL_NUMBER { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (40)] /// </summary> public string C_FEEDER_SCHOOL_NAME { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public int? CAMPUS { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (40)] /// </summary> public string SKGS_CAMPUS_NAME { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (33)] /// </summary> public string SKGS_SCHOOL_TYPE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (10)] /// </summary> public string FAMILY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (20)] /// </summary> public string RELATION_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_GENDER_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (30)] /// </summary> public string DF_SURNAME_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string DF_TITLE_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (30)] /// </summary> public string DF_NAME_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (6)] /// </summary> public string DF_BIRTH_COUNTRY_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string DF_KGT_SACC_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (40)] /// </summary> public string DF_KGT_DESCRIPTION_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_KGT_ENGLISH_SPEAKING_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_OCCUP_STATUS_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (7)] /// </summary> public string DF_LOTE_HOME_CODE_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string DF_KGL_LOTE_HOME_ASCL_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (75)] /// </summary> public string DF_KGL_LOTE_HOME_DESCRIPTION_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_GENDER_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (30)] /// </summary> public string DF_SURNAME_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string DF_TITLE_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (30)] /// </summary> public string DF_NAME_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (6)] /// </summary> public string DF_BIRTH_COUNTRY_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_KGT_ENGLISH_SPEAKING_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string DF_KGT_SACC_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (40)] /// </summary> public string DF_KGT_DESCRIPTION_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_OCCUP_STATUS_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (7)] /// </summary> public string DF_LOTE_HOME_CODE_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string DF_KGL_LOTE_HOME_ASCL_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (75)] /// </summary> public string DF_KGL_LOTE_HOME_DESCRIPTION_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string C_FAM_OCCUPATION { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string C_LBOTE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public double? C_YTD_ABSENCE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string C_CENSUSDAY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public double? C_YTD_APPROVED { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public DateTime? C_LAST_ABS_DAY { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public DateTime? C_START_SCHOOL_YEAR { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public short? C_ELIGIBLE_S_DAYS { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string C_LBOTE_MCEETYA { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string FULLTIME { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public double? SGB_TIME_FRACTION { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (8)] /// </summary> public string STPT_SCHL_NUM01 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (8)] /// </summary> public string STPT_SCHL_NUM02 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (8)] /// </summary> public string STPT_SCHL_NUM03 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (8)] /// </summary> public string STPT_SCHL_NUM04 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (2)] /// </summary> public string SKGS_STPT_ENTITY01 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (2)] /// </summary> public string SKGS_STPT_ENTITY02 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (2)] /// </summary> public string SKGS_STPT_ENTITY03 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (2)] /// </summary> public string SKGS_STPT_ENTITY04 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string SKGS_STPT_SCHOOL_ID01 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string SKGS_STPT_SCHOOL_ID02 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string SKGS_STPT_SCHOOL_ID03 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string SKGS_STPT_SCHOOL_ID04 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (40)] /// </summary> public string SKGS_STPT_SCHOOL_NAME01 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (40)] /// </summary> public string SKGS_STPT_SCHOOL_NAME02 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (40)] /// </summary> public string SKGS_STPT_SCHOOL_NAME03 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (40)] /// </summary> public string SKGS_STPT_SCHOOL_NAME04 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public double? STPT_SGB_TIME_FRACTION01 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public double? STPT_SGB_TIME_FRACTION02 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public double? STPT_SGB_TIME_FRACTION03 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public double? STPT_SGB_TIME_FRACTION04 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (4)] /// </summary> public string POSTCODE { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string REPEAT { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (7)] /// </summary> public string INTERNATIONAL_ST_ID { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public DateTime? LCREATED { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (12)] /// </summary> public string VSN { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_SCH_ED_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_SCH_ED_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_NON_SCH_ED_A { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (1)] /// </summary> public string DF_NON_SCH_ED_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (30)] /// </summary> public string ADDRESS_B { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// [Uppercase Alphanumeric (30)] /// </summary> public string ADDRESS_C { get; internal set; } /// <summary> /// Calculated Non School Education /// [Uppercase Alphanumeric (1)] /// </summary> public string CNSE { get; internal set; } /// <summary> /// Calculated School Education /// [Uppercase Alphanumeric (1)] /// </summary> public string CSE { get; internal set; } /// <summary> /// Final Education Value /// [Uppercase Alphanumeric (1)] /// </summary> public string FSE { get; internal set; } #endregion } }
using System; using System.Threading; using System.Reflection; using System.Runtime.Remoting; [Serializable] public class Foo { ~Foo () { Console.WriteLine ("FINALIZING IN DOMAIN " + AppDomain.CurrentDomain.FriendlyName + ": " + AppDomain.CurrentDomain.IsFinalizingForUnload ()); } } public class Bar : MarshalByRefObject { public int test (int x) { Console.WriteLine ("in " + Thread.GetDomain ().FriendlyName); return x + 1; } } [Serializable] public class SlowFinalize { ~SlowFinalize () { Console.WriteLine ("FINALIZE1."); try { Thread.Sleep (500); } catch (Exception ex) { Console.WriteLine ("A: " + ex); } Console.WriteLine ("FINALIZE2."); } } [Serializable] public class AThread { public AThread () { new Thread (new ThreadStart (Run)).Start (); } public void Run () { try { while (true) Thread.Sleep (100); } catch (ThreadAbortException ex) { Console.WriteLine ("Thread aborted correctly."); } } } // A Thread which refuses to die public class BThread : MarshalByRefObject { bool stop; public BThread () { new Thread (new ThreadStart (Run)).Start (); } public void Stop () { stop = true; } public void Run () { try { while (true) Thread.Sleep (100); } catch (ThreadAbortException ex) { while (!stop) Thread.Sleep (100); } } } public class UnloadThread { AppDomain domain; public UnloadThread (AppDomain domain) { this.domain = domain; } public void Run () { Console.WriteLine ("UNLOAD1"); AppDomain.Unload (domain); Console.WriteLine ("UNLOAD2"); } } class CrossDomainTester : MarshalByRefObject { } public class Tests { public static int Main(string[] args) { return TestDriver.RunTests (typeof (Tests), args); } public static int test_0_unload () { for (int i = 0; i < 10; ++i) { AppDomain appDomain = AppDomain.CreateDomain("Test-unload" + i); appDomain.CreateInstanceAndUnwrap ( typeof (CrossDomainTester).Assembly.FullName, "CrossDomainTester"); AppDomain.Unload(appDomain); } return 0; } public static int test_0_unload_default () { try { AppDomain.Unload (Thread.GetDomain ()); } catch (CannotUnloadAppDomainException) { return 0; } return 1; } public static int test_0_unload_after_unload () { AppDomain domain = AppDomain.CreateDomain ("Test2"); AppDomain.Unload (domain); try { AppDomain.Unload (domain); } catch (Exception) { return 0; } return 1; } public static int test_0_is_finalizing () { AppDomain domain = AppDomain.CreateDomain ("Test-is-finalizing"); object o = domain.CreateInstanceFromAndUnwrap (typeof (Tests).Assembly.Location, "Foo"); if (domain.IsFinalizingForUnload ()) return 1; AppDomain.Unload (domain); return 0; } public static int test_0_unload_with_active_threads () { AppDomain domain = AppDomain.CreateDomain ("Test3"); object o = domain.CreateInstanceFromAndUnwrap (typeof (Tests).Assembly.Location, "AThread"); Thread.Sleep (100); AppDomain.Unload (domain); return 0; } /* In recent mono versions, there is no unload timeout */ /* public static int test_0_unload_with_active_threads_timeout () { AppDomain domain = AppDomain.CreateDomain ("Test4"); BThread o = (BThread)domain.CreateInstanceFromAndUnwrap (typeof (Tests).Assembly.Location, "BThread"); Thread.Sleep (100); try { AppDomain.Unload (domain); } catch (Exception) { // Try again o.Stop (); AppDomain.Unload (domain); return 0; } return 1; } */ static void Worker (object x) { Thread.Sleep (100000); } public static void invoke_workers () { for (int i = 0; i < 1; i ++) ThreadPool.QueueUserWorkItem (Worker); } public static int test_0_unload_with_threadpool () { AppDomain domain = AppDomain.CreateDomain ("test_0_unload_with_threadpool"); domain.DoCallBack (new CrossAppDomainDelegate (invoke_workers)); AppDomain.Unload (domain); return 0; } /* * This test is not very deterministic since the thread which enqueues * the work item might or might not be inside the domain when the unload * happens. So disable this for now. */ /* public static void DoUnload (object state) { AppDomain.Unload (AppDomain.CurrentDomain); } public static void Callback () { Console.WriteLine (AppDomain.CurrentDomain); WaitCallback unloadDomainCallback = new WaitCallback (DoUnload); ThreadPool.QueueUserWorkItem (unloadDomainCallback); } public static int test_0_unload_inside_appdomain_async () { AppDomain domain = AppDomain.CreateDomain ("Test3"); domain.DoCallBack (new CrossAppDomainDelegate (Callback)); return 0; } */ public static void SyncCallback () { AppDomain.Unload (AppDomain.CurrentDomain); } public static int test_0_unload_inside_appdomain_sync () { AppDomain domain = AppDomain.CreateDomain ("Test3"); try { domain.DoCallBack (new CrossAppDomainDelegate (SyncCallback)); } catch (Exception ex) { /* Should throw a ThreadAbortException */ Thread.ResetAbort (); } return 0; } public static int test_0_invoke_after_unload () { AppDomain domain = AppDomain.CreateDomain ("DeadInvokeTest"); Bar bar = (Bar)domain.CreateInstanceAndUnwrap (typeof (Tests).Assembly.FullName, "Bar"); int x; if (!RemotingServices.IsTransparentProxy(bar)) return 3; AppDomain.Unload (domain); try { x = bar.test (123); if (x == 124) return 1; return 2; } catch (Exception e) { return 0; } } // FIXME: This does not work yet, because the thread is finalized too // early /* public static int test_0_unload_during_unload () { AppDomain domain = AppDomain.CreateDomain ("Test3"); object o = domain.CreateInstanceFromAndUnwrap (typeof (Tests).Assembly.Location, "SlowFinalize"); UnloadThread t = new UnloadThread (domain); // Start unloading in a separate thread new Thread (new ThreadStart (t.Run)).Start (); Thread.Sleep (100); try { AppDomain.Unload (domain); } catch (Exception) { Console.WriteLine ("OK"); } return 0; } */ }
/* * Velcro Physics: * Copyright (c) 2017 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using Microsoft.Xna.Framework; using QEngine.Physics.Dynamics.Solver; using QEngine.Physics.Shared; using QEngine.Physics.Utilities; namespace QEngine.Physics.Dynamics.Joints { // Pulley: // length1 = norm(p1 - s1) // length2 = norm(p2 - s2) // C0 = (length1 + ratio * length2)_initial // C = C0 - (length1 + ratio * length2) // u1 = (p1 - s1) / norm(p1 - s1) // u2 = (p2 - s2) / norm(p2 - s2) // Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) // J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) /// <summary> /// The pulley joint is connected to two bodies and two fixed world points. /// The pulley supports a ratio such that: /// <![CDATA[length1 + ratio * length2 <= constant]]> /// Yes, the force transmitted is scaled by the ratio. /// Warning: the pulley joint can get a bit squirrelly by itself. They often /// work better when combined with prismatic joints. You should also cover the /// the anchor points with static shapes to prevent one side from going to zero length. /// </summary> public class PulleyJoint : Joint { // Solver shared private float _impulse; // Solver temp private int _indexA; private int _indexB; private float _invIA; private float _invIB; private float _invMassA; private float _invMassB; private Vector2 _localCenterA; private Vector2 _localCenterB; private float _mass; private Vector2 _rA; private Vector2 _rB; private Vector2 _uA; private Vector2 _uB; internal PulleyJoint() { JointType = JointType.Pulley; } /// <summary> /// Constructor for PulleyJoint. /// </summary> /// <param name="bodyA">The first body.</param> /// <param name="bodyB">The second body.</param> /// <param name="anchorA">The anchor on the first body.</param> /// <param name="anchorB">The anchor on the second body.</param> /// <param name="worldAnchorA">The world anchor for the first body.</param> /// <param name="worldAnchorB">The world anchor for the second body.</param> /// <param name="ratio">The ratio.</param> /// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param> public PulleyJoint(Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, Vector2 worldAnchorA, Vector2 worldAnchorB, float ratio, bool useWorldCoordinates = false) : base(bodyA, bodyB) { JointType = JointType.Pulley; WorldAnchorA = worldAnchorA; WorldAnchorB = worldAnchorB; if (useWorldCoordinates) { LocalAnchorA = BodyA.GetLocalPoint(anchorA); LocalAnchorB = BodyB.GetLocalPoint(anchorB); Vector2 dA = anchorA - worldAnchorA; LengthA = dA.Length(); Vector2 dB = anchorB - worldAnchorB; LengthB = dB.Length(); } else { LocalAnchorA = anchorA; LocalAnchorB = anchorB; Vector2 dA = anchorA - BodyA.GetLocalPoint(worldAnchorA); LengthA = dA.Length(); Vector2 dB = anchorB - BodyB.GetLocalPoint(worldAnchorB); LengthB = dB.Length(); } System.Diagnostics.Debug.Assert(ratio != 0.0f); System.Diagnostics.Debug.Assert(ratio > Settings.Epsilon); Ratio = ratio; Constant = LengthA + ratio * LengthB; _impulse = 0.0f; } /// <summary> /// The local anchor point on BodyA /// </summary> public Vector2 LocalAnchorA { get; set; } /// <summary> /// The local anchor point on BodyB /// </summary> public Vector2 LocalAnchorB { get; set; } /// <summary> /// Get the first world anchor. /// </summary> /// <value></value> public sealed override Vector2 WorldAnchorA { get; set; } /// <summary> /// Get the second world anchor. /// </summary> /// <value></value> public sealed override Vector2 WorldAnchorB { get; set; } /// <summary> /// Get the current length of the segment attached to body1. /// </summary> /// <value></value> public float LengthA { get; set; } /// <summary> /// Get the current length of the segment attached to body2. /// </summary> /// <value></value> public float LengthB { get; set; } /// <summary> /// The current length between the anchor point on BodyA and WorldAnchorA /// </summary> public float CurrentLengthA { get { Vector2 p = BodyA.GetWorldPoint(LocalAnchorA); Vector2 s = WorldAnchorA; Vector2 d = p - s; return d.Length(); } } /// <summary> /// The current length between the anchor point on BodyB and WorldAnchorB /// </summary> public float CurrentLengthB { get { Vector2 p = BodyB.GetWorldPoint(LocalAnchorB); Vector2 s = WorldAnchorB; Vector2 d = p - s; return d.Length(); } } /// <summary> /// Get the pulley ratio. /// </summary> /// <value></value> public float Ratio { get; set; } //Velcro note: Only used for serialization. internal float Constant { get; set; } public override Vector2 GetReactionForce(float invDt) { Vector2 P = _impulse * _uB; return invDt * P; } public override float GetReactionTorque(float invDt) { return 0.0f; } internal override void InitVelocityConstraints(ref SolverData data) { _indexA = BodyA.IslandIndex; _indexB = BodyB.IslandIndex; _localCenterA = BodyA._sweep.LocalCenter; _localCenterB = BodyB._sweep.LocalCenter; _invMassA = BodyA._invMass; _invMassB = BodyB._invMass; _invIA = BodyA._invI; _invIB = BodyB._invI; Vector2 cA = data.Positions[_indexA].C; float aA = data.Positions[_indexA].A; Vector2 vA = data.Velocities[_indexA].V; float wA = data.Velocities[_indexA].W; Vector2 cB = data.Positions[_indexB].C; float aB = data.Positions[_indexB].A; Vector2 vB = data.Velocities[_indexB].V; float wB = data.Velocities[_indexB].W; Rot qA = new Rot(aA), qB = new Rot(aB); _rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA); _rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB); // Get the pulley axes. _uA = cA + _rA - WorldAnchorA; _uB = cB + _rB - WorldAnchorB; float lengthA = _uA.Length(); float lengthB = _uB.Length(); if (lengthA > 10.0f * Settings.LinearSlop) { _uA *= 1.0f / lengthA; } else { _uA = Vector2.Zero; } if (lengthB > 10.0f * Settings.LinearSlop) { _uB *= 1.0f / lengthB; } else { _uB = Vector2.Zero; } // Compute effective mass. float ruA = MathUtils.Cross(_rA, _uA); float ruB = MathUtils.Cross(_rB, _uB); float mA = _invMassA + _invIA * ruA * ruA; float mB = _invMassB + _invIB * ruB * ruB; _mass = mA + Ratio * Ratio * mB; if (_mass > 0.0f) { _mass = 1.0f / _mass; } if (Settings.EnableWarmstarting) { // Scale impulses to support variable time steps. _impulse *= data.Step.dtRatio; // Warm starting. Vector2 PA = -(_impulse) * _uA; Vector2 PB = (-Ratio * _impulse) * _uB; vA += _invMassA * PA; wA += _invIA * MathUtils.Cross(_rA, PA); vB += _invMassB * PB; wB += _invIB * MathUtils.Cross(_rB, PB); } else { _impulse = 0.0f; } data.Velocities[_indexA].V = vA; data.Velocities[_indexA].W = wA; data.Velocities[_indexB].V = vB; data.Velocities[_indexB].W = wB; } internal override void SolveVelocityConstraints(ref SolverData data) { Vector2 vA = data.Velocities[_indexA].V; float wA = data.Velocities[_indexA].W; Vector2 vB = data.Velocities[_indexB].V; float wB = data.Velocities[_indexB].W; Vector2 vpA = vA + MathUtils.Cross(wA, _rA); Vector2 vpB = vB + MathUtils.Cross(wB, _rB); float Cdot = -Vector2.Dot(_uA, vpA) - Ratio * Vector2.Dot(_uB, vpB); float impulse = -_mass * Cdot; _impulse += impulse; Vector2 PA = -impulse * _uA; Vector2 PB = -Ratio * impulse * _uB; vA += _invMassA * PA; wA += _invIA * MathUtils.Cross(_rA, PA); vB += _invMassB * PB; wB += _invIB * MathUtils.Cross(_rB, PB); data.Velocities[_indexA].V = vA; data.Velocities[_indexA].W = wA; data.Velocities[_indexB].V = vB; data.Velocities[_indexB].W = wB; } internal override bool SolvePositionConstraints(ref SolverData data) { Vector2 cA = data.Positions[_indexA].C; float aA = data.Positions[_indexA].A; Vector2 cB = data.Positions[_indexB].C; float aB = data.Positions[_indexB].A; Rot qA = new Rot(aA), qB = new Rot(aB); Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA); Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB); // Get the pulley axes. Vector2 uA = cA + rA - WorldAnchorA; Vector2 uB = cB + rB - WorldAnchorB; float lengthA = uA.Length(); float lengthB = uB.Length(); if (lengthA > 10.0f * Settings.LinearSlop) { uA *= 1.0f / lengthA; } else { uA = Vector2.Zero; } if (lengthB > 10.0f * Settings.LinearSlop) { uB *= 1.0f / lengthB; } else { uB = Vector2.Zero; } // Compute effective mass. float ruA = MathUtils.Cross(rA, uA); float ruB = MathUtils.Cross(rB, uB); float mA = _invMassA + _invIA * ruA * ruA; float mB = _invMassB + _invIB * ruB * ruB; float mass = mA + Ratio * Ratio * mB; if (mass > 0.0f) { mass = 1.0f / mass; } float C = Constant - lengthA - Ratio * lengthB; float linearError = Math.Abs(C); float impulse = -mass * C; Vector2 PA = -impulse * uA; Vector2 PB = -Ratio * impulse * uB; cA += _invMassA * PA; aA += _invIA * MathUtils.Cross(rA, PA); cB += _invMassB * PB; aB += _invIB * MathUtils.Cross(rB, PB); data.Positions[_indexA].C = cA; data.Positions[_indexA].A = aA; data.Positions[_indexB].C = cB; data.Positions[_indexB].A = aB; return linearError < Settings.LinearSlop; } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Runtime.CompilerServices; namespace System.Linq.Expressions { /// <summary> /// Represents creating a new array and possibly initializing the elements of the new array. /// </summary> [DebuggerTypeProxy(typeof(NewArrayExpressionProxy))] public class NewArrayExpression : Expression { internal NewArrayExpression(Type type, ReadOnlyCollection<Expression> expressions) { Expressions = expressions; Type = type; } internal static NewArrayExpression Make(ExpressionType nodeType, Type type, ReadOnlyCollection<Expression> expressions) { Debug.Assert(type.IsArray); if (nodeType == ExpressionType.NewArrayInit) { return new NewArrayInitExpression(type, expressions); } else { return new NewArrayBoundsExpression(type, expressions); } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get; } /// <summary> /// Gets the bounds of the array if the value of the <see cref="ExpressionType"/> property is NewArrayBounds, or the values to initialize the elements of the new array if the value of the <see cref="Expression.NodeType"/> property is NewArrayInit. /// </summary> public ReadOnlyCollection<Expression> Expressions { get; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitNewArray(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expressions">The <see cref="Expressions"/> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public NewArrayExpression Update(IEnumerable<Expression> expressions) { // Explicit null check here as otherwise wrong parameter name will be used. ContractUtils.RequiresNotNull(expressions, nameof(expressions)); if (ExpressionUtils.SameElements(ref expressions, Expressions)) { return this; } return NodeType == ExpressionType.NewArrayInit ? NewArrayInit(Type.GetElementType(), expressions) : NewArrayBounds(Type.GetElementType(), expressions); } } internal sealed class NewArrayInitExpression : NewArrayExpression { internal NewArrayInitExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.NewArrayInit; } internal sealed class NewArrayBoundsExpression : NewArrayExpression { internal NewArrayBoundsExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.NewArrayBounds; } public partial class Expression { #region NewArrayInit /// <summary> /// Creates a <see cref="NewArrayExpression"/> of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayInit"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayInit(Type type, params Expression[] initializers) { return NewArrayInit(type, (IEnumerable<Expression>)initializers); } /// <summary> /// Creates a <see cref="NewArrayExpression"/> of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayInit"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayInit(Type type, IEnumerable<Expression> initializers) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(initializers, nameof(initializers)); if (type == typeof(void)) { throw Error.ArgumentCannotBeOfTypeVoid(nameof(type)); } TypeUtils.ValidateType(type, nameof(type)); ReadOnlyCollection<Expression> initializerList = initializers.ToReadOnly(); Expression[] newList = null; for (int i = 0, n = initializerList.Count; i < n; i++) { Expression expr = initializerList[i]; ExpressionUtils.RequiresCanRead(expr, nameof(initializers), i); if (!TypeUtils.AreReferenceAssignable(type, expr.Type)) { if (!TryQuote(type, ref expr)) { throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type); } if (newList == null) { newList = new Expression[initializerList.Count]; for (int j = 0; j < i; j++) { newList[j] = initializerList[j]; } } } if (newList != null) { newList[i] = expr; } } if (newList != null) { initializerList = new TrueReadOnlyCollection<Expression>(newList); } return NewArrayExpression.Make(ExpressionType.NewArrayInit, type.MakeArrayType(), initializerList); } #endregion #region NewArrayBounds /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="System.Type"/> that represents the element type of the array.</param> /// <param name="bounds">An array that contains Expression objects to use to populate the <see cref="NewArrayExpression.Expressions"/> collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayBounds"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, params Expression[] bounds) { return NewArrayBounds(type, (IEnumerable<Expression>)bounds); } /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="System.Type"/> that represents the element type of the array.</param> /// <param name="bounds">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the <see cref="NewArrayExpression.Expressions"/> collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayBounds"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, IEnumerable<Expression> bounds) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(bounds, nameof(bounds)); if (type == typeof(void)) { throw Error.ArgumentCannotBeOfTypeVoid(nameof(type)); } TypeUtils.ValidateType(type, nameof(type)); ReadOnlyCollection<Expression> boundsList = bounds.ToReadOnly(); int dimensions = boundsList.Count; if (dimensions <= 0) throw Error.BoundsCannotBeLessThanOne(nameof(bounds)); for (int i = 0; i < dimensions; i++) { Expression expr = boundsList[i]; ExpressionUtils.RequiresCanRead(expr, nameof(bounds), i); if (!expr.Type.IsInteger()) { throw Error.ArgumentMustBeInteger(nameof(bounds), i); } } Type arrayType; if (dimensions == 1) { //To get a vector, need call Type.MakeArrayType(). //Type.MakeArrayType(1) gives a non-vector array, which will cause type check error. arrayType = type.MakeArrayType(); } else { arrayType = type.MakeArrayType(dimensions); } return NewArrayExpression.Make(ExpressionType.NewArrayBounds, arrayType, boundsList); } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Cluster { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; /// <summary> /// Defines grid projection which represents a common functionality over a group of nodes. /// Grid projection allows to group Ignite nodes into various subgroups to perform distributed /// operations on them. All ForXXX(...)' methods will create a child grid projection /// from existing projection. If you create a new projection from current one, then the resulting /// projection will include a subset of nodes from current projection. The following code snippet /// shows how to create grid projections: /// <code> /// var g = Ignition.GetIgnite(); /// /// // Projection over remote nodes. /// var remoteNodes = g.ForRemotes(); /// /// // Projection over random remote node. /// var randomNode = g.ForRandom(); /// /// // Projection over all nodes with cache named "myCache" enabled. /// var cacheNodes = g.ForCacheNodes("myCache"); /// /// // Projection over all nodes that have user attribute "group" set to value "worker". /// var workerNodes = g.ForAttribute("group", "worker"); /// </code> /// Grid projection provides functionality for executing tasks and closures over /// nodes in this projection using <see cref="GetCompute"/>. /// <para/> /// All members are thread-safe and may be used concurrently from multiple threads. /// </summary> public interface IClusterGroup { /// <summary> /// Instance of Ignite. /// </summary> IIgnite Ignite { get; } /// <summary> /// Gets compute functionality over this grid projection. All operations /// on the returned ICompute instance will only include nodes from /// this projection. /// </summary> /// <returns>Compute instance over this grid projection.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")] ICompute GetCompute(); /// <summary> /// Creates a grid projection over a given set of nodes. /// </summary> /// <param name="nodes">Collection of nodes to create a projection from.</param> /// <returns>Projection over provided Ignite nodes.</returns> IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes); /// <summary> /// Creates a grid projection over a given set of nodes. /// </summary> /// <param name="nodes">Collection of nodes to create a projection from.</param> /// <returns>Projection over provided Ignite nodes.</returns> IClusterGroup ForNodes(params IClusterNode[] nodes); /// <summary> /// Creates a grid projection over a given set of node IDs. /// </summary> /// <param name="ids">Collection of node IDs to create a projection from.</param> /// <returns>Projection over provided Ignite node IDs.</returns> IClusterGroup ForNodeIds(IEnumerable<Guid> ids); /// <summary> /// Creates a grid projection over a given set of node IDs. /// </summary> /// <param name="ids">Collection of node IDs to create a projection from.</param> /// <returns>Projection over provided Ignite node IDs.</returns> IClusterGroup ForNodeIds(params Guid[] ids); /// <summary> /// Creates a grid projection which includes all nodes that pass the given predicate filter. /// </summary> /// <param name="p">Predicate filter for nodes to include into this projection.</param> /// <returns>Grid projection for nodes that passed the predicate filter.</returns> IClusterGroup ForPredicate(Func<IClusterNode, bool> p); /// <summary> /// Creates projection for nodes containing given name and value /// specified in user attributes. /// </summary> /// <param name="name">Name of the attribute.</param> /// <param name="val">Optional attribute value to match.</param> /// <returns>Grid projection for nodes containing specified attribute.</returns> IClusterGroup ForAttribute(string name, string val); /// <summary> /// Creates projection for all nodes that have cache with specified name running. /// </summary> /// <param name="name">Cache name to include into projection.</param> /// <returns>Projection over nodes that have specified cache running.</returns> IClusterGroup ForCacheNodes(string name); /// <summary> /// Creates projection for all nodes that have cache with specified name running /// and cache distribution mode is PARTITIONED_ONLY or NEAR_PARTITIONED. /// </summary> /// <param name="name">Cache name to include into projection.</param> /// <returns>Projection over nodes that have specified cache running.</returns> IClusterGroup ForDataNodes(string name); /// <summary> /// Creates projection for all nodes that have cache with specified name running /// and cache distribution mode is CLIENT_ONLY or NEAR_ONLY. /// </summary> /// <param name="name">Cache name to include into projection.</param> /// <returns>Projection over nodes that have specified cache running.</returns> IClusterGroup ForClientNodes(string name); /// <summary> /// Gets grid projection consisting from the nodes in this projection excluding the local node. /// </summary> /// <returns>Grid projection consisting from the nodes in this projection excluding the local node.</returns> IClusterGroup ForRemotes(); /// <summary> /// Gets a cluster group consisting of the daemon nodes. /// <para /> /// Daemon nodes are the usual grid nodes that participate in topology but not visible on the main APIs, /// i.e. they are not part of any cluster group. The only way to see daemon nodes is to use this method. /// <para /> /// Daemon nodes are used primarily for management and monitoring functionality that /// is build on Ignite and needs to participate in the topology, but also needs to be /// excluded from the "normal" topology, so that it won't participate in the task execution /// or in-memory data grid storage. /// </summary> /// <returns>Cluster group consisting of the daemon nodes.</returns> IClusterGroup ForDaemons(); /// <summary> /// Gets grid projection consisting from the nodes in this projection residing on the /// same host as given node. /// </summary> /// <param name="node">Node residing on the host for which projection is created.</param> /// <returns>Projection for nodes residing on the same host as passed in node.</returns> IClusterGroup ForHost(IClusterNode node); /// <summary> /// Creates grid projection with one random node from current projection. /// </summary> /// <returns>Grid projection with one random node from current projection.</returns> IClusterGroup ForRandom(); /// <summary> /// Creates grid projection with one oldest node in the current projection. /// The resulting projection is dynamic and will always pick the next oldest /// node if the previous one leaves topology even after the projection has /// been created. /// </summary> /// <returns>Grid projection with one oldest node from the current projection.</returns> IClusterGroup ForOldest(); /// <summary> /// Creates grid projection with one youngest node in the current projection. /// The resulting projection is dynamic and will always pick the newest /// node in the topology, even if more nodes entered after the projection /// has been created. /// </summary> /// <returns>Grid projection with one youngest node from the current projection.</returns> IClusterGroup ForYoungest(); /// <summary> /// Creates grid projection for nodes supporting .Net, i.e. for nodes started with Apache.Ignite.exe. /// </summary> /// <returns>Grid projection for nodes supporting .Net.</returns> IClusterGroup ForDotNet(); /// <summary> /// Creates a cluster group of nodes started in server mode (<see cref="IgniteConfiguration.ClientMode"/>). /// </summary> /// <returns>Cluster group of nodes started in server mode.</returns> IClusterGroup ForServers(); /// <summary> /// Gets read-only collections of nodes in this projection. /// </summary> /// <returns>All nodes in this projection.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")] ICollection<IClusterNode> GetNodes(); /// <summary> /// Gets a node for given ID from this grid projection. /// </summary> /// <param name="id">Node ID.</param> /// <returns>Node with given ID from this projection or null if such node does not /// exist in this projection.</returns> IClusterNode GetNode(Guid id); /// <summary> /// Gets first node from the list of nodes in this projection. /// </summary> /// <returns>Node.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")] IClusterNode GetNode(); /// <summary> /// Gets a metrics snapshot for this projection /// </summary> /// <returns>Grid projection metrics snapshot.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")] IClusterMetrics GetMetrics(); /// <summary> /// Gets messaging facade over nodes within this cluster group. All operations on the returned /// <see cref="IMessaging"/>> instance will only include nodes from current cluster group. /// </summary> /// <returns>Messaging instance over this cluster group.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")] IMessaging GetMessaging(); /// <summary> /// Gets events facade over nodes within this cluster group. All operations on the returned /// <see cref="IEvents"/>> instance will only include nodes from current cluster group. /// </summary> /// <returns>Events instance over this cluster group.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")] IEvents GetEvents(); /// <summary> /// Gets services facade over nodes within this cluster group. All operations on the returned /// <see cref="IServices"/>> instance will only include nodes from current cluster group. /// </summary> /// <returns>Services instance over this cluster group.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")] IServices GetServices(); } }
// 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.Data; using System.Data.Common; using System.Diagnostics; // Debug services using System.Runtime.InteropServices; using System.Text; namespace System.Data.Odbc { internal sealed class CNativeBuffer : System.Data.ProviderBase.DbBuffer { internal CNativeBuffer(int initialSize) : base(initialSize) { } internal short ShortLength { get { return checked((short)Length); } } internal object MarshalToManaged(int offset, ODBC32.SQL_C sqlctype, int cb) { object value; switch (sqlctype) { case ODBC32.SQL_C.WCHAR: //Note: We always bind as unicode if (cb == ODBC32.SQL_NTS) { value = PtrToStringUni(offset); break; } Debug.Assert((cb > 0), "Character count negative "); Debug.Assert((Length >= cb), "Native buffer too small "); cb = Math.Min(cb / 2, (Length - 2) / 2); value = PtrToStringUni(offset, cb); break; case ODBC32.SQL_C.CHAR: case ODBC32.SQL_C.BINARY: Debug.Assert((cb > 0), "Character count negative "); Debug.Assert((Length >= cb), "Native buffer too small "); cb = Math.Min(cb, Length); value = ReadBytes(offset, cb); break; case ODBC32.SQL_C.SSHORT: value = ReadInt16(offset); break; case ODBC32.SQL_C.SLONG: value = ReadInt32(offset); break; case ODBC32.SQL_C.SBIGINT: value = ReadInt64(offset); break; case ODBC32.SQL_C.BIT: Byte b = ReadByte(offset); value = (b != 0x00); break; case ODBC32.SQL_C.REAL: value = ReadSingle(offset); break; case ODBC32.SQL_C.DOUBLE: value = ReadDouble(offset); break; case ODBC32.SQL_C.UTINYINT: value = ReadByte(offset); break; case ODBC32.SQL_C.GUID: value = ReadGuid(offset); break; case ODBC32.SQL_C.TYPE_TIMESTAMP: //So we are mapping this ourselves. //typedef struct tagTIMESTAMP_STRUCT //{ // SQLSMALLINT year; // SQLUSMALLINT month; // SQLUSMALLINT day; // SQLUSMALLINT hour; // SQLUSMALLINT minute; // SQLUSMALLINT second; // SQLUINTEGER fraction; (billoniths of a second) //} value = ReadDateTime(offset); break; // Note: System does not provide a date-only type case ODBC32.SQL_C.TYPE_DATE: // typedef struct tagDATE_STRUCT // { // SQLSMALLINT year; // SQLUSMALLINT month; // SQLUSMALLINT day; // } DATE_STRUCT; value = ReadDate(offset); break; // Note: System does not provide a date-only type case ODBC32.SQL_C.TYPE_TIME: // typedef struct tagTIME_STRUCT // { // SQLUSMALLINT hour; // SQLUSMALLINT minute; // SQLUSMALLINT second; // } TIME_STRUCT; value = ReadTime(offset); break; case ODBC32.SQL_C.NUMERIC: //Note: Unfortunatly the ODBC NUMERIC structure and the URT DECIMAL structure do not //align, so we can't so do the typical "PtrToStructure" call (below) like other types //We actually have to go through the pain of pulling our raw bytes and building the decimal // Marshal.PtrToStructure(buffer, typeof(decimal)); //So we are mapping this ourselves //typedef struct tagSQL_NUMERIC_STRUCT //{ // SQLCHAR precision; // SQLSCHAR scale; // SQLCHAR sign; /* 1 if positive, 0 if negative */ // SQLCHAR val[SQL_MAX_NUMERIC_LEN]; //} SQL_NUMERIC_STRUCT; value = ReadNumeric(offset); break; default: Debug.Assert(false, "UnknownSQLCType"); value = null; break; }; return value; } // if sizeorprecision applies only for wchar and numeric values // for wchar the a value of null means take the value's size // internal void MarshalToNative(int offset, object value, ODBC32.SQL_C sqlctype, int sizeorprecision, int valueOffset) { switch (sqlctype) { case ODBC32.SQL_C.WCHAR: { //Note: We always bind as unicode //Note: StructureToPtr fails indicating string it a non-blittable type //and there is no MarshalStringTo* that moves to an existing buffer, //they all alloc and return a new one, not at all what we want... //So we have to copy the raw bytes of the string ourself?! Char[] rgChars; int length; Debug.Assert(value is string || value is char[], "Only string or char[] can be marshaled to WCHAR"); if (value is string) { length = Math.Max(0, ((string)value).Length - valueOffset); if ((sizeorprecision > 0) && (sizeorprecision < length)) { length = sizeorprecision; } rgChars = ((string)value).ToCharArray(valueOffset, length); Debug.Assert(rgChars.Length < (base.Length - valueOffset), "attempting to extend parameter buffer!"); WriteCharArray(offset, rgChars, 0, rgChars.Length); WriteInt16(offset + (rgChars.Length * 2), 0); // Add the null terminator } else { length = Math.Max(0, ((char[])value).Length - valueOffset); if ((sizeorprecision > 0) && (sizeorprecision < length)) { length = sizeorprecision; } rgChars = (char[])value; Debug.Assert(rgChars.Length < (base.Length - valueOffset), "attempting to extend parameter buffer!"); WriteCharArray(offset, rgChars, valueOffset, length); WriteInt16(offset + (rgChars.Length * 2), 0); // Add the null terminator } break; } case ODBC32.SQL_C.BINARY: case ODBC32.SQL_C.CHAR: { Byte[] rgBytes = (Byte[])value; int length = rgBytes.Length; Debug.Assert((valueOffset <= length), "Offset out of Range"); // reduce length by the valueOffset // length -= valueOffset; // reduce length to be no more than size (if size is given) // if ((sizeorprecision > 0) && (sizeorprecision < length)) { length = sizeorprecision; } //AdjustSize(rgBytes.Length+1); //buffer = DangerousAllocateAndGetHandle(); // Realloc may have changed buffer address Debug.Assert(length < (base.Length - valueOffset), "attempting to extend parameter buffer!"); WriteBytes(offset, rgBytes, valueOffset, length); break; } case ODBC32.SQL_C.UTINYINT: WriteByte(offset, (Byte)value); break; case ODBC32.SQL_C.SSHORT: //Int16 WriteInt16(offset, (Int16)value); break; case ODBC32.SQL_C.SLONG: //Int32 WriteInt32(offset, (Int32)value); break; case ODBC32.SQL_C.REAL: //float WriteSingle(offset, (Single)value); break; case ODBC32.SQL_C.SBIGINT: //Int64 WriteInt64(offset, (Int64)value); break; case ODBC32.SQL_C.DOUBLE: //Double WriteDouble(offset, (Double)value); break; case ODBC32.SQL_C.GUID: //Guid WriteGuid(offset, (Guid)value); break; case ODBC32.SQL_C.BIT: WriteByte(offset, (Byte)(((bool)value) ? 1 : 0)); break; case ODBC32.SQL_C.TYPE_TIMESTAMP: { //typedef struct tagTIMESTAMP_STRUCT //{ // SQLSMALLINT year; // SQLUSMALLINT month; // SQLUSMALLINT day; // SQLUSMALLINT hour; // SQLUSMALLINT minute; // SQLUSMALLINT second; // SQLUINTEGER fraction; (billoniths of a second) //} //We have to map this ourselves, due to the different structures between //ODBC TIMESTAMP and URT DateTime, (ie: can't use StructureToPtr) WriteODBCDateTime(offset, (DateTime)value); break; } // Note: System does not provide a date-only type case ODBC32.SQL_C.TYPE_DATE: { // typedef struct tagDATE_STRUCT // { // SQLSMALLINT year; // SQLUSMALLINT month; // SQLUSMALLINT day; // } DATE_STRUCT; WriteDate(offset, (DateTime)value); break; } // Note: System does not provide a date-only type case ODBC32.SQL_C.TYPE_TIME: { // typedef struct tagTIME_STRUCT // { // SQLUSMALLINT hour; // SQLUSMALLINT minute; // SQLUSMALLINT second; // } TIME_STRUCT; WriteTime(offset, (TimeSpan)value); break; } case ODBC32.SQL_C.NUMERIC: { WriteNumeric(offset, (Decimal)value, checked((byte)sizeorprecision)); break; } default: Debug.Assert(false, "UnknownSQLCType"); break; } } internal HandleRef PtrOffset(int offset, int length) { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE: You must have called DangerousAddRef before calling this // method, or you run the risk of allowing Handle Recycling // to occur! //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Validate(offset, length); IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset); return new HandleRef(this, ptr); } internal void WriteODBCDateTime(int offset, DateTime value) { short[] buffer = new short[6] { unchecked((short)value.Year), unchecked((short)value.Month), unchecked((short)value.Day), unchecked((short)value.Hour), unchecked((short)value.Minute), unchecked((short)value.Second), }; WriteInt16Array(offset, buffer, 0, 6); WriteInt32(offset + 12, value.Millisecond * 1000000); //fraction } } internal sealed class CStringTokenizer { private readonly StringBuilder _token; private readonly string _sqlstatement; private readonly char _quote; // typically the semicolon '"' private readonly char _escape; // typically the same char as the quote private int _len = 0; private int _idx = 0; internal CStringTokenizer(string text, char quote, char escape) { _token = new StringBuilder(); _quote = quote; _escape = escape; _sqlstatement = text; if (text != null) { int iNul = text.IndexOf('\0'); _len = (0 > iNul) ? text.Length : iNul; } else { _len = 0; } } internal int CurrentPosition { get { return _idx; } } // Returns the next token in the statement, advancing the current index to // the start of the token internal String NextToken() { if (_token.Length != 0) { // if we've read a token before _idx += _token.Length; // proceed the internal marker (_idx) behind the token _token.Remove(0, _token.Length); // and start over with a fresh token } while ((_idx < _len) && Char.IsWhiteSpace(_sqlstatement[_idx])) { // skip whitespace _idx++; } if (_idx == _len) { // return if string is empty return String.Empty; } int curidx = _idx; // start with internal index at current index bool endtoken = false; // // process characters until we reache the end of the token or the end of the string // while (!endtoken && curidx < _len) { if (IsValidNameChar(_sqlstatement[curidx])) { while ((curidx < _len) && IsValidNameChar(_sqlstatement[curidx])) { _token.Append(_sqlstatement[curidx]); curidx++; } } else { char currentchar = _sqlstatement[curidx]; if (currentchar == '[') { curidx = GetTokenFromBracket(curidx); } else if (' ' != _quote && currentchar == _quote) { // if the ODBC driver does not support quoted identifiers it returns a single blank character curidx = GetTokenFromQuote(curidx); } else { // Some other marker like , ; ( or ) // could also be * or ? if (!Char.IsWhiteSpace(currentchar)) { switch (currentchar) { case ',': // commas are not part of a token so we'll only append them if they are at the beginning if (curidx == _idx) _token.Append(currentchar); break; default: _token.Append(currentchar); break; } } endtoken = true; break; } } } return (_token.Length > 0) ? _token.ToString() : String.Empty; } private int GetTokenFromBracket(int curidx) { Debug.Assert((_sqlstatement[curidx] == '['), "GetTokenFromQuote: character at starting position must be same as quotechar"); while (curidx < _len) { _token.Append(_sqlstatement[curidx]); curidx++; if (_sqlstatement[curidx - 1] == ']') break; } return curidx; } // attempts to complete an encapsulated token (e.g. "scott") // double quotes are valid part of the token (e.g. "foo""bar") // private int GetTokenFromQuote(int curidx) { Debug.Assert(_quote != ' ', "ODBC driver doesn't support quoted identifiers -- GetTokenFromQuote should not be used in this case"); Debug.Assert((_sqlstatement[curidx] == _quote), "GetTokenFromQuote: character at starting position must be same as quotechar"); int localidx = curidx; // start with local index at current index while (localidx < _len) { // run to the end of the statement _token.Append(_sqlstatement[localidx]); // append current character to token if (_sqlstatement[localidx] == _quote) { if (localidx > curidx) { // don't care for the first char if (_sqlstatement[localidx - 1] != _escape) { // if it's not escape we look at the following char if (localidx + 1 < _len) { // do not overrun the end of the string if (_sqlstatement[localidx + 1] != _quote) { return localidx + 1; // We've reached the end of the quoted text } } } } } localidx++; } return localidx; } private bool IsValidNameChar(char ch) { return (Char.IsLetterOrDigit(ch) || (ch == '_') || (ch == '-') || (ch == '.') || (ch == '$') || (ch == '#') || (ch == '@') || (ch == '~') || (ch == '`') || (ch == '%') || (ch == '^') || (ch == '&') || (ch == '|')); } // Searches for the token given, starting from the current position // If found, positions the currentindex at the // beginning of the token if found. internal int FindTokenIndex(String tokenString) { String nextToken; while (true) { nextToken = NextToken(); if ((_idx == _len) || ADP.IsEmpty(nextToken)) { // fxcop break; } if (String.Compare(tokenString, nextToken, StringComparison.OrdinalIgnoreCase) == 0) { return _idx; } } return -1; } // Skips the whitespace found in the beginning of the string. internal bool StartsWith(String tokenString) { int tempidx = 0; while ((tempidx < _len) && Char.IsWhiteSpace(_sqlstatement[tempidx])) { tempidx++; } if ((_len - tempidx) < tokenString.Length) { return false; } if (0 == String.Compare(_sqlstatement, tempidx, tokenString, 0, tokenString.Length, StringComparison.OrdinalIgnoreCase)) { // Reset current position and token _idx = 0; NextToken(); return true; } return false; } } }
//------------------------------------------------------------------------------ // <copyright file="DataGridParentRows.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System.Text; using System.Runtime.Remoting; using System; using System.Collections; using System.Windows.Forms; using System.Security.Permissions; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using Microsoft.Win32; using System.Runtime.InteropServices; using System.Diagnostics; using System.Runtime.Versioning; internal class DataGridParentRows { // siting // private DataGrid dataGrid; // ui // // private Color backColor = DataGrid.defaultParentRowsBackColor; // private Color foreColor = DataGrid.defaultParentRowsForeColor; private SolidBrush backBrush = DataGrid.DefaultParentRowsBackBrush; private SolidBrush foreBrush = DataGrid.DefaultParentRowsForeBrush; private int borderWidth = 1; // private Color borderColor = SystemColors.WindowFrame; private Brush borderBrush = new SolidBrush(SystemColors.WindowFrame); private static Bitmap rightArrow = null; private static Bitmap leftArrow = null; private ColorMap[] colorMap = new ColorMap[] {new ColorMap()}; // private bool gridLineDots = false; // private Color gridLineColor = SystemColors.Control; // private Brush gridLineBrush = SystemBrushes.Control; private Pen gridLinePen = SystemPens.Control; private int totalHeight = 0; private int textRegionHeight = 0; // now that we have left and right arrows, we also have layout private Layout layout = new Layout(); // mouse info // // private bool overLeftArrow = false; // private bool overRightArrow = false; private bool downLeftArrow = false; private bool downRightArrow = false; // a horizOffset of 0 means that the layout for the parent // rows is left aligned. // a horizOffset of 1 means that the leftmost unit of information ( let it be a // table name, a column name or a column value ) is not visible. // a horizOffset of 2 means that the leftmost 2 units of information are not visible, and so on // private int horizOffset = 0; // storage for parent row states // private ArrayList parents = new ArrayList(); private int parentsCount = 0; private ArrayList rowHeights = new ArrayList(); AccessibleObject accessibleObject; internal DataGridParentRows(DataGrid dataGrid) { this.colorMap[0].OldColor = Color.Black; this.dataGrid = dataGrid; // UpdateGridLinePen(); } // =------------------------------------------------------------------ // = Properties // =------------------------------------------------------------------ public AccessibleObject AccessibleObject { get { if (accessibleObject == null) { accessibleObject = new DataGridParentRowsAccessibleObject(this); } return accessibleObject; } } internal Color BackColor { get { return backBrush.Color; } set { if (value.IsEmpty) throw new ArgumentException(SR.GetString(SR.DataGridEmptyColor, "Parent Rows BackColor")); if (value != backBrush.Color) { backBrush = new SolidBrush(value); Invalidate(); } } } internal SolidBrush BackBrush { get { return backBrush; } set { if (value != backBrush) { CheckNull(value, "BackBrush"); backBrush = value; Invalidate(); } } } internal SolidBrush ForeBrush { get { return foreBrush; } set { if (value != foreBrush) { CheckNull(value, "BackBrush"); foreBrush = value; Invalidate(); } } } // since the layout of the parentRows is computed on every paint message, // we can actually return true ClientRectangle coordinates internal Rectangle GetBoundsForDataGridStateAccesibility(DataGridState dgs) { Rectangle ret = Rectangle.Empty; int rectY = 0; for (int i = 0; i < parentsCount; i++) { int height = (int) rowHeights[i]; if (parents[i] == dgs) { ret.X = layout.leftArrow.IsEmpty ? layout.data.X : layout.leftArrow.Right; ret.Height = height; ret.Y = rectY; ret.Width = layout.data.Width; return ret; } rectY += height; } return ret; } /* internal Color BorderColor { get { return borderColor; } set { if (value != borderColor) { borderColor = value; Invalidate(); } } } */ internal Brush BorderBrush { get { return borderBrush; } set { if (value != borderBrush) { borderBrush = value; Invalidate(); } } } /* internal Brush GridLineBrush { get { return gridLineBrush; } set { if (value != gridLineBrush) { gridLineBrush = value; UpdateGridLinePen(); Invalidate(); } } } internal bool GridLineDots { get { return gridLineDots; } set { if (gridLineDots != value) { gridLineDots = value; UpdateGridLinePen(); Invalidate(); } } } */ internal int Height { get { return totalHeight; } } internal Color ForeColor { get { return foreBrush.Color; } set { if (value.IsEmpty) throw new ArgumentException(SR.GetString(SR.DataGridEmptyColor, "Parent Rows ForeColor")); if (value != foreBrush.Color) { foreBrush = new SolidBrush(value); Invalidate(); } } } internal bool Visible { get { return dataGrid.ParentRowsVisible; } set { dataGrid.ParentRowsVisible = value; } } // =------------------------------------------------------------------ // = Methods // =------------------------------------------------------------------ /// <include file='doc\DataGridParentRows.uex' path='docs/doc[@for="DataGridParentRows.AddParent"]/*' /> /// <devdoc> /// Adds a DataGridState object to the top of the list of parents. /// </devdoc> internal void AddParent(DataGridState dgs) { CurrencyManager childDataSource = (CurrencyManager) dataGrid.BindingContext[dgs.DataSource, dgs.DataMember]; parents.Add(dgs); SetParentCount(parentsCount + 1); Debug.Assert(GetTopParent() != null, "we should have a parent at least"); } internal void Clear() { for (int i = 0; i < parents.Count; i++) { DataGridState dgs = parents[i] as DataGridState; dgs.RemoveChangeNotification(); } parents.Clear(); rowHeights.Clear(); totalHeight = 0; SetParentCount(0); } internal void SetParentCount(int count) { parentsCount = count; dataGrid.Caption.BackButtonVisible = (parentsCount > 0) && (dataGrid.AllowNavigation); } internal void CheckNull(object value, string propName) { if (value == null) throw new ArgumentNullException("propName"); } internal void Dispose() { gridLinePen.Dispose(); } /// <include file='doc\DataGridParentRows.uex' path='docs/doc[@for="DataGridParentRows.GetTopParent"]/*' /> /// <devdoc> /// Retrieves the top most parent in the list of parents. /// </devdoc> internal DataGridState GetTopParent() { if (parentsCount < 1) { return null; } return(DataGridState)(((ICloneable)(parents[parentsCount-1])).Clone()); } /// <include file='doc\DataGridParentRows.uex' path='docs/doc[@for="DataGridParentRows.IsEmpty"]/*' /> /// <devdoc> /// Determines if there are any parent rows contained in this object. /// </devdoc> internal bool IsEmpty() { return parentsCount == 0; } /// <include file='doc\DataGridParentRows.uex' path='docs/doc[@for="DataGridParentRows.PopTop"]/*' /> /// <devdoc> /// Similar to GetTopParent() but also removes it. /// </devdoc> internal DataGridState PopTop() { if (parentsCount < 1) { return null; } SetParentCount(parentsCount - 1); DataGridState ret = (DataGridState)parents[parentsCount]; ret.RemoveChangeNotification(); parents.RemoveAt(parentsCount); return ret; } internal void Invalidate() { if (dataGrid != null) dataGrid.InvalidateParentRows(); } internal void InvalidateRect(Rectangle rect) { if (dataGrid != null) { Rectangle r = new Rectangle(rect.X, rect.Y, rect.Width + borderWidth, rect.Height + borderWidth); dataGrid.InvalidateParentRowsRect(r); } } // called from DataGrid::OnLayout internal void OnLayout() { if (parentsCount == rowHeights.Count) return; int height = 0; if (totalHeight == 0) { totalHeight += 2 * borderWidth; } // figure out how tall each row's text will be // textRegionHeight = (int)dataGrid.Font.Height + 2; // make the height of the Column.Font count for the height // of the parentRows; // // if the user wants to programatically // navigate to a relation in the constructor of the form // ( ie, when the form does not process PerformLayout ) // the grid will receive an OnLayout message when there is more // than one parent in the grid if (parentsCount > rowHeights.Count) { Debug.Assert(parentsCount == rowHeights.Count + 1 || rowHeights.Count == 0, "see bug 82808 for more info, or the comment above"); int rowHeightsCount = this.rowHeights.Count; for (int i = rowHeightsCount; i < parentsCount; i++) { DataGridState dgs = (DataGridState) parents[i]; GridColumnStylesCollection cols = dgs.GridColumnStyles; int colsHeight = 0; for (int j=0; j<cols.Count; j++) { colsHeight = Math.Max(colsHeight, cols[j].GetMinimumHeight()); } height = Math.Max(colsHeight, textRegionHeight); // the height of the bottom border height ++; rowHeights.Add(height); totalHeight += height; } } else { Debug.Assert(parentsCount == rowHeights.Count - 1, "we do layout only for push/popTop"); if (parentsCount == 0) totalHeight = 0; else totalHeight -= (int) rowHeights[rowHeights.Count-1]; rowHeights.RemoveAt(rowHeights.Count - 1); } } private int CellCount() { int cellCount = 0; cellCount = ColsCount(); if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.TableName || dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) { cellCount ++; } return cellCount; } private void ResetMouseInfo() { // overLeftArrow = false; // overRightArrow = false; downLeftArrow = false; downRightArrow = false; } private void LeftArrowClick(int cellCount) { if (horizOffset > 0) { ResetMouseInfo(); horizOffset -= 1; Invalidate(); } else { ResetMouseInfo(); InvalidateRect(layout.leftArrow); } } private void RightArrowClick(int cellCount) { if (horizOffset < cellCount - 1) { ResetMouseInfo(); horizOffset += 1; Invalidate(); } else { ResetMouseInfo(); InvalidateRect(layout.rightArrow); } } // the only mouse clicks that are handled are // the mouse clicks on the LeftArrow and RightArrow // internal void OnMouseDown(int x, int y, bool alignToRight) { if (layout.rightArrow.IsEmpty) { Debug.Assert(layout.leftArrow.IsEmpty, "we can't have the leftArrow w/o the rightArrow"); return; } int cellCount = CellCount(); if (layout.rightArrow.Contains(x,y)) { // draw a nice sunken border around the right arrow area // we want to keep a cell on the screen downRightArrow = true; if (alignToRight) LeftArrowClick(cellCount); else RightArrowClick(cellCount); } else if (layout.leftArrow.Contains(x,y)) { downLeftArrow = true; if (alignToRight) RightArrowClick(cellCount); else LeftArrowClick(cellCount); } else { if (downLeftArrow) { downLeftArrow = false; InvalidateRect(layout.leftArrow); } if (downRightArrow) { downRightArrow = false; InvalidateRect(layout.rightArrow); } } } internal void OnMouseLeave() { if (downLeftArrow) { downLeftArrow = false; InvalidateRect(layout.leftArrow); } if (downRightArrow) { downRightArrow = false; InvalidateRect(layout.rightArrow); } } internal void OnMouseMove(int x, int y) { /* if (!layout.leftArrow.IsEmpty && layout.leftArrow.Contains(x,y)) { ResetMouseInfo(); overLeftArrow = true; InvalidateRect(layout.leftArrow); return; } if (!layout.rightArrow.IsEmpty && layout.rightArrow.Contains(x,y)) { ResetMouseInfo(); overRightArrow = true; InvalidateRect(layout.rightArrow); return; } */ if (downLeftArrow) { downLeftArrow = false; InvalidateRect(layout.leftArrow); } if (downRightArrow) { downRightArrow = false; InvalidateRect(layout.rightArrow); } } internal void OnMouseUp(int x, int y) { ResetMouseInfo(); if (!layout.rightArrow.IsEmpty && layout.rightArrow.Contains(x,y)) { InvalidateRect(layout.rightArrow); return; } if (!layout.leftArrow.IsEmpty && layout.leftArrow.Contains(x,y)) { InvalidateRect(layout.leftArrow); return; } } internal void OnResize(Rectangle oldBounds) { Invalidate(); } /// <include file='doc\DataGridParentRows.uex' path='docs/doc[@for="DataGridParentRows.Paint"]/*' /> /// <devdoc> /// Paints the parent rows /// </devdoc> internal void Paint(Graphics g, Rectangle visualbounds, bool alignRight) { Rectangle bounds = visualbounds; // Paint the border around our bounds if (borderWidth > 0) { PaintBorder(g, bounds); bounds.Inflate(-borderWidth, -borderWidth); } PaintParentRows(g, bounds, alignRight); } private void PaintBorder(Graphics g, Rectangle bounds) { Rectangle border = bounds; // top border.Height = borderWidth; g.FillRectangle(borderBrush, border); // bottom border.Y = bounds.Bottom - borderWidth; g.FillRectangle(borderBrush, border); // left border = new Rectangle(bounds.X, bounds.Y + borderWidth, borderWidth, bounds.Height - 2*borderWidth); g.FillRectangle(borderBrush, border); // right border.X = bounds.Right - borderWidth; g.FillRectangle(borderBrush, border); } // will return the width of the text box that will fit all the // tables names private int GetTableBoxWidth(Graphics g, Font font) { // try to make the font BOLD Font textFont = font; try { textFont = new Font(font, FontStyle.Bold); } catch { } int width = 0; for (int row = 0; row < parentsCount; row ++) { DataGridState dgs = (DataGridState) parents[row]; // Graphics.MeasureString(...) returns different results for ": " than for " :" // string displayTableName = dgs.ListManager.GetListName() + " :"; int size = (int) g.MeasureString(displayTableName, textFont).Width; width = Math.Max(size, width); } return width; } // will return the width of the text box that will // fit all the column names private int GetColBoxWidth(Graphics g, Font font, int colNum) { int width = 0; for (int row = 0; row < parentsCount; row ++) { DataGridState dgs = (DataGridState) parents[row]; GridColumnStylesCollection columns = dgs.GridColumnStyles; if (colNum < columns.Count) { // Graphics.MeasureString(...) returns different results for ": " than for " :" // string colName = columns[colNum].HeaderText + " :"; int size = (int) g.MeasureString(colName, font).Width; width = Math.Max(size, width); } } return width; } // will return the width of the best fit for the column // private int GetColDataBoxWidth(Graphics g, int colNum) { int width = 0; for (int row = 0; row < parentsCount; row ++) { DataGridState dgs = (DataGridState) parents[row]; GridColumnStylesCollection columns = dgs.GridColumnStyles; if (colNum < columns.Count) { object value = columns[colNum].GetColumnValueAtRow((CurrencyManager) dataGrid.BindingContext[dgs.DataSource, dgs.DataMember], dgs.LinkingRow.RowNumber); int size = columns[colNum].GetPreferredSize(g, value).Width; width = Math.Max(size, width); } } return width; } // will return the count of the table with the largest number of columns private int ColsCount() { int colNum = 0; for (int row = 0; row < parentsCount; row ++) { DataGridState dgs = (DataGridState) parents[row]; colNum = Math.Max(colNum, dgs.GridColumnStyles.Count); } return colNum; } // will return the total width required to paint the parentRows private int TotalWidth(int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) { int totalWidth = 0; totalWidth += tableNameBoxWidth; Debug.Assert(colsNameWidths.Length == colsDataWidths.Length, "both arrays are as long as the largest column count in dgs"); for (int i = 0; i < colsNameWidths.Length; i ++) { totalWidth += colsNameWidths[i]; totalWidth += colsDataWidths[i]; } // let 3 pixels in between datacolumns // see DonnaWa totalWidth += 3 * (colsNameWidths.Length - 1); return totalWidth; } // computes the layout for the parent rows // private void ComputeLayout(Rectangle bounds, int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) { int totalWidth = TotalWidth(tableNameBoxWidth, colsNameWidths, colsDataWidths); if (totalWidth > bounds.Width) { layout.leftArrow = new Rectangle(bounds.X, bounds.Y, 15, bounds.Height); layout.data = new Rectangle(layout.leftArrow.Right, bounds.Y, bounds.Width - 30, bounds.Height); layout.rightArrow = new Rectangle(layout.data.Right, bounds.Y, 15, bounds.Height); } else { layout.data = bounds; layout.leftArrow = Rectangle.Empty; layout.rightArrow = Rectangle.Empty; } } private void PaintParentRows(Graphics g, Rectangle bounds, bool alignToRight) { // variables needed for aligning the table and column names int tableNameBoxWidth = 0; int numCols = ColsCount(); int[] colsNameWidths = new int[numCols]; int[] colsDataWidths = new int[numCols]; // compute the size of the box that will contain the tableName // if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.TableName || dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) { tableNameBoxWidth = GetTableBoxWidth(g, dataGrid.Font); } // initialiaze the arrays that contain the column names and the column size // for (int i = 0; i < numCols; i++) { if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.ColumnName || dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) { colsNameWidths[i] = GetColBoxWidth(g, dataGrid.Font, i); } else { colsNameWidths[i] = 0; } colsDataWidths[i] = GetColDataBoxWidth(g, i); } // compute the layout // ComputeLayout(bounds, tableNameBoxWidth, colsNameWidths, colsDataWidths); // paint the navigation arrows, if necessary // if (!layout.leftArrow.IsEmpty) { g.FillRectangle(BackBrush, layout.leftArrow); PaintLeftArrow(g, layout.leftArrow, alignToRight); } // paint the parent rows: // Rectangle rowBounds = layout.data; for (int row = 0; row < parentsCount; ++row) { rowBounds.Height = (int) rowHeights[row]; if (rowBounds.Y > bounds.Bottom) break; int paintedWidth = PaintRow(g, rowBounds, row, dataGrid.Font, alignToRight, tableNameBoxWidth, colsNameWidths, colsDataWidths); if (row == parentsCount-1) break; // draw the grid line below g.DrawLine(gridLinePen, rowBounds.X, rowBounds.Bottom, rowBounds.X + paintedWidth, rowBounds.Bottom); rowBounds.Y += rowBounds.Height; } if (!layout.rightArrow.IsEmpty) { g.FillRectangle(BackBrush, layout.rightArrow); PaintRightArrow(g, layout.rightArrow, alignToRight); } } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private Bitmap GetBitmap(string bitmapName, Color transparentColor) { Bitmap b = null; try { b = new Bitmap(typeof(DataGridParentRows), bitmapName); b.MakeTransparent(transparentColor); } catch (Exception e) { Debug.Fail("Failed to load bitmap: " + bitmapName, e.ToString()); } return b; } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private Bitmap GetRightArrowBitmap() { if (rightArrow == null) rightArrow = GetBitmap("DataGridParentRows.RightArrow.bmp", Color.White); return rightArrow; } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private Bitmap GetLeftArrowBitmap() { if (leftArrow == null) leftArrow = GetBitmap("DataGridParentRows.LeftArrow.bmp", Color.White); return leftArrow; } private void PaintBitmap(Graphics g, Bitmap b, Rectangle bounds) { // center the bitmap in the bounds: int bmpX = bounds.X + (bounds.Width - b.Width) / 2; int bmpY = bounds.Y + (bounds.Height - b.Height) / 2; Rectangle bmpRect = new Rectangle(bmpX, bmpY, b.Width, b.Height); g.FillRectangle(BackBrush, bmpRect); // now draw the bitmap ImageAttributes attr = new ImageAttributes(); this.colorMap[0].NewColor = this.ForeColor; attr.SetRemapTable(colorMap, ColorAdjustType.Bitmap); g.DrawImage(b, bmpRect, 0, 0, bmpRect.Width, bmpRect.Height,GraphicsUnit.Pixel, attr); attr.Dispose(); } /* private void PaintOverButton(Graphics g, Rectangle bounds) { } */ private void PaintDownButton(Graphics g, Rectangle bounds) { g.DrawLine(Pens.Black, bounds.X, bounds.Y, bounds.X + bounds.Width, bounds.Y); // the top g.DrawLine(Pens.White, bounds.X + bounds.Width, bounds.Y, bounds.X + bounds.Width, bounds.Y + bounds.Height); // the right side g.DrawLine(Pens.White, bounds.X + bounds.Width, bounds.Y + bounds.Height, bounds.X, bounds.Y + bounds.Height); // the right side g.DrawLine(Pens.Black, bounds.X, bounds.Y + bounds.Height, bounds.X, bounds.Y); // the left side } private void PaintLeftArrow(Graphics g, Rectangle bounds, bool alignToRight) { Bitmap bmp = GetLeftArrowBitmap(); // paint the border around this bitmap if this is the case // /* if (overLeftArrow) { Debug.Assert(!downLeftArrow, "can both of those happen?"); PaintOverButton(g, bounds); layout.leftArrow.Inflate(-1,-1); } */ if (downLeftArrow) { PaintDownButton(g, bounds); layout.leftArrow.Inflate(-1,-1); lock (bmp) { PaintBitmap(g, bmp, bounds); } layout.leftArrow.Inflate(1,1); } else { lock (bmp) { PaintBitmap(g, bmp, bounds); } } } private void PaintRightArrow(Graphics g, Rectangle bounds, bool alignToRight) { Bitmap bmp = GetRightArrowBitmap(); // paint the border around this bitmap if this is the case // /* if (overRightArrow) { Debug.Assert(!downRightArrow, "can both of those happen?"); PaintOverButton(g, bounds); layout.rightArrow.Inflate(-1,-1); } */ if (downRightArrow) { PaintDownButton(g, bounds); layout.rightArrow.Inflate(-1,-1); lock (bmp) { PaintBitmap(g, bmp, bounds); } layout.rightArrow.Inflate(1,1); } else { lock (bmp) { PaintBitmap(g, bmp, bounds); } } } private int PaintRow(Graphics g, Rectangle bounds, int row, Font font, bool alignToRight, int tableNameBoxWidth, int[] colsNameWidths, int[] colsDataWidths) { DataGridState dgs = (DataGridState) parents[row]; Rectangle paintBounds = bounds; Rectangle rowBounds = bounds; paintBounds.Height = (int) rowHeights[row]; rowBounds.Height = (int) rowHeights[row]; int paintedWidth = 0; // used for scrolling: when paiting, we will skip horizOffset cells in the dataGrid ParentRows int skippedCells = 0; // paint the table name if ( dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.TableName || dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) { if (skippedCells < horizOffset) { // skip this skippedCells ++; } else { paintBounds.Width = Math.Min(paintBounds.Width, tableNameBoxWidth); paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); string displayTableName = dgs.ListManager.GetListName() + ": "; PaintText(g, paintBounds, displayTableName, font, true, alignToRight); // true is for painting bold paintedWidth += paintBounds.Width; } } if (paintedWidth >= bounds.Width) return bounds.Width; // we painted everything rowBounds.Width -= paintedWidth; rowBounds.X += alignToRight ? 0 : paintedWidth; paintedWidth += PaintColumns(g, rowBounds, dgs, font, alignToRight, colsNameWidths, colsDataWidths, skippedCells); // paint the possible space left after columns if (paintedWidth < bounds.Width) { paintBounds.X = bounds.X + paintedWidth; paintBounds.Width = bounds.Width - paintedWidth; paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); g.FillRectangle(BackBrush, paintBounds); } return paintedWidth; } private int PaintColumns(Graphics g, Rectangle bounds, DataGridState dgs, Font font, bool alignToRight, int[] colsNameWidths, int[] colsDataWidths, int skippedCells) { Rectangle paintBounds = bounds; Rectangle rowBounds = bounds; GridColumnStylesCollection cols = dgs.GridColumnStyles; int cx = 0; for (int i = 0; i < cols.Count; i ++) { if (cx >= bounds.Width) break; // paint the column name, if we have to if (dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.ColumnName || dataGrid.ParentRowsLabelStyle == DataGridParentRowsLabelStyle.Both) { if (skippedCells < horizOffset) { // skip this column } else { paintBounds.X = bounds.X + cx; paintBounds.Width = Math.Min(bounds.Width - cx, colsNameWidths[i]); paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); string colName = cols[i].HeaderText + ": "; PaintText(g, paintBounds, colName, font, false, alignToRight); // false is for not painting bold cx += paintBounds.Width; } } if (cx >= bounds.Width) break; if (skippedCells < horizOffset) { // skip this cell skippedCells ++; } else { // paint the cell contents paintBounds.X = bounds.X + cx; paintBounds.Width = Math.Min(bounds.Width - cx, colsDataWidths[i]); paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); // when we paint the data grid parent rows, we want to paint the data at the position // stored in the currency manager. cols[i].Paint(g, paintBounds, (CurrencyManager) dataGrid.BindingContext[dgs.DataSource, dgs.DataMember], dataGrid.BindingContext[dgs.DataSource, dgs.DataMember].Position, BackBrush, ForeBrush, alignToRight); cx += paintBounds.Width; // draw the line to the right (or left, according to alignRight) // g.DrawLine(new Pen(SystemColors.ControlDark), alignToRight ? paintBounds.X : paintBounds.Right, paintBounds.Y, alignToRight ? paintBounds.X : paintBounds.Right, paintBounds.Bottom); // this is how wide the line is.... cx++; // put 3 pixels in between columns // see DonnaWa // if ( i < cols.Count - 1) { paintBounds.X = bounds.X + cx; paintBounds.Width = Math.Min(bounds.Width - cx, 3); paintBounds.X = MirrorRect(bounds, paintBounds, alignToRight); g.FillRectangle(BackBrush, paintBounds); cx += 3; } } } return cx; } /// <include file='doc\DataGridParentRows.uex' path='docs/doc[@for="DataGridParentRows.PaintText"]/*' /> /// <devdoc> /// Draws on the screen the text. It is used only to paint the Table Name and the column Names /// Returns the width of bounding rectangle that was passed in /// </devdoc> private int PaintText(Graphics g, Rectangle textBounds, string text, Font font, bool bold, bool alignToRight) { Font textFont = font; if (bold) try { textFont = new Font(font, FontStyle.Bold); } catch {} else textFont = font; // right now, we paint the entire box, cause it will be used anyway g.FillRectangle(BackBrush, textBounds); StringFormat format = new StringFormat(); if (alignToRight) { format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; format.Alignment = StringAlignment.Far; } format.FormatFlags |= StringFormatFlags.NoWrap; // part 1, section 3: put the table and the column name in the // parent rows at the same height as the dataGridTextBoxColumn draws the string // textBounds.Offset(0, 2); textBounds.Height -= 2; g.DrawString(text, textFont, ForeBrush, textBounds, format); format.Dispose(); return textBounds.Width; } // will return the X coordinate of the containedRect mirrored within the surroundingRect // according to the value of alignToRight private int MirrorRect(Rectangle surroundingRect, Rectangle containedRect, bool alignToRight) { Debug.Assert(containedRect.X >= surroundingRect.X && containedRect.Right <= surroundingRect.Right, "containedRect is not contained in surroundingRect"); if (alignToRight) return surroundingRect.Right - containedRect.Right + surroundingRect.X; else return containedRect.X; } private class Layout { public Rectangle data; public Rectangle leftArrow; public Rectangle rightArrow; public Layout() { data = Rectangle.Empty; leftArrow = Rectangle.Empty; rightArrow = Rectangle.Empty; } public override string ToString() { StringBuilder sb = new StringBuilder(200); sb.Append("ParentRows Layout: \n"); sb.Append("data = "); sb.Append(data.ToString()); sb.Append("\n leftArrow = "); sb.Append(leftArrow.ToString()); sb.Append("\n rightArrow = "); sb.Append(rightArrow.ToString()); sb.Append("\n"); return sb.ToString(); } } [ComVisible(true)] protected internal class DataGridParentRowsAccessibleObject : AccessibleObject { DataGridParentRows owner = null; public DataGridParentRowsAccessibleObject(DataGridParentRows owner) : base() { Debug.Assert(owner != null, "DataGridParentRowsAccessibleObject must have a valid owner"); this.owner = owner; } internal DataGridParentRows Owner { get { return owner; } } public override Rectangle Bounds { get { return owner.dataGrid.RectangleToScreen(owner.dataGrid.ParentRowsBounds); } } public override string DefaultAction { get { return SR.GetString(SR.AccDGNavigateBack); } } public override string Name { get { return SR.GetString(SR.AccDGParentRows); } } public override AccessibleObject Parent { [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] get { return owner.dataGrid.AccessibilityObject; } } public override AccessibleRole Role { get { return AccessibleRole.List; } } public override AccessibleStates State { get { AccessibleStates state = AccessibleStates.ReadOnly; if (owner.parentsCount == 0) { state |= AccessibleStates.Invisible; } if (owner.dataGrid.ParentRowsVisible) { state |= AccessibleStates.Expanded; } else { state |= AccessibleStates.Collapsed; } return state; } } public override string Value { [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] get { return null; } } [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public override void DoDefaultAction() { owner.dataGrid.NavigateBack(); } public override AccessibleObject GetChild(int index) { return ((DataGridState)owner.parents[index]).ParentRowAccessibleObject; } public override int GetChildCount() { return owner.parentsCount; } /// <include file='doc\DataGridParentRows.uex' path='docs/doc[@for="DataGridParentRows.DataGridParentRowsAccessibleObject.GetFocused"]/*' /> /// <devdoc> /// Returns the currently focused child, if any. /// Returns this if the object itself is focused. /// </devdoc> public override AccessibleObject GetFocused() { return null; } internal AccessibleObject GetNext(AccessibleObject child) { int children = GetChildCount(); bool hit = false; for (int i=0; i<children; i++) { if (hit) { return GetChild(i); } if (GetChild(i) == child) { hit = true; } } return null; } internal AccessibleObject GetPrev(AccessibleObject child) { int children = GetChildCount(); bool hit = false; for (int i=children-1; i>=0; i--) { if (hit) { return GetChild(i); } if (GetChild(i) == child) { hit = true; } } return null; } /// <include file='doc\DataGridParentRows.uex' path='docs/doc[@for="DataGridParentRows.DataGridParentRowsAccessibleObject.Navigate"]/*' /> /// <devdoc> /// Navigate to the next or previous grid entry. /// </devdoc> [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public override AccessibleObject Navigate(AccessibleNavigation navdir) { switch (navdir) { case AccessibleNavigation.Right: case AccessibleNavigation.Next: case AccessibleNavigation.Down: return Parent.GetChild(1); case AccessibleNavigation.Up: case AccessibleNavigation.Left: case AccessibleNavigation.Previous: return Parent.GetChild(GetChildCount() - 1); case AccessibleNavigation.FirstChild: if (GetChildCount() > 0) { return GetChild(0); } break; case AccessibleNavigation.LastChild: if (GetChildCount() > 0) { return GetChild(GetChildCount() - 1); } break; } return null; } [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public override void Select(AccessibleSelection flags) { } } } }
// 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: A Stream whose backing store is memory. Great ** for temporary storage without creating a temp file. Also ** lets users expose a byte[] as a stream. ** ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { // A MemoryStream represents a Stream in memory (ie, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. [ContractPublicPropertyName("Length")] private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? [NonSerialized] private Task<int> _lastReadTask; // The last successful task returned from ReadAsync private const int MemStreamMaxLength = Int32.MaxValue; public MemoryStream() : this(0) { } public MemoryStream(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); } Contract.EndContractBlock(); _buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>(); _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } public MemoryStream(byte[] buffer) : this(buffer, true) { } public MemoryStream(byte[] buffer, bool writable) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); Contract.EndContractBlock(); _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream(byte[] buffer, int index, int count) : this(buffer, index, count, true, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) : this(buffer, index, count, writable, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _writable; } } private void EnsureWriteable() { if (!CanWrite) __Error.WriteNotSupported(); } protected override void Dispose(bool disposing) { try { if (disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work. _lastReadTask = null; } } finally { // Call base.Close() to cleanup async IO resources base.Dispose(disposing); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity(int value) { // Check for overflow if (value < 0) throw new IOException(SR.IO_StreamTooLong); if (value > _capacity) { int newCapacity = value; if (newCapacity < 256) newCapacity = 256; // We are ok with this overflowing since the next statement will deal // with the cases where _capacity*2 overflows. if (newCapacity < _capacity * 2) newCapacity = _capacity * 2; // We want to expand the array up to Array.MaxArrayLengthOneDimensional // And we want to give the user the value that they asked for if ((uint)(_capacity * 2) > Array.MaxByteArrayLength) newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength; Capacity = newCapacity; return true; } return false; } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Flush(); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } public virtual byte[] GetBuffer() { if (!_exposable) throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); return _buffer; } public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) { if (!_exposable) { buffer = default(ArraySegment<byte>); return false; } buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin)); return true; } // -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) --------------- // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) internal byte[] InternalGetBuffer() { return _buffer; } // PERF: Get origin and length - used in ResourceWriter. [FriendAccessAllowed] internal void InternalGetOriginAndLength(out int origin, out int length) { if (!_isOpen) __Error.StreamIsClosed(); origin = _origin; length = _length; } // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() { if (!_isOpen) __Error.StreamIsClosed(); return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if (!_isOpen) __Error.StreamIsClosed(); int pos = (_position += 4); // use temp to avoid a race condition if (pos > _length) { _position = _length; __Error.EndOfFile(); } return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead(int count) { if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n < 0) n = 0; Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. _position += n; return n; } // Gets & sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if (!_isOpen) __Error.StreamIsClosed(); return _capacity - _origin; } set { // Only update the capacity if the MS is expandable and the value is different than the current capacity. // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); Contract.Ensures(_capacity - _origin == value); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable(); // MemoryStream has this invariant: _origin > 0 => !expandable (see ctors) if (_expandable && value != _capacity) { if (value > 0) { byte[] newBuffer = new byte[value]; if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length); _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { get { if (!_isOpen) __Error.StreamIsClosed(); return _length - _origin; } } public override long Position { get { if (!_isOpen) __Error.StreamIsClosed(); return _position - _origin; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.Ensures(Position == value); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (value > MemStreamMaxLength) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); _position = _origin + (int)value; } } public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); int n = _length - _position; if (n > count) n = count; if (n <= 0) return 0; Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. if (n <= 8) { int byteCount = n; while (--byteCount >= 0) buffer[offset + byteCount] = _buffer[_position + byteCount]; } else Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n); _position += n; return n; } public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Read(...) // If cancellation was requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); try { int n = Read(buffer, offset, count); var t = _lastReadTask; Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion, "Expected that a stored last task completed successfully"); return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n)); } catch (OperationCanceledException oce) { return Task.FromCancellation<int>(oce); } catch (Exception exception) { return Task.FromException<int>(exception); } } public override int ReadByte() { if (!_isOpen) __Error.StreamIsClosed(); if (_position >= _length) return -1; return _buffer[_position++]; } public override void CopyTo(Stream destination, int bufferSize) { // Since we did not originally override this method, validate the arguments // the same way Stream does for back-compat. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read) when we are not sure. if (GetType() != typeof(MemoryStream)) { base.CopyTo(destination, bufferSize); return; } int originalPosition = _position; // Seek to the end of the MemoryStream. int remaining = InternalEmulateRead(_length - originalPosition); // If we were already at or past the end, there's no copying to do so just quit. if (remaining > 0) { // Call Write() on the other Stream, using our internal buffer and avoiding any // intermediary allocations. destination.Write(_buffer, originalPosition, remaining); } } public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { // This implementation offers beter performance compared to the base class version. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to ReadAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into ReadAsync) when we are not sure. if (this.GetType() != typeof(MemoryStream)) return base.CopyToAsync(destination, bufferSize, cancellationToken); // If cancelled - return fast: if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); // Avoid copying data from this buffer into a temp buffer: // (require that InternalEmulateRead does not throw, // otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below) Int32 pos = _position; Int32 n = InternalEmulateRead(_length - _position); // If destination is not a memory stream, write there asynchronously: MemoryStream memStrDest = destination as MemoryStream; if (memStrDest == null) return destination.WriteAsync(_buffer, pos, n, cancellationToken); try { // If destination is a MemoryStream, CopyTo synchronously: memStrDest.Write(_buffer, pos, n); return Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) __Error.StreamIsClosed(); if (offset > MemStreamMaxLength) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength); switch (loc) { case SeekOrigin.Begin: { int tempPosition = unchecked(_origin + (int)offset); if (offset < 0 || tempPosition < _origin) throw new IOException(SR.IO_SeekBeforeBegin); _position = tempPosition; break; } case SeekOrigin.Current: { int tempPosition = unchecked(_position + (int)offset); if (unchecked(_position + offset) < _origin || tempPosition < _origin) throw new IOException(SR.IO_SeekBeforeBegin); _position = tempPosition; break; } case SeekOrigin.End: { int tempPosition = unchecked(_length + (int)offset); if (unchecked(_length + offset) < _origin || tempPosition < _origin) throw new IOException(SR.IO_SeekBeforeBegin); _position = tempPosition; break; } default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } Debug.Assert(_position >= 0, "_position >= 0"); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength(long value) { if (value < 0 || value > Int32.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } Contract.Ensures(_length - _origin == value); Contract.EndContractBlock(); EnsureWriteable(); // Origin wasn't publicly exposed above. Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails. if (value > (Int32.MaxValue - _origin)) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity(newLength); if (!allocatedNewArray && newLength > _length) Array.Clear(_buffer, _length, newLength - _length); _length = newLength; if (_position > newLength) _position = newLength; } public virtual byte[] ToArray() { BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy."); byte[] copy = new byte[_length - _origin]; Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin); return copy; } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); int i = _position + count; // Check for overflow if (i < 0) throw new IOException(SR.IO_StreamTooLong); if (i > _length) { bool mustZero = _position > _length; if (i > _capacity) { bool allocatedNewArray = EnsureCapacity(i); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, i - _length); _length = i; } if ((count <= 8) && (buffer != _buffer)) { int byteCount = count; while (--byteCount >= 0) _buffer[_position + byteCount] = buffer[offset + byteCount]; } else Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count); _position = i; } public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // contract validation copied from Write(...) // If cancellation is already requested, bail early if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (OperationCanceledException oce) { return Task.FromCancellation<VoidTaskResult>(oce); } catch (Exception exception) { return Task.FromException(exception); } } public override void WriteByte(byte value) { if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); if (_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if (newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity(newLength); if (allocatedNewArray) mustZero = false; } if (mustZero) Array.Clear(_buffer, _length, _position - _length); _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); stream.Write(_buffer, _origin, _length - _origin); } } }
using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Ductus.FluentDocker.Extensions; using Ductus.FluentDocker.Model.Builders; using Ductus.FluentDocker.Model.Common; using Ductus.FluentDocker.Model.Containers; using Ductus.FluentDocker.Services; using Ductus.FluentDocker.Services.Extensions; using Ductus.FluentDocker.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace Ductus.FluentDocker.Tests.FluentApiTests { [TestClass] public class FluentContainerBasicTests { [ClassInitialize] public static void Initialize(TestContext ctx) { Utilities.LinuxMode(); Utilities.EnsureImage("postgres:9.6-alpine", TimeSpan.FromMinutes(1.0)); } [TestMethod] [TestCategory("CI")] public void VersionInfoShallBePossibleToRetrieve() { var v = Fd.Version(); Assert.IsTrue(v != null && v.Length > 0); } [TestMethod] [TestCategory("CI")] public void BuildContainerRenderServiceInStoppedMode() { using ( var container = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .Build()) { AreEqual(ServiceRunningState.Stopped, container.State); } } [TestMethod] [TestCategory("CI")] public void UseStaticBuilderWillAlwaysRunDisposeOnContainer() { Fd.Container(c => c.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .WaitForPort("5432/tcp", TimeSpan.FromSeconds(30)), svc => { var config = svc.GetConfiguration(); AreEqual(ServiceRunningState.Running, svc.State); IsTrue(config.Config.Env.Any(x => x == "POSTGRES_PASSWORD=mysecretpassword")); }); } [TestMethod] [TestCategory("CI")] public void UseStaticBuilderAsExtension() { var build = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .WaitForPort("5432/tcp", TimeSpan.FromSeconds(30)); build.Container(svc => { var config = svc.GetConfiguration(); AreEqual(ServiceRunningState.Running, svc.State); IsTrue(config.Config.Env.Any(x => x == "POSTGRES_PASSWORD=mysecretpassword")); }); } [TestMethod] [TestCategory("CI")] public void BuildAndStartContainerWithKeepContainerWillLeaveContainerInArchive() { string id; using ( var container = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .KeepContainer() .Build() .Start()) { id = container.Id; IsNotNull(id); } // We shall have the container as stopped by now. var cont = Fd.Discover() .Select(host => host.GetContainers().FirstOrDefault(x => x.Id == id)) .FirstOrDefault(container => null != container); IsNotNull(cont); cont.Remove(true); } [TestMethod] [TestCategory("CI")] public void BuildAndStartContainerWithCustomEnvironmentWillBeReflectedInGetConfiguration() { using ( var container = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .Build() .Start()) { var config = container.GetConfiguration(); AreEqual(ServiceRunningState.Running, container.State); IsTrue(config.Config.Env.Any(x => x == "POSTGRES_PASSWORD=mysecretpassword")); } } [TestMethod] [TestCategory("CI")] public void PauseAndResumeShallWorkOnSingleContainer() { using ( var container = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .Build() .Start()) { AreEqual(ServiceRunningState.Running, container.State); container.Pause(); AreEqual(ServiceRunningState.Paused, container.State); var config = container.GetConfiguration(true); AreEqual(ServiceRunningState.Paused, config.State.ToServiceState()); container.Start(); AreEqual(ServiceRunningState.Running, container.State); config = container.GetConfiguration(true); AreEqual(ServiceRunningState.Running, config.State.ToServiceState()); } } [TestMethod] [TestCategory("CI")] public void ExplicitPortMappingShouldWork() { using ( var container = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(40001, 5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .Build() .Start()) { var endpoint = container.ToHostExposedEndpoint("5432/tcp"); AreEqual(40001, endpoint.Port); } } [TestMethod] [TestCategory("CI")] public void ImplicitPortMappingShouldWork() { using ( var container = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .Build() .Start()) { var endpoint = container.ToHostExposedEndpoint("5432/tcp"); AreNotEqual(0, endpoint.Port); } } [TestMethod] [TestCategory("CI")] public void WaitForPortShallWork() { using ( var container = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .WaitForPort("5432/tcp", 30000 /*30s*/) .Build() .Start()) { var config = container.GetConfiguration(true); AreEqual(ServiceRunningState.Running, config.State.ToServiceState()); } } [TestMethod] [TestCategory("CI")] public void WaitForProcessShallWork() { using ( var container = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .WaitForProcess("postgres", 30000 /*30s*/) .Build() .Start()) { var config = container.GetConfiguration(true); AreEqual(ServiceRunningState.Running, config.State.ToServiceState()); } } [TestMethod] [TestCategory("Volume")] public async Task VolumeMappingShallWork() { const string html = "<html><head>Hello World</head><body><h1>Hello world</h1></body></html>"; var hostPath = (TemplateString)@"${TEMP}/fluentdockertest/${RND}"; Directory.CreateDirectory(hostPath); using ( var container = Fd.UseContainer() .UseImage("nginx:1.13.6-alpine") .ExposePort(80) .Mount(hostPath, "/usr/share/nginx/html", MountType.ReadOnly) .Build() .Start() .WaitForPort("80/tcp", 30000 /*30s*/)) { AreEqual(ServiceRunningState.Running, container.State); try { File.WriteAllText(Path.Combine(hostPath, "hello.html"), html); var response = await $"http://{container.ToHostExposedEndpoint("80/tcp")}/hello.html".Wget(); AreEqual(html, response); } finally { if (Directory.Exists(hostPath)) Directory.Delete(hostPath, true); } } } [TestMethod] [TestCategory("Volume")] public async Task VolumeMappingWithSpacesShallWork() { const string html = "<html><head>Hello World</head><body><h1>Hello world</h1></body></html>"; var hostPath = (TemplateString)@"${TEMP}/fluentdockertest/with space in path/${RND}"; Directory.CreateDirectory(hostPath); using ( var container = Fd.UseContainer() .UseImage("nginx:1.13.6-alpine") .ExposePort(80) .Mount(hostPath, "/usr/share/nginx/html", MountType.ReadOnly) .WaitForPort("80/tcp", 30000 /*30s*/) .Build() .Start()) { AreEqual(ServiceRunningState.Running, container.State); try { File.WriteAllText(Path.Combine(hostPath, "hello.html"), html); var response = await $"http://{container.ToHostExposedEndpoint("80/tcp")}/hello.html".Wget(); AreEqual(html, response); } finally { if (Directory.Exists(hostPath)) Directory.Delete(hostPath, true); } } } [TestMethod] [TestCategory("CI")] public void CopyFromRunningContainerShallWork() { var fullPath = (TemplateString)@"${TEMP}/fluentdockertest/${RND}"; Directory.CreateDirectory(fullPath); try { using (Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .Build() .Start() .CopyFrom("/", fullPath)) { var files = Directory.EnumerateFiles(fullPath).ToArray(); IsTrue(files.Any(x => x.EndsWith(".dockerenv"))); } } finally { if (Directory.Exists(fullPath)) Directory.Delete(fullPath, true); } } [TestMethod] [TestCategory("CI")] public void CopyBeforeDisposeContainerShallWork() { var fullPath = (TemplateString)@"${TEMP}/fluentdockertest/${RND}"; Directory.CreateDirectory(fullPath); try { using (Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .CopyOnDispose("/", fullPath) .Build() .Start()) { } var files = Directory.EnumerateFiles(fullPath).ToArray(); IsTrue(files.Any(x => x.EndsWith(".dockerenv"))); } finally { if (Directory.Exists(fullPath)) Directory.Delete(fullPath, true); } } [TestMethod] [TestCategory("CI")] public void ExportToTarFileWhenDisposeShallWork() { var fullPath = (TemplateString)@"${TEMP}/fluentdockertest/${RND}/export.tar"; // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); try { using (Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .ExportOnDispose(fullPath) .Build() .Start()) { } IsTrue(File.Exists(fullPath)); } finally { if (File.Exists(fullPath)) Directory.Delete(Path.GetDirectoryName(fullPath), true); } } [TestMethod] [TestCategory("CI")] public void ExportExplodedWhenDisposeShallWork() { var fullPath = (TemplateString)@"${TEMP}/fluentdockertest/${RND}"; Directory.CreateDirectory(fullPath); try { using (Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .ExportExplodedOnDispose(fullPath) .Build() .Start()) { } IsTrue(Directory.Exists(fullPath)); var files = Directory.GetFiles(fullPath).ToArray(); IsTrue(files.Any(x => x.Contains(".dockerenv"))); } finally { if (Directory.Exists(fullPath)) Directory.Delete(fullPath, true); } } [TestMethod] [TestCategory("CI")] public void ExportWithConditionDisposeShallWork() { var fullPath = (TemplateString)@"${TEMP}/fluentdockertest/${RND}/export.tar"; // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); // Probably the opposite is reverse where the last statement in the using clause // would set failure = false - but this is a unit test ;) var failure = false; try { // ReSharper disable once AccessToModifiedClosure using (Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .ExportOnDispose(fullPath, svc => failure) .Build() .Start()) { failure = true; } IsTrue(File.Exists(fullPath)); } finally { if (File.Exists(fullPath)) Directory.Delete(Path.GetDirectoryName(fullPath), true); } } [TestMethod] [TestCategory("CI")] public void CopyToRunningContainerShallWork() { var fullPath = (TemplateString)@"${TEMP}/fluentdockertest/${RND}/hello.html"; // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); File.WriteAllText(fullPath, "<html><head>Hello World</head><body><h1>Hello world</h1></body></html>"); try { using ( var container = Fd.UseContainer() .UseImage("postgres:9.6-alpine") .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .Build() .Start() .WaitForProcess("postgres", 30000 /*30s*/) .Diff(out var before) .CopyTo("/bin", fullPath)) { var after = container.Diff(); IsFalse(before.Any(x => x.Item == "/bin/hello.html")); IsTrue(after.Any(x => x.Item == "/bin/hello.html")); } } finally { if (Directory.Exists(fullPath)) Directory.Delete(fullPath, true); } } [TestMethod] [TestCategory("CI")] public void ReuseOfExistingContainerShallWork() { using (Fd .UseContainer() .UseImage("postgres:9.6-alpine") .WithName("reusable-name") .Build()) using (Fd .UseContainer() .ReuseIfExists() .UseImage("postgres:9.6-alpine") .WithName("reusable-name") .Build()) { } } [TestMethod] [TestCategory("CI")] public void PullContainerBeforeRunningShallWork() { using ( var container = Fd.UseContainer() .UseImage("postgres:latest", true) .ExposePort(5432) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .WaitForProcess("postgres", 30000 /*30s*/) .Build() .Start()) { var config = container.GetConfiguration(true); AreEqual(ServiceRunningState.Running, config.State.ToServiceState()); } } [TestMethod] [TestCategory("CI")] public void ContainerHealthCheckShallWork() { using ( var container = Fd.UseContainer() .UseImage("postgres:latest", true) .HealthCheck("exit") .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .Build() .Start()) { var config = container.GetConfiguration(true); AreEqual(HealthState.Starting, config.State.Health.Status); } } [TestMethod] [TestCategory("CI")] public void ContainerWithUlimitsShallWork() { using ( var container = Fd.UseContainer() .UseImage("postgres:latest", true) .UseUlimit(Ulimit.NoFile, 2048, 2048) .WithEnvironment("POSTGRES_PASSWORD=mysecretpassword") .Build() .Start()) { var config = container.GetConfiguration(true); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // Test class that verifies the integration with APM (Task => APM) section 2.5.11 in the TPL spec // "Asynchronous Programming Model", or the "Begin/End" pattern // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using Xunit; using System; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Threading.Tasks.Tests { /// <summary> /// A class that implements the APM pattern to ensure that TPL can support APM patttern /// </summary> public sealed class TaskAPMTests : IDisposable { /// <summary> /// Used to indicate whether to test TPL's Task or Future functionality for the APM pattern /// </summary> private bool _hasReturnType; /// <summary> /// Used to synchornize between Main thread and async thread, by blocking the main thread until /// the thread that invokes the TaskCompleted method via AsyncCallback finishes /// </summary> private ManualResetEvent _mre = new ManualResetEvent(false); /// <summary> /// The input value to LongTask<int>.DoTask/BeginDoTask /// </summary> private const int IntInput = 1000; /// <summary> /// The constant that defines the number of milliseconds to spinwait (to simulate work) in the LongTask class /// </summary> private const int LongTaskMilliseconds = 100; [Theory] [OuterLoop] [InlineData(true)] [InlineData(false)] public void WaitUntilCompleteTechnique(bool hasReturnType) { _hasReturnType = hasReturnType; LongTask longTask; if (_hasReturnType) longTask = new LongTask<int>(LongTaskMilliseconds); else longTask = new LongTask(LongTaskMilliseconds); // Prove that the Wait-until-done technique works IAsyncResult asyncResult = longTask.BeginDoTask(null, null); longTask.EndDoTask(asyncResult); AssertTaskCompleted(asyncResult); Assert.False(asyncResult.CompletedSynchronously, "Should not have completed synchronously."); } [Theory] [OuterLoop] [InlineData(true)] [InlineData(false)] public void PollUntilCompleteTechnique(bool hasReturnType) { _hasReturnType = hasReturnType; LongTask longTask; if (_hasReturnType) longTask = new LongTask<int>(LongTaskMilliseconds); else longTask = new LongTask(LongTaskMilliseconds); IAsyncResult asyncResult = longTask.BeginDoTask(null, null); while (!asyncResult.IsCompleted) { Task.Delay(300).Wait(); } AssertTaskCompleted(asyncResult); Assert.False(asyncResult.CompletedSynchronously, "Should not have completed synchronously."); } [Theory] [OuterLoop] [InlineData(true)] [InlineData(false)] public void WaitOnAsyncWaitHandleTechnique(bool hasReturnType) { _hasReturnType = hasReturnType; LongTask longTask; if (_hasReturnType) longTask = new LongTask<int>(LongTaskMilliseconds); else longTask = new LongTask(LongTaskMilliseconds); IAsyncResult asyncResult = longTask.BeginDoTask(null, null); asyncResult.AsyncWaitHandle.WaitOne(); AssertTaskCompleted(asyncResult); Assert.False(asyncResult.CompletedSynchronously, "Should not have completed synchronously."); } [Theory] [OuterLoop] [InlineData(true)] [InlineData(false)] public void CallbackTechnique(bool hasReturnType) { _hasReturnType = hasReturnType; LongTask longTask; if (_hasReturnType) longTask = new LongTask<int>(LongTaskMilliseconds); else longTask = new LongTask(LongTaskMilliseconds); IAsyncResult asyncResult; if (_hasReturnType) asyncResult = ((LongTask<int>)longTask).BeginDoTask(IntInput, TaskCompleted, longTask); else asyncResult = longTask.BeginDoTask(TaskCompleted, longTask); _mre.WaitOne(); //Block the main thread until async thread finishes executing the call back AssertTaskCompleted(asyncResult); Assert.False(asyncResult.CompletedSynchronously, "Should not have completed synchronously."); } /// <summary> /// Method used by the callback implementation by the APM /// </summary> /// <param name="ar"></param> private void TaskCompleted(IAsyncResult ar) { if (_hasReturnType) { LongTask<int> lt = (LongTask<int>)ar.AsyncState; int retValue = lt.EndDoTask(ar); if (retValue != IntInput) Assert.True(false, string.Format("Mismatch: Return = {0} vs Expect = {1}", retValue, IntInput)); } else { LongTask lt = (LongTask)ar.AsyncState; lt.EndDoTask(ar); } _mre.Set(); } /// <summary> /// Assert that the IAsyncResult represent a completed Task /// </summary> private void AssertTaskCompleted(IAsyncResult ar) { Assert.True(ar.IsCompleted); Assert.Equal(TaskStatus.RanToCompletion, ((Task)ar).Status); } public void Dispose() { _mre.Dispose(); } } /// <summary> /// A dummy class that simulates a long running task that implements IAsyncResult methods /// </summary> public class LongTask { // Amount of time to SpinWait, in milliseconds. protected readonly Int32 _msWaitDuration; public LongTask(Int32 milliseconds) { _msWaitDuration = milliseconds; } // Synchronous version of time-consuming method public void DoTask() { // Simulate time-consuming task SpinWait.SpinUntil(() => false, _msWaitDuration); } // Asynchronous version of time-consuming method (Begin part) public IAsyncResult BeginDoTask(AsyncCallback callback, Object state) { // Create IAsyncResult object identifying the asynchronous operation Task task = Task.Factory.StartNew( delegate { DoTask(); //simulates workload }, state); if (callback != null) { task.ContinueWith(delegate { callback(task); }); } return task; // Return the IAsyncResult to the caller } // Asynchronous version of time-consuming method (End part) public void EndDoTask(IAsyncResult asyncResult) { // We know that the IAsyncResult is really a Task object Task task = (Task)asyncResult; // Wait for operation to complete task.Wait(); } } /// <summary> /// A dummy class that simulates a long running Future that implements IAsyncResult methods /// </summary> public sealed class LongTask<T> : LongTask { public LongTask(Int32 milliseconds) : base(milliseconds) { } // Synchronous version of time-consuming method public T DoTask(T input) { SpinWait.SpinUntil(() => false, _msWaitDuration); // Simulate time-consuming task return input; // Return some result, for now, just return the input } public IAsyncResult BeginDoTask(T input, AsyncCallback callback, Object state) { // Create IAsyncResult object identifying the asynchronous operation Task<T> task = Task<T>.Factory.StartNew( delegate { return DoTask(input); }, state); task.ContinueWith(delegate { callback(task); }); return task; // Return the IAsyncResult to the caller } // Asynchronous version of time-consuming method (End part) new public T EndDoTask(IAsyncResult asyncResult) { // We know that the IAsyncResult is really a Task object Task<T> task = (Task<T>)asyncResult; // Return the result return task.Result; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using ChannelAdvisorAccess.Exceptions; using ChannelAdvisorAccess.Misc; namespace ChannelAdvisorAccess.Services.Items { public partial class ItemsService: IItemsService { #region Skus public IEnumerable< string > GetAllSkus( Mark mark = null ) { if( mark.IsBlank() ) mark = Mark.CreateNew(); try { ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo() ) ); var filteredSkus = this.GetFilteredSkus( new ItemsFilter(), mark ); ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, methodResult : filteredSkus.ToJson(), additionalInfo : this.AdditionalLogInfo() ) ); return filteredSkus; } catch( Exception exception ) { var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo() ), exception ); ChannelAdvisorLogger.LogTraceException( channelAdvisorException ); throw channelAdvisorException; } } public async Task< IEnumerable< string > > GetAllSkusAsync( Mark mark = null ) { if( mark.IsBlank() ) mark = Mark.CreateNew(); try { ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo() ) ); var filteredSkus = await this.GetFilteredSkusAsync( new ItemsFilter(), mark ).ConfigureAwait( false ); ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, methodResult : filteredSkus.ToJson(), additionalInfo : this.AdditionalLogInfo() ) ); return filteredSkus; } catch( Exception exception ) { var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo() ), exception ); ChannelAdvisorLogger.LogTraceException( channelAdvisorException ); throw channelAdvisorException; } } public IEnumerable< string > GetFilteredSkus( ItemsFilter filter, Mark mark = null ) { if( mark.IsBlank() ) mark = Mark.CreateNew(); try { ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo(), methodParameters : filter.ToJson() ) ); filter.Criteria.PageSize = 100; filter.Criteria.PageNumber = 0; filter.DetailLevel.IncludeClassificationInfo = true; filter.DetailLevel.IncludePriceInfo = true; filter.DetailLevel.IncludeQuantityInfo = true; var filteredSkus = new List< string >(); while( true ) { filter.Criteria.PageNumber += 1; var itemResponse = AP.CreateQuery( ExtensionsInternal.CreateMethodCallInfo( this.AdditionalLogInfo ) ).Get( () => { ChannelAdvisorLogger.LogTraceRetryStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo(), methodParameters : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : filter.ToJson() ) ); var apiResultOfArrayOfString = this._client.GetFilteredSkuList ( this._credentials, this.AccountId, filter.Criteria, filter.SortField, filter.SortDirection ); ChannelAdvisorLogger.LogTraceRetryEnd( this.CreateMethodCallInfo( mark : mark, methodResult : apiResultOfArrayOfString.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : filter.ToJson() ) ); return apiResultOfArrayOfString; } ); ChannelAdvisorLogger.LogTrace( this.CreateMethodCallInfo( mark : mark, methodResult : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndReturnsForTrace ) ? null : itemResponse.ToJson(), additionalInfo : this.AdditionalLogInfo() ) ); if( !this.IsRequestSuccessful( itemResponse ) ) { filteredSkus.Add( null ); continue; } var items = itemResponse.ResultData; if( items == null ) { ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, methodResult : filteredSkus.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : filter.ToJson() ) ); return filteredSkus; } filteredSkus.AddRange( items ); if( items.Length == 0 || items.Length < filter.Criteria.PageSize ) { ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, methodResult : filteredSkus.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : filter.ToJson() ) ); return filteredSkus; } } } catch( Exception exception ) { var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo() ), exception ); ChannelAdvisorLogger.LogTraceException( channelAdvisorException ); throw channelAdvisorException; } } public async Task< IEnumerable< string > > GetFilteredSkusAsync( ItemsFilter filter, Mark mark = null ) { if( mark.IsBlank() ) mark = Mark.CreateNew(); try { ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo(), methodParameters : filter.ToJson() ) ); filter.Criteria.PageSize = 100; filter.Criteria.PageNumber = 0; var skus = new List< string >(); while( true ) { filter.Criteria.PageNumber += 1; var itemResponse = await AP.CreateQueryAsync( ExtensionsInternal.CreateMethodCallInfo( this.AdditionalLogInfo ) ).Get( async () => { ChannelAdvisorLogger.LogTraceRetryStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo(), methodParameters : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : filter.ToJson() ) ); var getFilteredSkuListResponse = await this._client.GetFilteredSkuListAsync ( this._credentials, this.AccountId, filter.Criteria, filter.SortField, filter.SortDirection ).ConfigureAwait( false ); ChannelAdvisorLogger.LogTraceRetryEnd( this.CreateMethodCallInfo( mark : mark, methodResult : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : getFilteredSkuListResponse.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : filter.ToJson() ) ); return getFilteredSkuListResponse; } ).ConfigureAwait( false ); ChannelAdvisorLogger.LogTrace( this.CreateMethodCallInfo( mark : mark, methodResult : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndReturnsForTrace ) ? null : itemResponse.ToJson(), additionalInfo : this.AdditionalLogInfo() ) ); if( !this.IsRequestSuccessful( itemResponse.GetFilteredSkuListResult ) ) continue; var pageSkus = itemResponse.GetFilteredSkuListResult.ResultData; if( pageSkus == null ) { ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, methodResult : skus.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : filter.ToJson() ) ); return skus; } skus.AddRange( pageSkus ); if( pageSkus.Length == 0 || pageSkus.Length < filter.Criteria.PageSize ) { ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, methodResult : skus.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : filter.ToJson() ) ); return skus; } } } catch( Exception exception ) { var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo() ), exception ); ChannelAdvisorLogger.LogTraceException( channelAdvisorException ); throw channelAdvisorException; } } public async Task< PagedApiResponse< string > > GetFilteredSkusAsync( ItemsFilter filter, int startPage, int pageLimit, Mark mark = null ) { if( mark.IsBlank() ) mark = Mark.CreateNew(); var parameters = new { filter, startPage, pageLimit }; try { ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo(), methodParameters : parameters.ToJson() ) ); filter.Criteria.PageSize = 100; filter.Criteria.PageNumber = ( startPage > 0 ) ? startPage - 1 : 1; var skus = new List< string >(); for( var iteration = 0; iteration < pageLimit; iteration++ ) { filter.Criteria.PageNumber += 1; var itemResponse = await AP.CreateQueryAsync( ExtensionsInternal.CreateMethodCallInfo( this.AdditionalLogInfo ) ).Get( async () => { ChannelAdvisorLogger.LogTraceRetryStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo(), methodParameters : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : parameters.ToJson() ) ); var getFilteredSkuListResponse = await this._client.GetFilteredSkuListAsync( this._credentials, this.AccountId, filter.Criteria, filter.SortField, filter.SortDirection ) .ConfigureAwait( false ); ChannelAdvisorLogger.LogTraceRetryEnd( this.CreateMethodCallInfo( mark : mark, methodResult : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : getFilteredSkuListResponse.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : parameters.ToJson() ) ); return getFilteredSkuListResponse; } ).ConfigureAwait( false ); ChannelAdvisorLogger.LogTrace( this.CreateMethodCallInfo( mark : mark, methodResult : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndReturnsForTrace ) ? null : itemResponse.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndReturnsForTrace ) ? null : parameters.ToJson() ) ); if( !this.IsRequestSuccessful( itemResponse.GetFilteredSkuListResult ) ) continue; var pageSkus = itemResponse.GetFilteredSkuListResult.ResultData; if( pageSkus == null ) { var pagedApiResponse = new PagedApiResponse< string >( skus, filter.Criteria.PageNumber, true ); ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, methodResult : pagedApiResponse.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : parameters.ToJson() ) ); return pagedApiResponse; } skus.AddRange( pageSkus ); if( pageSkus.Length == 0 || pageSkus.Length < filter.Criteria.PageSize ) { var pagedApiResponse = new PagedApiResponse< string >( skus, filter.Criteria.PageNumber, true ); ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, methodResult : pagedApiResponse.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : parameters.ToJson() ) ); return pagedApiResponse; } } var apiResponse = new PagedApiResponse< string >( skus, filter.Criteria.PageNumber, false ); ChannelAdvisorLogger.LogTraceEnd( this.CreateMethodCallInfo( mark : mark, methodResult : apiResponse.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : parameters.ToJson() ) ); return apiResponse; } catch( Exception exception ) { var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo() ), exception ); ChannelAdvisorLogger.LogTraceException( channelAdvisorException ); throw channelAdvisorException; } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Automation; using Microsoft.WindowsAzure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.Management.Automation { /// <summary> /// Service operation for automation job schedules. (see /// http://aka.ms/azureautomationsdk/jobscheduleoperations for more /// information) /// </summary> internal partial class JobScheduleOperations : IServiceOperations<AutomationManagementClient>, IJobScheduleOperations { /// <summary> /// Initializes a new instance of the JobScheduleOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal JobScheduleOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Create a job schedule. (see /// http://aka.ms/azureautomationsdk/jobscheduleoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create job schedule /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the create job schedule operation. /// </returns> public async Task<JobScheduleCreateResponse> CreateAsync(string automationAccount, JobScheduleCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.Runbook == null) { throw new ArgumentNullException("parameters.Properties.Runbook"); } if (parameters.Properties.Schedule == null) { throw new ArgumentNullException("parameters.Properties.Schedule"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/jobSchedules/"; url = url + Guid.NewGuid().ToString(); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject jobScheduleCreateParametersValue = new JObject(); requestDoc = jobScheduleCreateParametersValue; JObject propertiesValue = new JObject(); jobScheduleCreateParametersValue["properties"] = propertiesValue; JObject scheduleValue = new JObject(); propertiesValue["schedule"] = scheduleValue; if (parameters.Properties.Schedule.Name != null) { scheduleValue["name"] = parameters.Properties.Schedule.Name; } JObject runbookValue = new JObject(); propertiesValue["runbook"] = runbookValue; if (parameters.Properties.Runbook.Name != null) { runbookValue["name"] = parameters.Properties.Runbook.Name; } if (parameters.Properties.Parameters != null) { if (parameters.Properties.Parameters is ILazyCollection == false || ((ILazyCollection)parameters.Properties.Parameters).IsInitialized) { JObject parametersDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties.Parameters) { string parametersKey = pair.Key; string parametersValue = pair.Value; parametersDictionary[parametersKey] = parametersValue; } propertiesValue["parameters"] = parametersDictionary; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobScheduleCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobScheduleCreateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JobSchedule jobScheduleInstance = new JobSchedule(); result.JobSchedule = jobScheduleInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { JobScheduleProperties propertiesInstance = new JobScheduleProperties(); jobScheduleInstance.Properties = propertiesInstance; JToken jobScheduleIdValue = propertiesValue2["jobScheduleId"]; if (jobScheduleIdValue != null && jobScheduleIdValue.Type != JTokenType.Null) { string jobScheduleIdInstance = ((string)jobScheduleIdValue); propertiesInstance.Id = jobScheduleIdInstance; } JToken scheduleValue2 = propertiesValue2["schedule"]; if (scheduleValue2 != null && scheduleValue2.Type != JTokenType.Null) { ScheduleAssociationProperty scheduleInstance = new ScheduleAssociationProperty(); propertiesInstance.Schedule = scheduleInstance; JToken nameValue = scheduleValue2["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); scheduleInstance.Name = nameInstance; } } JToken runbookValue2 = propertiesValue2["runbook"]; if (runbookValue2 != null && runbookValue2.Type != JTokenType.Null) { RunbookAssociationProperty runbookInstance = new RunbookAssociationProperty(); propertiesInstance.Runbook = runbookInstance; JToken nameValue2 = runbookValue2["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); runbookInstance.Name = nameInstance2; } } JToken parametersSequenceElement = ((JToken)propertiesValue2["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey2 = ((string)property.Name); string parametersValue2 = ((string)property.Value); propertiesInstance.Parameters.Add(parametersKey2, parametersValue2); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete the job schedule identified by job schedule name. (see /// http://aka.ms/azureautomationsdk/jobscheduleoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobScheduleName'> /// Required. The job schedule name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string automationAccount, Guid jobScheduleName, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("jobScheduleName", jobScheduleName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/jobSchedules/"; url = url + Uri.EscapeDataString(jobScheduleName.ToString()); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the job schedule identified by job schedule name. (see /// http://aka.ms/azureautomationsdk/jobscheduleoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobScheduleName'> /// Required. The job schedule name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get job schedule operation. /// </returns> public async Task<JobScheduleGetResponse> GetAsync(string automationAccount, Guid jobScheduleName, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("jobScheduleName", jobScheduleName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/jobSchedules/"; url = url + Uri.EscapeDataString(jobScheduleName.ToString()); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobScheduleGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobScheduleGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JobSchedule jobScheduleInstance = new JobSchedule(); result.JobSchedule = jobScheduleInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobScheduleProperties propertiesInstance = new JobScheduleProperties(); jobScheduleInstance.Properties = propertiesInstance; JToken jobScheduleIdValue = propertiesValue["jobScheduleId"]; if (jobScheduleIdValue != null && jobScheduleIdValue.Type != JTokenType.Null) { string jobScheduleIdInstance = ((string)jobScheduleIdValue); propertiesInstance.Id = jobScheduleIdInstance; } JToken scheduleValue = propertiesValue["schedule"]; if (scheduleValue != null && scheduleValue.Type != JTokenType.Null) { ScheduleAssociationProperty scheduleInstance = new ScheduleAssociationProperty(); propertiesInstance.Schedule = scheduleInstance; JToken nameValue = scheduleValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); scheduleInstance.Name = nameInstance; } } JToken runbookValue = propertiesValue["runbook"]; if (runbookValue != null && runbookValue.Type != JTokenType.Null) { RunbookAssociationProperty runbookInstance = new RunbookAssociationProperty(); propertiesInstance.Runbook = runbookInstance; JToken nameValue2 = runbookValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); runbookInstance.Name = nameInstance2; } } JToken parametersSequenceElement = ((JToken)propertiesValue["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); string parametersValue = ((string)property.Value); propertiesInstance.Parameters.Add(parametersKey, parametersValue); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve a list of job schedules. (see /// http://aka.ms/azureautomationsdk/jobscheduleoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list job schedule operation. /// </returns> public async Task<JobScheduleListResponse> ListAsync(string automationAccount, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/jobSchedules"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobScheduleListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobScheduleListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { JobSchedule jobScheduleInstance = new JobSchedule(); result.JobSchedules.Add(jobScheduleInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobScheduleProperties propertiesInstance = new JobScheduleProperties(); jobScheduleInstance.Properties = propertiesInstance; JToken jobScheduleIdValue = propertiesValue["jobScheduleId"]; if (jobScheduleIdValue != null && jobScheduleIdValue.Type != JTokenType.Null) { string jobScheduleIdInstance = ((string)jobScheduleIdValue); propertiesInstance.Id = jobScheduleIdInstance; } JToken scheduleValue = propertiesValue["schedule"]; if (scheduleValue != null && scheduleValue.Type != JTokenType.Null) { ScheduleAssociationProperty scheduleInstance = new ScheduleAssociationProperty(); propertiesInstance.Schedule = scheduleInstance; JToken nameValue = scheduleValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); scheduleInstance.Name = nameInstance; } } JToken runbookValue = propertiesValue["runbook"]; if (runbookValue != null && runbookValue.Type != JTokenType.Null) { RunbookAssociationProperty runbookInstance = new RunbookAssociationProperty(); propertiesInstance.Runbook = runbookInstance; JToken nameValue2 = runbookValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); runbookInstance.Name = nameInstance2; } } JToken parametersSequenceElement = ((JToken)propertiesValue["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); string parametersValue = ((string)property.Value); propertiesInstance.Parameters.Add(parametersKey, parametersValue); } } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve next list of schedules. (see /// http://aka.ms/azureautomationsdk/jobscheduleoperations for more /// information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list job schedule operation. /// </returns> public async Task<JobScheduleListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobScheduleListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobScheduleListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { JobSchedule jobScheduleInstance = new JobSchedule(); result.JobSchedules.Add(jobScheduleInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobScheduleProperties propertiesInstance = new JobScheduleProperties(); jobScheduleInstance.Properties = propertiesInstance; JToken jobScheduleIdValue = propertiesValue["jobScheduleId"]; if (jobScheduleIdValue != null && jobScheduleIdValue.Type != JTokenType.Null) { string jobScheduleIdInstance = ((string)jobScheduleIdValue); propertiesInstance.Id = jobScheduleIdInstance; } JToken scheduleValue = propertiesValue["schedule"]; if (scheduleValue != null && scheduleValue.Type != JTokenType.Null) { ScheduleAssociationProperty scheduleInstance = new ScheduleAssociationProperty(); propertiesInstance.Schedule = scheduleInstance; JToken nameValue = scheduleValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); scheduleInstance.Name = nameInstance; } } JToken runbookValue = propertiesValue["runbook"]; if (runbookValue != null && runbookValue.Type != JTokenType.Null) { RunbookAssociationProperty runbookInstance = new RunbookAssociationProperty(); propertiesInstance.Runbook = runbookInstance; JToken nameValue2 = runbookValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); runbookInstance.Name = nameInstance2; } } JToken parametersSequenceElement = ((JToken)propertiesValue["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); string parametersValue = ((string)property.Value); propertiesInstance.Parameters.Add(parametersKey, parametersValue); } } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using SchoolBusAPI.Models; namespace SchoolBusAPI.ViewModels { /// <summary> /// /// </summary> [DataContract] public partial class SchoolBusOwnerViewModel : IEquatable<SchoolBusOwnerViewModel> { /// <summary> /// Default constructor, required by entity framework /// </summary> public SchoolBusOwnerViewModel() { } /// <summary> /// Initializes a new instance of the <see cref="SchoolBusOwnerViewModel" /> class. /// </summary> /// <param name="Id">Primary Key (required).</param> /// <param name="Name">The name of the School Bus owner as defined by the user&amp;#x2F;Inspector. Not tied to the ICBC or NSC names, but whatever is most useful for the Inspectors..</param> /// <param name="Status">Status of the School Bus owner - enumerated value Active, Archived.</param> /// <param name="DateCreated">The date-time of the creation of the record from the audit fields. Since this might be surfaced in the API, adding it to the definition..</param> /// <param name="PrimaryContact">Link to the designated Primary Contact for the Inspector to the School Bus Owner organization..</param> /// <param name="District">The District to which this School Bus is affliated..</param> /// <param name="Contacts">The set of contacts related to the School Bus Owner..</param> /// <param name="Notes">The set of notes about the school bus owner entered by users..</param> /// <param name="Attachments">The set of attachments about the school bus owner uploaded by the users..</param> /// <param name="History">The history of updates made to the School Bus Owner data..</param> /// <param name="NextInspectionDate">The next inspection date associated with this owner.</param> /// <param name="NumberOfBuses">The number of buses for which this owner is associated with.</param> /// <param name="NextInspectionTypeCode">Type Code for the Next InspectionType. Null if there are no next inspections..</param> public SchoolBusOwnerViewModel(int Id, string Name = null, string Status = null, DateTime? DateCreated = null, Contact PrimaryContact = null, District District = null, List<Contact> Contacts = null, List<Note> Notes = null, List<Attachment> Attachments = null, List<History> History = null, DateTime? NextInspectionDate = null, int? NumberOfBuses = null, string NextInspectionTypeCode = null) { this.Id = Id; this.Name = Name; this.Status = Status; this.DateCreated = DateCreated; this.PrimaryContact = PrimaryContact; this.District = District; this.Contacts = Contacts; this.Notes = Notes; this.Attachments = Attachments; this.History = History; this.NextInspectionDate = NextInspectionDate; this.NumberOfBuses = NumberOfBuses; this.NextInspectionTypeCode = NextInspectionTypeCode; } /// <summary> /// Primary Key /// </summary> /// <value>Primary Key</value> [DataMember(Name="id")] [MetaDataExtension (Description = "Primary Key")] public int Id { get; set; } /// <summary> /// The name of the School Bus owner as defined by the user&#x2F;Inspector. Not tied to the ICBC or NSC names, but whatever is most useful for the Inspectors. /// </summary> /// <value>The name of the School Bus owner as defined by the user&#x2F;Inspector. Not tied to the ICBC or NSC names, but whatever is most useful for the Inspectors.</value> [DataMember(Name="name")] [MetaDataExtension (Description = "The name of the School Bus owner as defined by the user&amp;#x2F;Inspector. Not tied to the ICBC or NSC names, but whatever is most useful for the Inspectors.")] public string Name { get; set; } /// <summary> /// Status of the School Bus owner - enumerated value Active, Archived /// </summary> /// <value>Status of the School Bus owner - enumerated value Active, Archived</value> [DataMember(Name="status")] [MetaDataExtension (Description = "Status of the School Bus owner - enumerated value Active, Archived")] public string Status { get; set; } /// <summary> /// The date-time of the creation of the record from the audit fields. Since this might be surfaced in the API, adding it to the definition. /// </summary> /// <value>The date-time of the creation of the record from the audit fields. Since this might be surfaced in the API, adding it to the definition.</value> [DataMember(Name="dateCreated")] [MetaDataExtension (Description = "The date-time of the creation of the record from the audit fields. Since this might be surfaced in the API, adding it to the definition.")] public DateTime? DateCreated { get; set; } /// <summary> /// Link to the designated Primary Contact for the Inspector to the School Bus Owner organization. /// </summary> /// <value>Link to the designated Primary Contact for the Inspector to the School Bus Owner organization.</value> [DataMember(Name="primaryContact")] [MetaDataExtension (Description = "Link to the designated Primary Contact for the Inspector to the School Bus Owner organization.")] public Contact PrimaryContact { get; set; } /// <summary> /// The District to which this School Bus is affliated. /// </summary> /// <value>The District to which this School Bus is affliated.</value> [DataMember(Name="District")] [MetaDataExtension (Description = "The District to which this School Bus is affliated.")] public District District { get; set; } /// <summary> /// The set of contacts related to the School Bus Owner. /// </summary> /// <value>The set of contacts related to the School Bus Owner.</value> [DataMember(Name="contacts")] [MetaDataExtension (Description = "The set of contacts related to the School Bus Owner.")] public List<Contact> Contacts { get; set; } /// <summary> /// The set of notes about the school bus owner entered by users. /// </summary> /// <value>The set of notes about the school bus owner entered by users.</value> [DataMember(Name="notes")] [MetaDataExtension (Description = "The set of notes about the school bus owner entered by users.")] public List<Note> Notes { get; set; } /// <summary> /// The set of attachments about the school bus owner uploaded by the users. /// </summary> /// <value>The set of attachments about the school bus owner uploaded by the users.</value> [DataMember(Name="attachments")] [MetaDataExtension (Description = "The set of attachments about the school bus owner uploaded by the users.")] public List<Attachment> Attachments { get; set; } /// <summary> /// The history of updates made to the School Bus Owner data. /// </summary> /// <value>The history of updates made to the School Bus Owner data.</value> [DataMember(Name="history")] [MetaDataExtension (Description = "The history of updates made to the School Bus Owner data.")] public List<History> History { get; set; } /// <summary> /// The next inspection date associated with this owner /// </summary> /// <value>The next inspection date associated with this owner</value> [DataMember(Name="nextInspectionDate")] [MetaDataExtension (Description = "The next inspection date associated with this owner")] public DateTime? NextInspectionDate { get; set; } /// <summary> /// The number of buses for which this owner is associated with /// </summary> /// <value>The number of buses for which this owner is associated with</value> [DataMember(Name="numberOfBuses")] [MetaDataExtension (Description = "The number of buses for which this owner is associated with")] public int? NumberOfBuses { get; set; } /// <summary> /// Type Code for the Next InspectionType. Null if there are no next inspections. /// </summary> /// <value>Type Code for the Next InspectionType. Null if there are no next inspections.</value> [DataMember(Name="nextInspectionTypeCode")] [MetaDataExtension (Description = "Type Code for the Next InspectionType. Null if there are no next inspections.")] public string NextInspectionTypeCode { 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 SchoolBusOwnerViewModel {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" DateCreated: ").Append(DateCreated).Append("\n"); sb.Append(" PrimaryContact: ").Append(PrimaryContact).Append("\n"); sb.Append(" District: ").Append(District).Append("\n"); sb.Append(" Contacts: ").Append(Contacts).Append("\n"); sb.Append(" Notes: ").Append(Notes).Append("\n"); sb.Append(" Attachments: ").Append(Attachments).Append("\n"); sb.Append(" History: ").Append(History).Append("\n"); sb.Append(" NextInspectionDate: ").Append(NextInspectionDate).Append("\n"); sb.Append(" NumberOfBuses: ").Append(NumberOfBuses).Append("\n"); sb.Append(" NextInspectionTypeCode: ").Append(NextInspectionTypeCode).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((SchoolBusOwnerViewModel)obj); } /// <summary> /// Returns true if SchoolBusOwnerViewModel instances are equal /// </summary> /// <param name="other">Instance of SchoolBusOwnerViewModel to be compared</param> /// <returns>Boolean</returns> public bool Equals(SchoolBusOwnerViewModel other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Status == other.Status || this.Status != null && this.Status.Equals(other.Status) ) && ( this.DateCreated == other.DateCreated || this.DateCreated != null && this.DateCreated.Equals(other.DateCreated) ) && ( this.PrimaryContact == other.PrimaryContact || this.PrimaryContact != null && this.PrimaryContact.Equals(other.PrimaryContact) ) && ( this.District == other.District || this.District != null && this.District.Equals(other.District) ) && ( this.Contacts == other.Contacts || this.Contacts != null && this.Contacts.SequenceEqual(other.Contacts) ) && ( this.Notes == other.Notes || this.Notes != null && this.Notes.SequenceEqual(other.Notes) ) && ( this.Attachments == other.Attachments || this.Attachments != null && this.Attachments.SequenceEqual(other.Attachments) ) && ( this.History == other.History || this.History != null && this.History.SequenceEqual(other.History) ) && ( this.NextInspectionDate == other.NextInspectionDate || this.NextInspectionDate != null && this.NextInspectionDate.Equals(other.NextInspectionDate) ) && ( this.NumberOfBuses == other.NumberOfBuses || this.NumberOfBuses != null && this.NumberOfBuses.Equals(other.NumberOfBuses) ) && ( this.NextInspectionTypeCode == other.NextInspectionTypeCode || this.NextInspectionTypeCode != null && this.NextInspectionTypeCode.Equals(other.NextInspectionTypeCode) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) { hash = hash * 59 + this.Name.GetHashCode(); } if (this.Status != null) { hash = hash * 59 + this.Status.GetHashCode(); } if (this.DateCreated != null) { hash = hash * 59 + this.DateCreated.GetHashCode(); } if (this.PrimaryContact != null) { hash = hash * 59 + this.PrimaryContact.GetHashCode(); } if (this.District != null) { hash = hash * 59 + this.District.GetHashCode(); } if (this.Contacts != null) { hash = hash * 59 + this.Contacts.GetHashCode(); } if (this.Notes != null) { hash = hash * 59 + this.Notes.GetHashCode(); } if (this.Attachments != null) { hash = hash * 59 + this.Attachments.GetHashCode(); } if (this.History != null) { hash = hash * 59 + this.History.GetHashCode(); } if (this.NextInspectionDate != null) { hash = hash * 59 + this.NextInspectionDate.GetHashCode(); } if (this.NumberOfBuses != null) { hash = hash * 59 + this.NumberOfBuses.GetHashCode(); } if (this.NextInspectionTypeCode != null) { hash = hash * 59 + this.NextInspectionTypeCode.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(SchoolBusOwnerViewModel left, SchoolBusOwnerViewModel right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(SchoolBusOwnerViewModel left, SchoolBusOwnerViewModel right) { return !Equals(left, right); } #endregion Operators } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Text; using System.Web.UI.WebControls; using WebsitePanel.EnterpriseServer; namespace WebsitePanel.Portal { public partial class UsernameControl : WebsitePanelControlBase { public Unit Width { get { return txtName.Width; } set { txtName.Width = value; } } public string ValidationGroup { get { return valRequireUsername.ValidationGroup; } set { valRequireUsername.ValidationGroup = value; valCorrectUsername.ValidationGroup = value; valCorrectMinLength.ValidationGroup = value; } } public bool EditMode { get { return (ViewState["EditMode"] != null) ? (bool)ViewState["EditMode"] : false; } set { ViewState["EditMode"] = value; ToggleControls(); } } public bool RequiredField { get { return (ViewState["RequiredField"] != null) ? (bool)ViewState["RequiredField"] : true; } set { ViewState["RequiredField"] = value; ToggleControls(); } } public string Text { get { return EditMode ? txtName.Text.Trim() : litPrefix.Text + txtName.Text.Trim() + litSuffix.Text; } set { txtName.Text = value; lblName.Text = PortalAntiXSS.Encode(value); } } private UserInfo PolicyUser { get { return (ViewState["PolicyUser"] != null) ? (UserInfo)ViewState["PolicyUser"] : null; } set { ViewState["PolicyUser"] = value; } } private string PolicyValue { get { return (ViewState["PolicyValue"] != null) ? (string)ViewState["PolicyValue"] : null; } set { ViewState["PolicyValue"] = value; } } public void SetPackagePolicy(int packageId, string settingsName, string key) { // load package PackageInfo package = PackagesHelper.GetCachedPackage(packageId); if (package != null) { // init by user SetUserPolicy(package.UserId, settingsName, key); } } public void SetUserPolicy(int userId, string settingsName, string key) { // load user profile UserInfo user = UsersHelper.GetCachedUser(userId); if (user != null) { PolicyUser = user; // load settings UserSettings settings = UsersHelper.GetCachedUserSettings(userId, settingsName); if (settings != null) { string policyValue = settings[key]; if (policyValue != null) PolicyValue = policyValue; } } // toggle controls ToggleControls(); } protected void Page_Load(object sender, EventArgs e) { ToggleControls(); } private void ToggleControls() { // hide/show controls litPrefix.Visible = !EditMode; txtName.Visible = !EditMode; lblName.Visible = EditMode; litSuffix.Visible = !EditMode; valRequireUsername.Enabled = RequiredField && !EditMode; valCorrectUsername.Enabled = !EditMode; valCorrectMinLength.Enabled = !EditMode; if (EditMode) return; // require validator valRequireUsername.ErrorMessage = GetLocalizedString("CantBeBlank.Text"); // disable min length validator valCorrectMinLength.Enabled = false; // username validator string defAllowedRegexp = PanelGlobals.UsernameDefaultAllowedRegExp; string defAllowedText = "a-z&nbsp;&nbsp;A-Z&nbsp;&nbsp;0-9&nbsp;&nbsp;.&nbsp;&nbsp;_"; // parse and enforce policy if (PolicyValue != null) { bool enabled = false; string allowedSymbols = null; int minLength = -1; int maxLength = -1; string prefix = null; string suffix = null; try { // parse settings string[] parts = PolicyValue.Split(';'); enabled = Utils.ParseBool(parts[0], false); allowedSymbols = parts[1]; minLength = Utils.ParseInt(parts[2], -1); maxLength = Utils.ParseInt(parts[3], -1); prefix = parts[4]; suffix = parts[5]; } catch { /* skip */ } // apply policy if (enabled) { // prefix if (!String.IsNullOrEmpty(prefix)) { // substitute vars prefix = Utils.ReplaceStringVariable(prefix, "user_id", PolicyUser.UserId.ToString()); prefix = Utils.ReplaceStringVariable(prefix, "user_name", PolicyUser.Username); // display litPrefix.Text = prefix; // adjust max length maxLength -= prefix.Length; } // suffix if (!String.IsNullOrEmpty(suffix)) { // substitute vars suffix = Utils.ReplaceStringVariable(suffix, "user_id", PolicyUser.UserId.ToString()); suffix = Utils.ReplaceStringVariable(suffix, "user_name", PolicyUser.Username); // display litSuffix.Text = suffix; // adjust max length maxLength -= suffix.Length; } // min length if (minLength > 0) { valCorrectMinLength.Enabled = true; valCorrectMinLength.ValidationExpression = "^.{" + minLength.ToString() + ",}$"; valCorrectMinLength.ErrorMessage = String.Format( GetLocalizedString("MinLength.Text"), minLength); } // max length if (maxLength > 0) txtName.MaxLength = maxLength; // process allowed symbols if (!String.IsNullOrEmpty(allowedSymbols)) { StringBuilder sb = new StringBuilder(defAllowedRegexp); for (int i = 0; i < allowedSymbols.Length; i++) { // Escape characters only if required if (PanelGlobals.MetaCharacters2Escape.IndexOf(allowedSymbols[i]) > -1) sb.Append(@"\").Append(allowedSymbols[i]); else sb.Append(allowedSymbols[i]); // defAllowedText += "&nbsp;&nbsp;" + allowedSymbols[i]; } defAllowedRegexp = sb.ToString(); } } // if(enabled) } // if (PolicyValue != null) valCorrectUsername.ValidationExpression = @"^[" + defAllowedRegexp + @"]*$"; valCorrectUsername.ErrorMessage = String.Format(GetLocalizedString("AllowedSymbols.Text"), defAllowedText); } // ToggleControls() } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Management; using System.Net; using System.Net.NetworkInformation; using X_ToolZ.WMI_Classes; namespace xipconfig { class XNetworkInterface { public readonly Win32_NetworkAdapter xWin32NetworkAdapter; public Win32_NetworkAdapterConfiguration xWin32NetworkAdapterConfiguration { get { return xWin32NetworkAdapter.Win32_NetworkAdapterConfiguration; } } public NetworkInterface xNetworkInterface { get { return xWin32NetworkAdapter.NetworkInterface; } } public MSFT_NetAdapter xMSFTNetAdapter { get { return xWin32NetworkAdapter.MSFT_NetAdapter; } } public XNetworkInterface(Win32_NetworkAdapter nic) { xWin32NetworkAdapter = nic; } public int ID { get; set; } public string ShortName { get { return InterfaceType.ToString() + ID; } } public string DeviceID { get { return xWin32NetworkAdapter.DeviceID; } } public string Name { get { if(xWin32NetworkAdapter != null && xWin32NetworkAdapter.Name !=null) return xWin32NetworkAdapter.Description; return string.Empty; } } public string DisplayName { get { if (xWin32NetworkAdapter != null && xWin32NetworkAdapter.NetConnectionID != null) return xWin32NetworkAdapter.NetConnectionID; return string.Empty; } } public bool IsEnabled { get { if (xWin32NetworkAdapter.NetEnabled.HasValue && xWin32NetworkAdapter.NetEnabled.Value) return true; return false; } } public List<IPAddress> IPAddresses { get { var retval = new List<IPAddress>(); if (xWin32NetworkAdapterConfiguration.IPAddress != null) retval.AddRange(xWin32NetworkAdapterConfiguration.IPAddress.Select(IPAddress.Parse)); return retval; } } public IPAddress SubnetMask { get { if (xWin32NetworkAdapterConfiguration.IPSubnet != null) return IPAddress.Parse(xWin32NetworkAdapterConfiguration.IPSubnet[0]); return null; } } public IPAddress Gateway { get { if (xWin32NetworkAdapterConfiguration.DefaultIPGateway != null) return IPAddress.Parse(xWin32NetworkAdapterConfiguration.DefaultIPGateway[0]); return null; } } public string MACAddress { get { return xWin32NetworkAdapter.MACAddress; } } public bool? DHCPEnabled { get { return xWin32NetworkAdapterConfiguration.DHCPEnabled; } } public IPAddress DHCPServer { get { if (xWin32NetworkAdapterConfiguration.DHCPServer != null) return IPAddress.Parse(xWin32NetworkAdapterConfiguration.DHCPServer); return null; } } //public DateTime? DHCPLeaseObtained //{ // get { return xWin32NetworkAdapterConfiguration.DHCPLeaseObtained; } //} //public DateTime? DHCPLeaseExpires //{ // get { return xWin32NetworkAdapterConfiguration.DHCPLeaseExpires; } //} public List<IPAddress> DNSServers { get { var retval = new List<IPAddress>(); if (xWin32NetworkAdapterConfiguration.DNSServerSearchOrder != null && xWin32NetworkAdapterConfiguration.DNSServerSearchOrder.Length > 0) retval.AddRange(xWin32NetworkAdapterConfiguration.DNSServerSearchOrder.Select(IPAddress.Parse)); return retval; } } public string DNSSuffix { get { if (xWin32NetworkAdapterConfiguration.DNSDomainSuffixSearchOrder != null && xWin32NetworkAdapterConfiguration.DNSDomainSuffixSearchOrder.Length > 0) return xWin32NetworkAdapterConfiguration.DNSDomainSuffixSearchOrder.Aggregate((current, next) => current + ", " + next); return string.Empty; } } public bool? NetBIOSEnabled { get { if (xWin32NetworkAdapterConfiguration.TcpipNetbiosOptions.HasValue) { if (xWin32NetworkAdapterConfiguration.TcpipNetbiosOptions == 0 || xWin32NetworkAdapterConfiguration.TcpipNetbiosOptions == 1) return true; if (xWin32NetworkAdapterConfiguration.TcpipNetbiosOptions == 2) return false; } return null; } } public enum XInterfaceType { [Description("Ethernet")] eth = 1, [Description("Wireless80211")] wlan = 2, [Description("Virtual")] virt = 3, [Description("Loopback")] loop = 4, [Description("Tunnel")] tun = 5, [Description("Modem")] mod = 6, [Description("unknown")] unkn = 7 } public XInterfaceType InterfaceType { get { XInterfaceType retval = XInterfaceType.unkn; if (xMSFTNetAdapter != null) { if(!xMSFTNetAdapter.HardwareInterface) return XInterfaceType.virt; switch (xMSFTNetAdapter.NdisPhysicalMedium) { case 1: case 9: case 12: return XInterfaceType.wlan; case 14: case 15: return XInterfaceType.eth; } } if (xNetworkInterface != null) { switch (xNetworkInterface.NetworkInterfaceType) { case NetworkInterfaceType.FastEthernetT: case NetworkInterfaceType.FastEthernetFx: case NetworkInterfaceType.Ethernet3Megabit: case NetworkInterfaceType.GigabitEthernet: case NetworkInterfaceType.Ethernet: return XInterfaceType.eth; case NetworkInterfaceType.Wireless80211: return XInterfaceType.wlan; case NetworkInterfaceType.Loopback: return XInterfaceType.loop; case NetworkInterfaceType.Tunnel: return XInterfaceType.tun; case NetworkInterfaceType.GenericModem: return XInterfaceType.mod; } } if (xWin32NetworkAdapter.AdapterTypeID != null) { switch (xWin32NetworkAdapter.AdapterTypeID) { case 0: return XInterfaceType.eth; case 9: return XInterfaceType.wlan; } } if (!string.IsNullOrWhiteSpace(xWin32NetworkAdapterConfiguration.ServiceName)) { string serviceName = xWin32NetworkAdapterConfiguration.ServiceName.ToLower(); if (serviceName.Contains("tunnel")) return XInterfaceType.tun; } return retval; } } public enum XConnectionStatus { Disconnected = 0, Connecting = 1, Connected = 2, Disconnecting = 3, //[Description("Hardware not present")] HardwareNotPresent = 4, [Description("Disabled")] HardwareNotPresent = 4, [Description("Hardware disabled")] HardwareDisabled = 5, [Description("Hardware malfunction")] HardwareMalfunction = 6, [Description("Media disconnected")] MediaDisconnected = 7, Authenticating = 8, [Description("Authentication succeeded")] AuthenticationSucceeded = 9, [Description("Authentication failed")] AuthenticationFailed = 10, [Description("Invalid address")] InvalidAddress = 11, [Description("Credentials required")] CredentialsRequired = 12, unknown = 13 } public XConnectionStatus ConnectionStatus { get { //ToDo: look for alternatives in MSFTNetAdapter if (xWin32NetworkAdapter.NetConnectionStatus != null) return (XConnectionStatus) xWin32NetworkAdapter.NetConnectionStatus; return XConnectionStatus.unknown; } } public bool Enable() { return PowerDevice(true); } public bool Disable() { return PowerDevice(false); } private bool PowerDevice(bool up) { ManagementObject mo = this.xWin32NetworkAdapter.GetWMIObject(); string todo; if (up) todo = "Enable"; else todo = "Disable"; uint exitCode = (uint)mo.InvokeMethod(todo, null); return exitCode == 0; } public WMIResult EnableDHCP() { ManagementBaseObject retval; using (ManagementObject mo = this.xWin32NetworkAdapterConfiguration.GetWMIObject()) { retval = mo.InvokeMethod("EnableDHCP", null, null); } SetDNS(null); return HandleExitCode((uint) retval["returnValue"]); } public WMIResult EnableStatic(string IPAddress, string SubnetMask) { using (ManagementObject mo = xWin32NetworkAdapterConfiguration.GetWMIObject()) { using (var parameters = mo.GetMethodParameters("EnableStatic")) { parameters["IPAddress"] = new[] {IPAddress}; parameters["SubnetMask"] = new[] {SubnetMask}; ManagementBaseObject retval = mo.InvokeMethod("EnableStatic", parameters, null); return HandleExitCode((uint) retval["returnValue"]); } } } public WMIResult SetGateway(string gateway) { using (ManagementObject mo = xWin32NetworkAdapterConfiguration.GetWMIObject()) { using (var parameters = mo.GetMethodParameters("SetGateways")) { parameters["DefaultIPGateway"] = new[] {gateway}; parameters["GatewayCostMetric"] = new[] {1}; ManagementBaseObject retval = mo.InvokeMethod("SetGateways", parameters, null); return HandleExitCode((uint)retval["returnValue"]); } } } public WMIResult SetDNS(string[] servers) { using (ManagementObject mo = xWin32NetworkAdapterConfiguration.GetWMIObject()) { using (var parameters = mo.GetMethodParameters("SetDNSServerSearchOrder")) { parameters["DNSServerSearchOrder"] = servers; ManagementBaseObject retval = mo.InvokeMethod("SetDNSServerSearchOrder", parameters, null); return HandleExitCode((uint)retval["returnValue"]); } } } public WMIResult HandleExitCode(uint code) { WMIResult retval; if (code == 2147749891) return WMIResult.Access_denied; if (Enum.TryParse(code.ToString(), out retval)) return retval; return WMIResult.Error; } public enum WMIResult { //Successful_completion_no_reboot_required = 0, OK = 0, [Description("Successful but reboot required")] Successful_completion_reboot_required = 1, Method_not_supported_on_this_platform = 64, Unknown_failure = 65, [Description("Invalid SubnetMask")] Invalid_subnet_mask = 66, An_error_occurred_while_processing_an_instance_that_was_returned = 67, [Description("Invalid Input Parameter")] Invalid_input_parameter = 68, More_than_five_gateways_specified = 69, Invalid_IP_address = 70, Invalid_gateway_IP_address = 71, An_error_occurred_while_accessing_the_registry_for_the_requested_information = 72, Invalid_domain_name = 73, Invalid_host_name = 74, No_primary_or_secondary_WINS_server_defined = 75, Invalid_file = 76, Invalid_system_path = 77, File_copy_failed = 78, Invalid_security_parameter = 79, Unable_to_configure_TCPIP_service = 80, Unable_to_configure_DHCP_service = 81, Unable_to_renew_DHCP_lease = 82, Unable_to_release_DHCP_lease = 83, IP_not_enabled_on_adapter = 84, IPX_not_enabled_on_adapter = 85, Frame_or_network_number_bounds_error = 86, Invalid_frame_type = 87, Invalid_network_number = 88, Duplicate_network_number = 89, Parameter_out_of_bounds = 90, [Description("Access Denied")] Access_denied = 91, Out_of_memory = 92, Already_exists = 93, Path_file_or_object_not_found = 94, Unable_to_notify_service = 95, Unable_to_notify_DNS_service = 96, Interface_not_configurable = 97, Not_all_DHCP_leases_could_be_released_or_renewed = 98, DHCP_not_enabled_on_the_adapter = 100, Error } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Xunit; namespace NuGet.Test { public class XmlExtensionsTest { [Fact] public void MergingWithSameTagDifferentAttributesWithNoConflictsMergesAttributes() { // Arrange XElement a = XElement.Parse(@"<foo><bar a=""aValue"" /></foo>"); XElement b = XElement.Parse(@"<foo><bar b=""bValue"" /></foo>"); // Act var result = a.MergeWith(b); // Assert Assert.Equal(1, result.Elements("bar").Count()); XElement barElement = result.Element("bar"); Assert.NotNull(barElement); Assert.Equal(2, barElement.Attributes().Count()); AssertAttributeValue(barElement, "a", "aValue"); AssertAttributeValue(barElement, "b", "bValue"); } [Fact] public void MergingWithNodeActions() { // Arrange XElement a = XElement.Parse(@"<foo><baz /></foo>"); XElement b = XElement.Parse(@"<foo><bar /></foo>"); // Act var result = a.MergeWith(b, new Dictionary<XName, Action<XElement, XElement>> { { "bar", (parent, element) => parent.AddFirst(element) } }); // Assert var elements = result.Elements().ToList(); Assert.Equal(2, elements.Count); Assert.Equal("bar", elements[0].Name); Assert.Equal("baz", elements[1].Name); } [Fact] public void MergingWithoutInsertionMappingsAddsToEnd() { // Arrange XElement a = XElement.Parse(@"<foo><baz /></foo>"); XElement b = XElement.Parse(@"<foo><bar /></foo>"); // Act var result = a.MergeWith(b); // Assert var elements = result.Elements().ToList(); Assert.Equal(2, elements.Count); Assert.Equal("baz", elements[0].Name); Assert.Equal("bar", elements[1].Name); } [Fact] public void MergingElementsWithMultipleSameAttributeNamesAndValuesDoesntDuplicateEntries() { // Act XElement a = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); XElement b = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); // Act var result = a.MergeWith(b); // Assert var elements = result.Elements("test").ToList(); Assert.Equal(2, elements.Count); AssertAttributeValue(elements[0], "name", "one"); AssertAttributeValue(elements[0], "value", "foo"); AssertAttributeValue(elements[1], "name", "two"); AssertAttributeValue(elements[1], "value", "bar"); } [Fact] public void MergingElementsMergeComments() { // Act XElement a = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <special> </special> <!-- old comment --> </tests>"); XElement b = XElement.Parse(@"<tests> <!-- this is a comment --> <test name=""one"" value=""foo""> <!-- this is a comment inside element --> <child> <!-- this is a nested comment --> </child> <!-- comment before new element --> <!-- second comment before new element --> <rock /> </test> <!-- comment at the end --> </tests>"); // Act var result = a.MergeWith(b).ToString(); // Assert Assert.Equal(@"<tests> <!-- this is a comment --> <test name=""one"" value=""foo""> <!-- this is a comment inside element --> <child> <!-- this is a nested comment --> </child> <!-- comment before new element --> <!-- second comment before new element --> <rock /> </test> <special></special> <!-- old comment --> <!-- comment at the end --> </tests>", result); } [Fact] public void MergingElementsMergeCommentsWhenThereIsNoChildElement() { // Act XElement a = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> </tests>"); XElement b = XElement.Parse(@"<tests> <!-- this file contains only comment hahaha, you like that? --> <!-- dark knight rises --> </tests>"); // Act var result = a.MergeWith(b).ToString(); // Assert Assert.Equal(@"<tests> <test name=""one"" value=""foo"" /> <!-- this file contains only comment hahaha, you like that? --> <!-- dark knight rises --> </tests>", result); } [Fact] public void MergingElementsWithMultipleEntiresAddsEntryIfNotExists() { // Act XElement a = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); XElement b = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> <test name=""three"" value=""baz"" /> </tests>"); // Act var result = a.MergeWith(b); // Assert var elements = result.Elements("test").ToList(); Assert.Equal(3, elements.Count); AssertAttributeValue(elements[0], "name", "one"); AssertAttributeValue(elements[0], "value", "foo"); AssertAttributeValue(elements[1], "name", "two"); AssertAttributeValue(elements[1], "value", "bar"); AssertAttributeValue(elements[2], "name", "three"); AssertAttributeValue(elements[2], "value", "baz"); } [Fact] public void MergingTagWithConflictsAddsTag() { // Arrange XElement a = XElement.Parse(@"<connectionStrings><add name=""sqlce"" connectionString=""|DataDirectory|\foo.sdf"" /></connectionStrings>"); XElement b = XElement.Parse(@"<connectionStrings><add name=""sqlserver"" connectionString=""foo.bar"" /></connectionStrings>"); // Act var result = a.MergeWith(b); // Assert var elements = result.Elements("add").ToList(); Assert.Equal(2, elements.Count); AssertAttributeValue(elements[0], "name", "sqlce"); AssertAttributeValue(elements[0], "connectionString", @"|DataDirectory|\foo.sdf"); AssertAttributeValue(elements[1], "name", "sqlserver"); AssertAttributeValue(elements[1], "connectionString", "foo.bar"); } [Fact] public void ExceptWithTagsNoConflicts() { // Arrange XElement a = XElement.Parse(@"<foo><bar b=""2"" /></foo>"); XElement b = XElement.Parse(@"<foo><bar a=""1"" b=""2"" /></foo>"); // Act var result = a.Except(b); // Assert Assert.Equal(0, result.Elements("bar").Count()); } [Fact] public void ExceptWithTagsWithConflicts() { // Arrange XElement a = XElement.Parse(@"<foo><bar b=""2"" a=""g"" /></foo>"); XElement b = XElement.Parse(@"<foo><bar a=""1"" b=""2"" /></foo>"); // Act var result = a.Except(b); // Assert Assert.Equal(1, result.Elements("bar").Count()); XElement barElement = result.Element("bar"); Assert.NotNull(barElement); Assert.Equal(2, barElement.Attributes().Count()); AssertAttributeValue(barElement, "a", "g"); AssertAttributeValue(barElement, "b", "2"); } [Fact] public void ExceptRemoveComments() { // Act XElement a = XElement.Parse(@"<tests> <test name=""One"" value=""foo"" /> <test name=""two"" value=""bar"" /> <!-- comment --> </tests>"); XElement b = XElement.Parse(@"<tests> <!-- comment --> <test name=""two"" value=""bar"" /> </tests>"); // Act var result = a.Except(b); // Assert Assert.Equal(@"<tests> <test name=""One"" value=""foo"" /> </tests>", result.ToString()); } [Fact] public void ExceptDoNotRemoveCommentIfCommentsDoNotMatch() { // Act XElement a = XElement.Parse(@"<tests> <test name=""One"" value=""foo"" /> <test name=""two"" value=""bar"" /> <!-- this is a comment --> </tests>"); XElement b = XElement.Parse(@"<tests> <!-- comment --> <test name=""two"" value=""bar"" /> </tests>"); // Act var result = a.Except(b); // Assert Assert.Equal(@"<tests> <test name=""One"" value=""foo"" /> <!-- this is a comment --> </tests>", result.ToString()); } [Fact] public void ExceptWithSimilarTagsRemovesTagsThatChanged() { // Act XElement a = XElement.Parse(@"<tests> <test name=""One"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); XElement b = XElement.Parse(@"<tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests>"); // Act var result = a.Except(b); // Assert Assert.Equal(@"<tests> <test name=""One"" value=""foo"" /> </tests>", result.ToString()); } [Fact] public void ExceptWithSimilarTagsRemovesTagsThatWereReordered() { // Act XElement a = XElement.Parse(@" <configuration> <tests> <test name=""one"" value=""foo"" /> <test name=""two"" value=""bar"" /> </tests> </configuration>"); XElement b = XElement.Parse(@" <configuration> <tests> <test name=""two"" value=""bar"" /> <test name=""one"" value=""foo"" /> </tests> </configuration>"); // Act var result = a.Except(b); // Assert Assert.Equal("<configuration />", result.ToString()); } [Fact] public void AddWithIndentWorksForSelfEnclosedElement() { // Arrange const string xml = @"<root> <container /> </root>"; XElement root = XElement.Parse(xml, LoadOptions.PreserveWhitespace); XElement container = root.Elements().First(); XElement content = XElement.Parse("<a><b>text</b><c/></a>"); // Act container.AddIndented(content); // Assert Assert.Equal(@"<root> <container> <a> <b>text</b> <c /> </a> </container> </root>", root.ToString()); } [Fact] public void AddWithIndentWorksForEmptyElement() { // Arrange const string xml = @"<root> <container> </container> </root>"; XElement root = XElement.Parse(xml, LoadOptions.PreserveWhitespace); XElement container = root.Elements().First(); XElement content = XElement.Parse("<a><b>text</b><c/></a>"); // Act container.AddIndented(content); // Assert Assert.Equal(@"<root> <container> <a> <b>text</b> <c /> </a> </container> </root>", root.ToString()); } [Fact] public void AddWithIndentWorksForElementWithChildren() { // Arrange const string xml = @"<root> <container> <child /> </container> </root>"; XElement root = XElement.Parse(xml, LoadOptions.PreserveWhitespace); XElement container = root.Elements().First(); XElement content = XElement.Parse("<a><b>text</b><c/></a>"); // Act container.AddIndented(content); // Assert Assert.Equal(@"<root> <container> <child /> <a> <b>text</b> <c /> </a> </container> </root>", root.ToString()); } [Fact] public void AddWithIndentUsesTabs() { // Arrange string xml = @"<root> <container> <child /> </container> </root>".Replace(" ", "\t"); XElement root = XElement.Parse(xml, LoadOptions.PreserveWhitespace); XElement container = root.Elements().First(); XElement content = XElement.Parse("<a><b>text</b><c/></a>"); // Act container.AddIndented(content); // Assert Assert.Equal(@"<root> <container> <child /> <a> <b>text</b> <c /> </a> </container> </root>".Replace(" ", "\t"), root.ToString()); } private static void AssertAttributeValue(XElement element, string attributeName, string expectedAttributeValue) { XAttribute attr = element.Attribute(attributeName); Assert.NotNull(attr); Assert.Equal(expectedAttributeValue, attr.Value); } } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 2.3.1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// PrivateIndividualName /// </summary> [DataContract] public partial class PrivateIndividualName : IEquatable<PrivateIndividualName>, IValidatableObject { /// <summary> /// Gets or Sets Gender /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum GenderEnum { /// <summary> /// Enum Male for "Male" /// </summary> [EnumMember(Value = "Male")] Male, /// <summary> /// Enum Female for "Female" /// </summary> [EnumMember(Value = "Female")] Female, /// <summary> /// Enum NotSpecified for "Not Specified" /// </summary> [EnumMember(Value = "Not Specified")] NotSpecified } /// <summary> /// Gets or Sets Gender /// </summary> [DataMember(Name="gender", EmitDefaultValue=false)] public GenderEnum? Gender { get; set; } /// <summary> /// Initializes a new instance of the <see cref="PrivateIndividualName" /> class. /// </summary> [JsonConstructorAttribute] protected PrivateIndividualName() { } /// <summary> /// Initializes a new instance of the <see cref="PrivateIndividualName" /> class. /// </summary> /// <param name="Forename">Forename (required).</param> /// <param name="MiddleName">MiddleName.</param> /// <param name="Surname">Surname (required).</param> /// <param name="Dob">Dob (required).</param> /// <param name="Gender">Gender.</param> /// <param name="PhoneNumber">PhoneNumber (required).</param> /// <param name="Address">Address (required).</param> public PrivateIndividualName(string Forename = default(string), string MiddleName = default(string), string Surname = default(string), string Dob = default(string), GenderEnum? Gender = default(GenderEnum?), string PhoneNumber = default(string), string Address = default(string)) { // to ensure "Forename" is required (not null) if (Forename == null) { throw new InvalidDataException("Forename is a required property for PrivateIndividualName and cannot be null"); } else { this.Forename = Forename; } // to ensure "Surname" is required (not null) if (Surname == null) { throw new InvalidDataException("Surname is a required property for PrivateIndividualName and cannot be null"); } else { this.Surname = Surname; } // to ensure "Dob" is required (not null) if (Dob == null) { throw new InvalidDataException("Dob is a required property for PrivateIndividualName and cannot be null"); } else { this.Dob = Dob; } // to ensure "PhoneNumber" is required (not null) if (PhoneNumber == null) { throw new InvalidDataException("PhoneNumber is a required property for PrivateIndividualName and cannot be null"); } else { this.PhoneNumber = PhoneNumber; } // to ensure "Address" is required (not null) if (Address == null) { throw new InvalidDataException("Address is a required property for PrivateIndividualName and cannot be null"); } else { this.Address = Address; } this.MiddleName = MiddleName; this.Gender = Gender; } /// <summary> /// Gets or Sets Forename /// </summary> [DataMember(Name="forename", EmitDefaultValue=false)] public string Forename { get; set; } /// <summary> /// Gets or Sets MiddleName /// </summary> [DataMember(Name="middle_name", EmitDefaultValue=false)] public string MiddleName { get; set; } /// <summary> /// Gets or Sets Surname /// </summary> [DataMember(Name="surname", EmitDefaultValue=false)] public string Surname { get; set; } /// <summary> /// Gets or Sets Dob /// </summary> [DataMember(Name="dob", EmitDefaultValue=false)] public string Dob { get; set; } /// <summary> /// Gets or Sets PhoneNumber /// </summary> [DataMember(Name="phone_number", EmitDefaultValue=false)] public string PhoneNumber { get; set; } /// <summary> /// Gets or Sets Address /// </summary> [DataMember(Name="address", EmitDefaultValue=false)] public string Address { 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 PrivateIndividualName {\n"); sb.Append(" Forename: ").Append(Forename).Append("\n"); sb.Append(" MiddleName: ").Append(MiddleName).Append("\n"); sb.Append(" Surname: ").Append(Surname).Append("\n"); sb.Append(" Dob: ").Append(Dob).Append("\n"); sb.Append(" Gender: ").Append(Gender).Append("\n"); sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); sb.Append(" Address: ").Append(Address).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as PrivateIndividualName); } /// <summary> /// Returns true if PrivateIndividualName instances are equal /// </summary> /// <param name="other">Instance of PrivateIndividualName to be compared</param> /// <returns>Boolean</returns> public bool Equals(PrivateIndividualName other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Forename == other.Forename || this.Forename != null && this.Forename.Equals(other.Forename) ) && ( this.MiddleName == other.MiddleName || this.MiddleName != null && this.MiddleName.Equals(other.MiddleName) ) && ( this.Surname == other.Surname || this.Surname != null && this.Surname.Equals(other.Surname) ) && ( this.Dob == other.Dob || this.Dob != null && this.Dob.Equals(other.Dob) ) && ( this.Gender == other.Gender || this.Gender != null && this.Gender.Equals(other.Gender) ) && ( this.PhoneNumber == other.PhoneNumber || this.PhoneNumber != null && this.PhoneNumber.Equals(other.PhoneNumber) ) && ( this.Address == other.Address || this.Address != null && this.Address.Equals(other.Address) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Forename != null) hash = hash * 59 + this.Forename.GetHashCode(); if (this.MiddleName != null) hash = hash * 59 + this.MiddleName.GetHashCode(); if (this.Surname != null) hash = hash * 59 + this.Surname.GetHashCode(); if (this.Dob != null) hash = hash * 59 + this.Dob.GetHashCode(); if (this.Gender != null) hash = hash * 59 + this.Gender.GetHashCode(); if (this.PhoneNumber != null) hash = hash * 59 + this.PhoneNumber.GetHashCode(); if (this.Address != null) hash = hash * 59 + this.Address.GetHashCode(); return hash; } } /// <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) { // Forename (string) pattern Regex regexForename = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant); if (false == regexForename.Match(this.Forename).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Forename, must match a pattern of " + regexForename, new [] { "Forename" }); } // MiddleName (string) pattern Regex regexMiddleName = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant); if (false == regexMiddleName.Match(this.MiddleName).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for MiddleName, must match a pattern of " + regexMiddleName, new [] { "MiddleName" }); } // Surname (string) pattern Regex regexSurname = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant); if (false == regexSurname.Match(this.Surname).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Surname, must match a pattern of " + regexSurname, new [] { "Surname" }); } // Dob (string) pattern Regex regexDob = new Regex(@"^(0[1-9]|[12][0-9]|3[01])[\/\\-](0[1-9]|1[012])[\/\\-]\\d{4}$", RegexOptions.CultureInvariant); if (false == regexDob.Match(this.Dob).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Dob, must match a pattern of " + regexDob, new [] { "Dob" }); } // PhoneNumber (string) pattern Regex regexPhoneNumber = new Regex(@"^(07[\\d]{9})$", RegexOptions.CultureInvariant); if (false == regexPhoneNumber.Match(this.PhoneNumber).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PhoneNumber, must match a pattern of " + regexPhoneNumber, new [] { "PhoneNumber" }); } // Address (string) pattern Regex regexAddress = new Regex(@"[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9](?:A-Z-245|[^CIKMOV]){2}", RegexOptions.CultureInvariant); if (false == regexAddress.Match(this.Address).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Address, must match a pattern of " + regexAddress, new [] { "Address" }); } yield break; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MultiTenantAccountManager.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Linq; using Sharpduino.Constants; using Sharpduino.Exceptions; using Sharpduino.Messages; using Sharpduino.Messages.Send; using Sharpduino.Messages.TwoWay; using Sharpduino.SerialProviders; using UnityEngine; namespace Sharpduino { public class ArduinoLeo : IDisposable { private readonly EasyFirmata firmata; /// <summary> /// Creates a new instance of the ArduinoLeo. This implementation hides a lot /// of the complexity from the end user /// </summary> /// <param name="comPort">The port of the arduino board. All other parameters are supposed to be the default ones.</param> public ArduinoLeo(string comPort) { var provider = new ComPortProvider(comPort); firmata = new EasyFirmata(provider); } /// <summary> /// Property to show that the library has been initialized. /// Nothing can happen before we are initialized. /// </summary> public bool IsInitialized { get { return firmata.IsInitialized; } } /// <summary> /// Sets a pin to servo mode with specific min and max pulse and start angle /// </summary> /// <param name="pin">The pin.</param> /// <param name="minPulse">The min pulse.</param> /// <param name="maxPulse">The max pulse.</param> /// <param name="startAngle">The start angle.</param> /// <exception cref="InvalidPinModeException">If the pin doesn't support servo functionality</exception> public void SetServoMode(ArduinoLeoPins pin, int minPulse, int maxPulse, int startAngle) { if (firmata.IsInitialized == false) return; var currentPin = firmata.Pins[(int) pin]; // Throw an exception if the pin doesn't have this capability if (!currentPin.Capabilities.Keys.Contains(PinModes.Servo)) throw new InvalidPinModeException(PinModes.Servo,currentPin.Capabilities.Keys.ToList()); // Configure the servo mode firmata.SendMessage(new ServoConfigMessage() { Pin = (byte) pin, Angle = startAngle,MinPulse = minPulse, MaxPulse = maxPulse}); currentPin.CurrentMode = PinModes.Servo; currentPin.CurrentValue = startAngle; } public void pinMode(ArduinoLeoPins pin, PinModes mode) { if ( firmata.IsInitialized == false ) return; // Throw an exception if the pin doesn't have this capability if (!firmata.Pins[(int)pin].Capabilities.Keys.Contains(mode)) throw new InvalidPinModeException(PinModes.Servo, firmata.Pins[(int)pin].Capabilities.Keys.ToList()); switch (mode) { case PinModes.I2C: // TODO : Special case for I2C message... throw new NotImplementedException(); case PinModes.Servo: // Special case for servo message... firmata.SendMessage(new ServoConfigMessage() { Pin = (byte)pin }); break; default: firmata.SendMessage(new PinModeMessage { Mode = mode, Pin = (byte)pin }); break; } // TODO : see if we need this or the next way //firmata.Pins[(byte) pin].CurrentMode = mode; // Update the pin state firmata.SendMessage(new PinStateQueryMessage(){Pin = (byte) pin}); } public int digitalRead(ArduinoLeoPins pin) { if (firmata.IsInitialized == false) return -1; // TODO : Decide on whether this should throw an exception if ( firmata.Pins[(int) pin].CurrentMode != PinModes.Input ) return -1; Debug.Log ("query status"); // find the port which this pin belongs to var port = (byte) pin/8; // Update the pin state firmata.SendMessage(new PinStateQueryMessage(){Pin = (byte) pin}); Debug.Log (firmata.Pins [(int)pin].CurrentValue); // get the values for the other pins in this port var values = firmata.GetDigitalPortValues(port); // update the new value for this pin //Debug.Log (values[pin]); return values[(int) pin % 8] ? ArduinoConstants.HIGH : ArduinoConstants.LOW; } public void digitalWrite(ArduinoLeoPins pin, int newValue) { if (firmata.IsInitialized == false) return; // TODO : Decide on whether this should throw an exception if ( firmata.Pins[(int) pin].CurrentMode != PinModes.Output ) return; // find the port which this pin belongs to var port = (byte) pin/8; // get the values for the other pins in this port var previousValues = firmata.GetDigitalPortValues(port); // update the new value for this pin previousValues[(int) pin % 8] = (newValue == ArduinoConstants.HIGH ? true : false); // Send the message to the board firmata.SendMessage(new DigitalMessage(){Port = port, PinStates = previousValues}); // update the new value to the firmata pins list firmata.Pins[(int) pin].CurrentValue = (newValue == ArduinoConstants.HIGH ? 1 : 0); } public void SetPWM(ArduinoLeoPWMPins pin, int newValue) { if (firmata.IsInitialized == false) return; // TODO : Decide on whether this should throw an exception if (firmata.Pins[(int)pin].CurrentMode != PinModes.PWM) return; // Send the message to the board firmata.SendMessage(new AnalogMessage(){Pin = (byte)pin, Value = newValue}); // Update the firmata pins list firmata.Pins[(int) pin].CurrentValue = newValue; } public void SetServo(ArduinoLeoPins pin, int newValue) { if (firmata.IsInitialized == false) return; // TODO : Decide on whether this should throw an exception if (firmata.Pins[(int)pin].CurrentMode != PinModes.Servo) return; firmata.SendMessage(new AnalogMessage(){Pin = (byte)pin,Value = newValue}); // Update the firmata pins list firmata.Pins[(int)pin].CurrentValue = newValue; } public void SetSamplingInterval(int milliseconds) { if ( !firmata.IsInitialized ) return; firmata.SendMessage(new SamplingIntervalMessage(){Interval = milliseconds}); } public Pin GetCurrentPinState(ArduinoLeoPins pin) { if (!firmata.IsInitialized) return null; return firmata.Pins[(int) pin]; } public int analogRead(ArduinoLeoAnalogPins pin) { if (firmata.IsInitialized == false) return -1; // TODO : Decide on whether this should throw an exception if (firmata.AnalogPins[(int)pin].CurrentMode != PinModes.Analog) return -1; return firmata.AnalogPins[(int)pin].CurrentValue; } public void Dispose() { firmata.Dispose(); } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; using Quilt4Net.Core.DataTransfer; using Quilt4Net.Core.Events; using Quilt4Net.Core.Interfaces; namespace Quilt4Net.Core { internal class WebApiClient : IWebApiClient { private readonly object _syncRoot = new object(); private static int _instanceCounter; private readonly IConfiguration _configuration; private Authorization _authorization; public event EventHandler<AuthorizationChangedEventArgs> AuthorizationChangedEvent; internal WebApiClient(IConfiguration configuration) { lock (_syncRoot) { if (_instanceCounter != 0) { if (!configuration.AllowMultipleInstances) { throw new InvalidOperationException("Multiple instances is not allowed. Set configuration setting AllowMultipleInstances to true if you want to use multiple instances of this object."); } } _instanceCounter++; } _configuration = configuration; } public event EventHandler<WebApiRequestEventArgs> WebApiRequestEvent; public event EventHandler<WebApiResponseEventArgs> WebApiResponseEvent; public async Task CreateAsync<T>(string controller, T data) { await Execute(async client => { await PostAsync<T>(client, $"api/{controller}", data); return true; }); } public async Task<TResult> CreateAsync<T, TResult>(string controller, T data) { return await Execute(async client => { var response = await PostAsync<T>(client, $"api/{controller}", data); return response.Content.ReadAsAsync<TResult>().Result; }); } public async Task<TResult> ReadAsync<TResult>(string controller, string id) { var result = await Execute(async client => { var response = await GetAsync(client, $"api/{controller}/{id}"); return response.Content.ReadAsAsync<TResult>().Result; }); return result; } public async Task<IEnumerable<TResult>> ReadAsync<TResult>(string controller) { var result = await Execute(async client => { var response = await GetAsync(client, $"api/{controller}"); return response.Content.ReadAsAsync<IEnumerable<TResult>>().Result; }); return result; } public async Task UpdateAsync<T>(string controller, string id, T data) { await Execute(async client => { await PutAsync(client, $"api/{controller}/{id}", data); return true; }); } public async Task DeleteAsync(string controller, string id) { await Execute(async client => { await DeleteAsync(client, $"api/{controller}/{id}"); return true; }); } public async Task ExecuteCommandAsync<T>(string controller, string action, T data) { await Execute(async client => { await PostAsync(client, $"api/{controller}/{action}", data); return true; }); } public async Task<TResult> ExecuteQueryAsync<T, TResult>(string controller) { var result = await Execute(async client => { var response = await GetAsync(client, $"api/{controller}"); return response.Content.ReadAsAsync<TResult>().Result; }); return result; } public async Task<TResult> ExecuteQueryAsync<T, TResult>(string controller, string id) { return await ExecuteQueryAsync<T, TResult>(controller + "/" + id); } ////public async Task<TResult> ExecuteQueryAsync<T, TResult>(string controller, IDictionary<string, string> parameters) //public async Task<TResult> ExecuteQueryAsync<T, TResult>(string controller, T data) //{ // var info = typeof(T).GetRuntimeProperties(); // var param = string.Empty; // var sign = "?"; // foreach (var propertyInfo in info) // { // param += sign + propertyInfo.Name + "=" + propertyInfo.GetValue(data); // sign = "&"; // } // var result = await Execute(async client => // { // var response = await GetAsync(client, $"api/{controller}{param}"); // return response.Content.ReadAsAsync<TResult>().Result; // }); // return result; //} public async Task<TResult> PostQueryAsync<TResult>(string controller, string action, FormUrlEncodedContent cnt) { var result = await Execute(async client => { var response = await PostAsync(client, $"api/{controller}/{action}", cnt); return response.Content.ReadAsAsync<TResult>().Result; }); return result; } public async Task<TResult> PostQueryAsync<T, TResult>(string controller, string action, T data) { var result = await Execute(async client => { var response = await PostAsync(client, $"api/{controller}/{action}", data); return response.Content.ReadAsAsync<TResult>().Result; }); return result; } private async Task<HttpResponseMessage> PostAsync<T>(HttpClient client, string requestUri, T data) { WebApiRequestEventArgs request = null; try { var jsonFormatter = new JsonMediaTypeFormatter(); var content = new ObjectContent<T>(data, jsonFormatter); request = new WebApiRequestEventArgs(client.BaseAddress, requestUri, OperationType.Post, JsonConvert.SerializeObject(data)); OnWebApiRequestEvent(request); var response = Task.Run(() => { try { return client.PostAsync(requestUri, content); } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.Message); throw; } }); if (!response.Wait(client.Timeout)) { throw new TimeoutException(); } if (!response.Result.IsSuccessStatusCode) { throw await new ExpectedIssues(_configuration).GetExceptionFromResponse(response.Result); } var contentData = response.Result.Content.ReadAsStringAsync().Result; OnWebApiResponseEvent(new WebApiResponseEventArgs(request, response.Result, contentData)); return response.Result; } catch (Exception exception) { OnWebApiResponseEvent(new WebApiResponseEventArgs(request, exception)); throw; } } private async Task<HttpResponseMessage> GetAsync(HttpClient client, string requestUri) { WebApiRequestEventArgs request = null; try { request = new WebApiRequestEventArgs(client.BaseAddress, requestUri, OperationType.Get); OnWebApiRequestEvent(request); var response = await client.GetAsync(requestUri); if (!response.IsSuccessStatusCode) { throw await new ExpectedIssues(_configuration).GetExceptionFromResponse(response); } var contentData = response.Content.ReadAsStringAsync().Result; OnWebApiResponseEvent(new WebApiResponseEventArgs(request, response, contentData)); return response; } catch (Exception exception) { OnWebApiResponseEvent(new WebApiResponseEventArgs(request, exception)); throw; } } private async Task PutAsync<T>(HttpClient client, string requestUri, T data) { WebApiRequestEventArgs request = null; try { var jsonFormatter = new JsonMediaTypeFormatter(); var content = new ObjectContent<T>(data, jsonFormatter); request = new WebApiRequestEventArgs(client.BaseAddress, requestUri, OperationType.Put, JsonConvert.SerializeObject(data)); OnWebApiRequestEvent(request); var response = await client.PutAsync(requestUri, content); if (!response.IsSuccessStatusCode) { throw await new ExpectedIssues(_configuration).GetExceptionFromResponse(response); } OnWebApiResponseEvent(new WebApiResponseEventArgs(request, response)); } catch (Exception exception) { OnWebApiResponseEvent(new WebApiResponseEventArgs(request, exception)); throw; } } private async Task DeleteAsync(HttpClient client, string requestUri) { WebApiRequestEventArgs request = null; try { request = new WebApiRequestEventArgs(client.BaseAddress, requestUri, OperationType.Delete); OnWebApiRequestEvent(request); var response = await client.DeleteAsync(requestUri); if (!response.IsSuccessStatusCode) { throw await new ExpectedIssues(_configuration).GetExceptionFromResponse(response); } OnWebApiResponseEvent(new WebApiResponseEventArgs(request, response)); } catch (Exception exception) { OnWebApiResponseEvent(new WebApiResponseEventArgs(request, exception)); throw; } } public void SetAuthorization(string userName, string tokenType, string accessToken) { _authorization = string.IsNullOrEmpty(accessToken) ? null : new Authorization(tokenType, accessToken); OnAuthorizationChangedEvent(new AuthorizationChangedEventArgs(userName, _authorization)); } public bool IsAuthorized => _authorization != null; private async Task<T> Execute<T>(Func<HttpClient, Task<T>> action) { using (var client = GetHttpClient()) { try { var response = await action(client); return response; } catch (TaskCanceledException exception) { throw new ExpectedIssues(_configuration).GetException(ExpectedIssues.CallTerminatedByServer, exception); } } } private HttpClient GetHttpClient() { var client = new HttpClient { BaseAddress = new Uri(_configuration.Target.Location) }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.Timeout = _configuration.Target.Timeout; //TODO: This is where the hash is supposed to be calculated for the message, so that the server can verify that the origin is correct. if (_authorization != null) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(_authorization.TokenType, _authorization.AccessToken); } return client; } protected virtual void OnAuthorizationChangedEvent(AuthorizationChangedEventArgs e) { AuthorizationChangedEvent?.Invoke(this, e); } protected virtual void OnWebApiRequestEvent(WebApiRequestEventArgs e) { WebApiRequestEvent?.Invoke(this, e); } protected virtual void OnWebApiResponseEvent(WebApiResponseEventArgs e) { WebApiResponseEvent?.Invoke(this, e); } } }
namespace StockSharp.Messages { using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Ecng.Common; using Ecng.Serialization; using StockSharp.Localization; /// <summary> /// Withdraw types. /// </summary> public enum WithdrawTypes { /// <summary> /// Cryptocurrency. /// </summary> [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CryptocurrencyKey)] Crypto, /// <summary> /// Bank wire. /// </summary> [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BankWireKey)] BankWire, /// <summary> /// Bank card. /// </summary> [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BankCardKey)] BankCard, } /// <summary> /// Bank details. /// </summary> [Serializable] [System.Runtime.Serialization.DataContract] [TypeConverter(typeof(ExpandableObjectConverter))] public class BankDetails : IPersistable { /// <summary> /// Bank account. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.AccountKey, Description = LocalizedStrings.BankAccountKey, Order = 0)] public string Account { get; set; } /// <summary> /// Bank account name. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.AccountNameKey, Description = LocalizedStrings.BankAccountNameKey, Order = 1)] public string AccountName { get; set; } /// <summary> /// Name. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.NameKey, Description = LocalizedStrings.NameKey + LocalizedStrings.Dot, Order = 2)] public string Name { get; set; } /// <summary> /// Address. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.AddressKey, Description = LocalizedStrings.AddressKey + LocalizedStrings.Dot, Order = 3)] public string Address { get; set; } /// <summary> /// Country. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CountryKey, Description = LocalizedStrings.CountryKey + LocalizedStrings.Dot, Order = 4)] public string Country { get; set; } /// <summary> /// City. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CityKey, Description = LocalizedStrings.CityKey + LocalizedStrings.Dot, Order = 5)] public string City { get; set; } /// <summary> /// Bank SWIFT. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.SwiftKey, Description = LocalizedStrings.BankSwiftKey, Order = 6)] public string Swift { get; set; } /// <summary> /// Bank BIC. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BicKey, Description = LocalizedStrings.BankBicKey, Order = 7)] public string Bic { get; set; } /// <summary> /// IBAN. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.IbanKey, Description = LocalizedStrings.IbanKey + LocalizedStrings.Dot, Order = 8)] public string Iban { get; set; } /// <summary> /// Postal code. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.PostalCodeKey, Description = LocalizedStrings.PostalCodeKey + LocalizedStrings.Dot, Order = 8)] public string PostalCode { get; set; } /// <summary> /// Currency. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CurrencyKey, Description = LocalizedStrings.CurrencyKey + LocalizedStrings.Dot, Order = 9)] public CurrencyTypes Currency { get; set; } = CurrencyTypes.BTC; /// <summary> /// Load settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Load(SettingsStorage storage) { Account = storage.GetValue<string>(nameof(Account)); AccountName = storage.GetValue<string>(nameof(AccountName)); Name = storage.GetValue<string>(nameof(Name)); Address = storage.GetValue<string>(nameof(Address)); Country = storage.GetValue<string>(nameof(Country)); City = storage.GetValue<string>(nameof(City)); Bic = storage.GetValue<string>(nameof(Bic)); Swift = storage.GetValue<string>(nameof(Swift)); Iban = storage.GetValue<string>(nameof(Iban)); PostalCode = storage.GetValue<string>(nameof(PostalCode)); Currency = storage.GetValue<CurrencyTypes>(nameof(Currency)); } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Save(SettingsStorage storage) { storage.SetValue(nameof(Account), Account); storage.SetValue(nameof(AccountName), AccountName); storage.SetValue(nameof(Name), Name); storage.SetValue(nameof(Address), Address); storage.SetValue(nameof(Country), Country); storage.SetValue(nameof(City), City); storage.SetValue(nameof(Bic), Bic); storage.SetValue(nameof(Swift), Swift); storage.SetValue(nameof(Iban), Iban); storage.SetValue(nameof(PostalCode), PostalCode); storage.SetValue(nameof(Currency), Currency); } /// <inheritdoc /> public override string ToString() { return $"Acc={Account}&AccName={AccountName}&Curr={Currency}&Name={Name}&Add={Address}&Cntry={Country}&City={City}&Bic={Bic}&Swift={Swift}&Iban={Iban}&Postal={PostalCode}"; } } /// <summary> /// Withdraw info. /// </summary> [Serializable] [System.Runtime.Serialization.DataContract] [TypeConverter(typeof(ExpandableObjectConverter))] public class WithdrawInfo : IPersistable { /// <summary> /// Withdraw type. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.TypeKey, Description = LocalizedStrings.WithdrawTypeKey, GroupName = LocalizedStrings.WithdrawKey, Order = 0)] public WithdrawTypes Type { get; set; } /// <summary> /// Crypto address. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CryptoAddressKey, Description = LocalizedStrings.CryptoAddressKey + LocalizedStrings.Dot, GroupName = LocalizedStrings.WithdrawKey, Order = 2)] public string CryptoAddress { get; set; } /// <summary> /// Express withdraw. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ExpressKey, Description = LocalizedStrings.ExpressWithdrawKey, GroupName = LocalizedStrings.WithdrawKey, Order = 3)] public bool Express { get; set; } /// <summary> /// Charge fee. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ChargeFeeKey, Description = LocalizedStrings.ChargeFeeKey + LocalizedStrings.Dot, GroupName = LocalizedStrings.WithdrawKey, Order = 3)] public decimal? ChargeFee { get; set; } /// <summary> /// Payment id. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.PaymentIdKey, Description = LocalizedStrings.PaymentIdKey + LocalizedStrings.Dot, GroupName = LocalizedStrings.WithdrawKey, Order = 4)] public string PaymentId { get; set; } /// <summary> /// Bank details. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BankKey, Description = LocalizedStrings.BankDetailsKey, GroupName = LocalizedStrings.BankKey, Order = 50)] public BankDetails BankDetails { get; set; } /// <summary> /// Intermediary bank details. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.IntermediaryBankKey, Description = LocalizedStrings.IntermediaryBankDetailsKey, GroupName = LocalizedStrings.BankKey, Order = 51)] public BankDetails IntermediaryBankDetails { get; set; } /// <summary> /// Company details. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CompanyKey, Description = LocalizedStrings.CompanyDetailsKey, GroupName = LocalizedStrings.BankKey, Order = 7)] public BankDetails CompanyDetails { get; set; } /// <summary> /// Bank card number. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BankCardKey, Description = LocalizedStrings.BankCardNumberKey, GroupName = LocalizedStrings.BankKey, Order = 8)] public string CardNumber { get; set; } /// <summary> /// Comment of bank transaction. /// </summary> [DataMember] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str135Key, Description = LocalizedStrings.BankCommentKey, GroupName = LocalizedStrings.WithdrawKey, Order = 9)] public string Comment { get; set; } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Load(SettingsStorage storage) { Type = storage.GetValue<WithdrawTypes>(nameof(Type)); Express = storage.GetValue<bool>(nameof(Express)); ChargeFee = storage.GetValue<decimal?>(nameof(ChargeFee)); BankDetails = storage.GetValue<SettingsStorage>(nameof(BankDetails))?.Load<BankDetails>(); IntermediaryBankDetails = storage.GetValue<SettingsStorage>(nameof(IntermediaryBankDetails))?.Load<BankDetails>(); CompanyDetails = storage.GetValue<SettingsStorage>(nameof(CompanyDetails))?.Load<BankDetails>(); CardNumber = storage.GetValue<string>(nameof(CardNumber)); PaymentId = storage.GetValue<string>(nameof(PaymentId)); CryptoAddress = storage.GetValue<string>(nameof(CryptoAddress)); Comment = storage.GetValue<string>(nameof(Comment)); } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Save(SettingsStorage storage) { storage.SetValue(nameof(Type), Type); storage.SetValue(nameof(Express), Express); storage.SetValue(nameof(ChargeFee), ChargeFee); storage.SetValue(nameof(BankDetails), BankDetails?.Save()); storage.SetValue(nameof(IntermediaryBankDetails), IntermediaryBankDetails?.Save()); storage.SetValue(nameof(CompanyDetails), CompanyDetails?.Save()); storage.SetValue(nameof(CardNumber), CardNumber); storage.SetValue(nameof(PaymentId), PaymentId); storage.SetValue(nameof(CryptoAddress), CryptoAddress); storage.SetValue(nameof(Comment), Comment); } /// <inheritdoc /> public override string ToString() { return $"Type={Type}&Addr={CryptoAddress}&Id={PaymentId}&Comment={Comment}&Company={CompanyDetails}&Bank={BankDetails}&Fee={ChargeFee}"; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ChallengeResponseDecoder { public const ushort BLOCK_LENGTH = 16; public const ushort TEMPLATE_ID = 8; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private ChallengeResponseDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public ChallengeResponseDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ChallengeResponseDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int CorrelationIdId() { return 1; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 0; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int ClusterSessionIdId() { return 2; } public static int ClusterSessionIdSinceVersion() { return 0; } public static int ClusterSessionIdEncodingOffset() { return 8; } public static int ClusterSessionIdEncodingLength() { return 8; } public static string ClusterSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public long ClusterSessionId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int EncodedCredentialsId() { return 3; } public static int EncodedCredentialsSinceVersion() { return 0; } public static string EncodedCredentialsMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int EncodedCredentialsHeaderLength() { return 4; } public int EncodedCredentialsLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetEncodedCredentials(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetEncodedCredentials(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[ChallengeResponse](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='clusterSessionId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ClusterSessionId="); builder.Append(ClusterSessionId()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='encodedCredentials', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("EncodedCredentials="); builder.Append(EncodedCredentialsLength() + " raw bytes"); Limit(originalLimit); return builder; } } }
using Jint.Runtime; namespace Jint.Native.TypedArray { public sealed class Int8ArrayConstructor : TypedArrayConstructor { internal Int8ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.Int8) { } public TypedArrayInstance Construct(sbyte[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class Uint8ArrayConstructor : TypedArrayConstructor { internal Uint8ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.Uint8) { } public TypedArrayInstance Construct(byte[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class Uint8ClampedArrayConstructor : TypedArrayConstructor { internal Uint8ClampedArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.Uint8C) { } public TypedArrayInstance Construct(byte[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class Int16ArrayConstructor : TypedArrayConstructor { internal Int16ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.Int16) { } public TypedArrayInstance Construct(short[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class Uint16ArrayConstructor : TypedArrayConstructor { internal Uint16ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.Uint16) { } public TypedArrayInstance Construct(ushort[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class Int32ArrayConstructor : TypedArrayConstructor { internal Int32ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.Int32) { } public TypedArrayInstance Construct(int[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class Uint32ArrayConstructor : TypedArrayConstructor { internal Uint32ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.Uint32) { } public TypedArrayInstance Construct(uint[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class Float32ArrayConstructor : TypedArrayConstructor { internal Float32ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.Float32) { } public TypedArrayInstance Construct(float[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class Float64ArrayConstructor : TypedArrayConstructor { internal Float64ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.Float64) { } public TypedArrayInstance Construct(double[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class BigInt64ArrayConstructor : TypedArrayConstructor { internal BigInt64ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.BigInt64) { } public TypedArrayInstance Construct(long[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } public sealed class BigUint64ArrayConstructor : TypedArrayConstructor { internal BigUint64ArrayConstructor( Engine engine, Realm realm, IntrinsicTypedArrayConstructor functionPrototype, IntrinsicTypedArrayPrototype objectPrototype) : base(engine, realm, functionPrototype, objectPrototype, TypedArrayElementType.BigUint64) { } public TypedArrayInstance Construct(ulong[] values) { var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } } }
// <copyright file="HttpWebRequestActivitySource.netfx.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if NETFRAMEWORK using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Trace; namespace OpenTelemetry.Instrumentation.Http.Implementation { /// <summary> /// Hooks into the <see cref="HttpWebRequest"/> class reflectively and writes diagnostic events as requests are processed. /// </summary> /// <remarks> /// Inspired from the System.Diagnostics.DiagnosticSource.HttpHandlerDiagnosticListener class which has some bugs and feature gaps. /// See https://github.com/dotnet/runtime/pull/33732 for details. /// </remarks> internal static class HttpWebRequestActivitySource { public const string ActivitySourceName = "OpenTelemetry.HttpWebRequest"; public const string ActivityName = ActivitySourceName + ".HttpRequestOut"; internal static readonly Func<HttpWebRequest, string, IEnumerable<string>> HttpWebRequestHeaderValuesGetter = (request, name) => request.Headers.GetValues(name); internal static readonly Action<HttpWebRequest, string, string> HttpWebRequestHeaderValuesSetter = (request, name, value) => request.Headers.Add(name, value); internal static HttpWebRequestInstrumentationOptions Options = new HttpWebRequestInstrumentationOptions(); private static readonly Version Version = typeof(HttpWebRequestActivitySource).Assembly.GetName().Version; private static readonly ActivitySource WebRequestActivitySource = new ActivitySource(ActivitySourceName, Version.ToString()); // Fields for reflection private static FieldInfo connectionGroupListField; private static Type connectionGroupType; private static FieldInfo connectionListField; private static Type connectionType; private static FieldInfo writeListField; private static Func<object, IAsyncResult> writeAResultAccessor; private static Func<object, IAsyncResult> readAResultAccessor; // LazyAsyncResult & ContextAwareResult private static Func<object, AsyncCallback> asyncCallbackAccessor; private static Action<object, AsyncCallback> asyncCallbackModifier; private static Func<object, object> asyncStateAccessor; private static Action<object, object> asyncStateModifier; private static Func<object, bool> endCalledAccessor; private static Func<object, object> resultAccessor; private static Func<object, bool> isContextAwareResultChecker; // HttpWebResponse private static Func<object[], HttpWebResponse> httpWebResponseCtor; private static Func<HttpWebResponse, Uri> uriAccessor; private static Func<HttpWebResponse, object> verbAccessor; private static Func<HttpWebResponse, string> mediaTypeAccessor; private static Func<HttpWebResponse, bool> usesProxySemanticsAccessor; private static Func<HttpWebResponse, object> coreResponseDataAccessor; private static Func<HttpWebResponse, bool> isWebSocketResponseAccessor; private static Func<HttpWebResponse, string> connectionGroupNameAccessor; static HttpWebRequestActivitySource() { try { PrepareReflectionObjects(); PerformInjection(); } catch (Exception ex) { // If anything went wrong, just no-op. Write an event so at least we can find out. HttpInstrumentationEventSource.Log.ExceptionInitializingInstrumentation(typeof(HttpWebRequestActivitySource).FullName, ex); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void AddRequestTagsAndInstrumentRequest(HttpWebRequest request, Activity activity) { activity.DisplayName = HttpTagHelper.GetOperationNameForHttpMethod(request.Method); if (activity.IsAllDataRequested) { activity.SetTag(SemanticConventions.AttributeHttpMethod, request.Method); activity.SetTag(SemanticConventions.AttributeHttpHost, HttpTagHelper.GetHostTagValueFromRequestUri(request.RequestUri)); activity.SetTag(SemanticConventions.AttributeHttpUrl, HttpTagHelper.GetUriTagValueFromRequestUri(request.RequestUri)); if (Options.SetHttpFlavor) { activity.SetTag(SemanticConventions.AttributeHttpFlavor, HttpTagHelper.GetFlavorTagValueFromProtocolVersion(request.ProtocolVersion)); } try { Options.Enrich?.Invoke(activity, "OnStartActivity", request); } catch (Exception ex) { HttpInstrumentationEventSource.Log.EnrichmentException(ex); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void AddResponseTags(HttpWebResponse response, Activity activity) { if (activity.IsAllDataRequested) { activity.SetTag(SemanticConventions.AttributeHttpStatusCode, (int)response.StatusCode); activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, (int)response.StatusCode)); try { Options.Enrich?.Invoke(activity, "OnStopActivity", response); } catch (Exception ex) { HttpInstrumentationEventSource.Log.EnrichmentException(ex); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void AddExceptionTags(Exception exception, Activity activity) { if (!activity.IsAllDataRequested) { return; } Status status; if (exception is WebException wexc) { if (wexc.Response is HttpWebResponse response) { activity.SetTag(SemanticConventions.AttributeHttpStatusCode, (int)response.StatusCode); status = SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, (int)response.StatusCode); } else { switch (wexc.Status) { case WebExceptionStatus.Timeout: case WebExceptionStatus.RequestCanceled: status = Status.Error; break; case WebExceptionStatus.SendFailure: case WebExceptionStatus.ConnectFailure: case WebExceptionStatus.SecureChannelFailure: case WebExceptionStatus.TrustFailure: case WebExceptionStatus.ServerProtocolViolation: case WebExceptionStatus.MessageLengthLimitExceeded: status = Status.Error.WithDescription(exception.Message); break; default: status = Status.Error.WithDescription(exception.Message); break; } } } else { status = Status.Error.WithDescription(exception.Message); } activity.SetStatus(status); if (Options.RecordException) { activity.RecordException(exception); } try { Options.Enrich?.Invoke(activity, "OnException", exception); } catch (Exception ex) { HttpInstrumentationEventSource.Log.EnrichmentException(ex); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void InstrumentRequest(HttpWebRequest request, ActivityContext activityContext) => Propagators.DefaultTextMapPropagator.Inject(new PropagationContext(activityContext, Baggage.Current), request, HttpWebRequestHeaderValuesSetter); [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsRequestInstrumented(HttpWebRequest request) => Propagators.DefaultTextMapPropagator.Extract(default, request, HttpWebRequestHeaderValuesGetter) != default; private static void ProcessRequest(HttpWebRequest request) { if (!WebRequestActivitySource.HasListeners() || !Options.EventFilter(request)) { // No subscribers to the ActivitySource or User provider Filter is // filtering this request. // Propagation must still be done in such cases, to allow // downstream services to continue from parent context, if any. // Eg: Parent could be the Asp.Net activity. InstrumentRequest(request, Activity.Current?.Context ?? default); return; } if (IsRequestInstrumented(request)) { // This request was instrumented by previous // ProcessRequest, such is the case with redirect responses where the same request is sent again. return; } var activity = WebRequestActivitySource.StartActivity(ActivityName, ActivityKind.Client); var activityContext = Activity.Current?.Context ?? default; // Propagation must still be done in all cases, to allow // downstream services to continue from parent context, if any. // Eg: Parent could be the Asp.Net activity. InstrumentRequest(request, activityContext); if (activity == null) { // There is a listener but it decided not to sample the current request. return; } IAsyncResult asyncContext = writeAResultAccessor(request); if (asyncContext != null) { // Flow here is for [Begin]GetRequestStream[Async]. AsyncCallbackWrapper callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext)); asyncCallbackModifier(asyncContext, callback.AsyncCallback); } else { // Flow here is for [Begin]GetResponse[Async] without a prior call to [Begin]GetRequestStream[Async]. asyncContext = readAResultAccessor(request); AsyncCallbackWrapper callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext)); asyncCallbackModifier(asyncContext, callback.AsyncCallback); } AddRequestTagsAndInstrumentRequest(request, activity); } private static void HookOrProcessResult(HttpWebRequest request) { IAsyncResult writeAsyncContext = writeAResultAccessor(request); if (writeAsyncContext == null || !(asyncCallbackAccessor(writeAsyncContext)?.Target is AsyncCallbackWrapper writeAsyncContextCallback)) { // If we already hooked into the read result during ProcessRequest or we hooked up after the fact already we don't need to do anything here. return; } // If we got here it means the user called [Begin]GetRequestStream[Async] and we have to hook the read result after the fact. IAsyncResult readAsyncContext = readAResultAccessor(request); if (readAsyncContext == null) { // We're still trying to establish the connection (no read has started). return; } // Clear our saved callback so we know not to process again. asyncCallbackModifier(writeAsyncContext, null); if (endCalledAccessor.Invoke(readAsyncContext) || readAsyncContext.CompletedSynchronously) { // We need to process the result directly because the read callback has already fired. Force a copy because response has likely already been disposed. ProcessResult(readAsyncContext, null, writeAsyncContextCallback.Activity, resultAccessor(readAsyncContext), true); return; } // Hook into the result callback if it hasn't already fired. AsyncCallbackWrapper callback = new AsyncCallbackWrapper(writeAsyncContextCallback.Request, writeAsyncContextCallback.Activity, asyncCallbackAccessor(readAsyncContext)); asyncCallbackModifier(readAsyncContext, callback.AsyncCallback); } private static void ProcessResult(IAsyncResult asyncResult, AsyncCallback asyncCallback, Activity activity, object result, bool forceResponseCopy) { // We could be executing on a different thread now so restore the activity if needed. if (Activity.Current != activity) { Activity.Current = activity; } try { if (result is Exception ex) { AddExceptionTags(ex, activity); } else { HttpWebResponse response = (HttpWebResponse)result; if (forceResponseCopy || (asyncCallback == null && isContextAwareResultChecker(asyncResult))) { // For async calls (where asyncResult is ContextAwareResult)... // If no callback was set assume the user is manually calling BeginGetResponse & EndGetResponse // in which case they could dispose the HttpWebResponse before our listeners have a chance to work with it. // Disposed HttpWebResponse throws when accessing properties, so let's make a copy of the data to ensure that doesn't happen. HttpWebResponse responseCopy = httpWebResponseCtor( new object[] { uriAccessor(response), verbAccessor(response), coreResponseDataAccessor(response), mediaTypeAccessor(response), usesProxySemanticsAccessor(response), DecompressionMethods.None, isWebSocketResponseAccessor(response), connectionGroupNameAccessor(response), }); AddResponseTags(responseCopy, activity); } else { AddResponseTags(response, activity); } } } catch (Exception ex) { HttpInstrumentationEventSource.Log.FailedProcessResult(ex); } activity.Stop(); } private static void PrepareReflectionObjects() { // At any point, if the operation failed, it should just throw. The caller should catch all exceptions and swallow. Type servicePointType = typeof(ServicePoint); Assembly systemNetHttpAssembly = servicePointType.Assembly; connectionGroupListField = servicePointType.GetField("m_ConnectionGroupList", BindingFlags.Instance | BindingFlags.NonPublic); connectionGroupType = systemNetHttpAssembly?.GetType("System.Net.ConnectionGroup"); connectionListField = connectionGroupType?.GetField("m_ConnectionList", BindingFlags.Instance | BindingFlags.NonPublic); connectionType = systemNetHttpAssembly?.GetType("System.Net.Connection"); writeListField = connectionType?.GetField("m_WriteList", BindingFlags.Instance | BindingFlags.NonPublic); writeAResultAccessor = CreateFieldGetter<IAsyncResult>(typeof(HttpWebRequest), "_WriteAResult", BindingFlags.NonPublic | BindingFlags.Instance); readAResultAccessor = CreateFieldGetter<IAsyncResult>(typeof(HttpWebRequest), "_ReadAResult", BindingFlags.NonPublic | BindingFlags.Instance); // Double checking to make sure we have all the pieces initialized if (connectionGroupListField == null || connectionGroupType == null || connectionListField == null || connectionType == null || writeListField == null || writeAResultAccessor == null || readAResultAccessor == null || !PrepareAsyncResultReflectionObjects(systemNetHttpAssembly) || !PrepareHttpWebResponseReflectionObjects(systemNetHttpAssembly)) { // If anything went wrong here, just return false. There is nothing we can do. throw new InvalidOperationException("Unable to initialize all required reflection objects"); } } private static bool PrepareAsyncResultReflectionObjects(Assembly systemNetHttpAssembly) { Type lazyAsyncResultType = systemNetHttpAssembly?.GetType("System.Net.LazyAsyncResult"); if (lazyAsyncResultType != null) { asyncCallbackAccessor = CreateFieldGetter<AsyncCallback>(lazyAsyncResultType, "m_AsyncCallback", BindingFlags.NonPublic | BindingFlags.Instance); asyncCallbackModifier = CreateFieldSetter<AsyncCallback>(lazyAsyncResultType, "m_AsyncCallback", BindingFlags.NonPublic | BindingFlags.Instance); asyncStateAccessor = CreateFieldGetter<object>(lazyAsyncResultType, "m_AsyncState", BindingFlags.NonPublic | BindingFlags.Instance); asyncStateModifier = CreateFieldSetter<object>(lazyAsyncResultType, "m_AsyncState", BindingFlags.NonPublic | BindingFlags.Instance); endCalledAccessor = CreateFieldGetter<bool>(lazyAsyncResultType, "m_EndCalled", BindingFlags.NonPublic | BindingFlags.Instance); resultAccessor = CreateFieldGetter<object>(lazyAsyncResultType, "m_Result", BindingFlags.NonPublic | BindingFlags.Instance); } Type contextAwareResultType = systemNetHttpAssembly?.GetType("System.Net.ContextAwareResult"); if (contextAwareResultType != null) { isContextAwareResultChecker = CreateTypeChecker(contextAwareResultType); } return asyncCallbackAccessor != null && asyncCallbackModifier != null && asyncStateAccessor != null && asyncStateModifier != null && endCalledAccessor != null && resultAccessor != null && isContextAwareResultChecker != null; } private static bool PrepareHttpWebResponseReflectionObjects(Assembly systemNetHttpAssembly) { Type knownHttpVerbType = systemNetHttpAssembly?.GetType("System.Net.KnownHttpVerb"); Type coreResponseData = systemNetHttpAssembly?.GetType("System.Net.CoreResponseData"); if (knownHttpVerbType != null && coreResponseData != null) { var constructorParameterTypes = new Type[] { typeof(Uri), knownHttpVerbType, coreResponseData, typeof(string), typeof(bool), typeof(DecompressionMethods), typeof(bool), typeof(string), }; ConstructorInfo ctor = typeof(HttpWebResponse).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, constructorParameterTypes, null); if (ctor != null) { httpWebResponseCtor = CreateTypeInstance<HttpWebResponse>(ctor); } } uriAccessor = CreateFieldGetter<HttpWebResponse, Uri>("m_Uri", BindingFlags.NonPublic | BindingFlags.Instance); verbAccessor = CreateFieldGetter<HttpWebResponse, object>("m_Verb", BindingFlags.NonPublic | BindingFlags.Instance); mediaTypeAccessor = CreateFieldGetter<HttpWebResponse, string>("m_MediaType", BindingFlags.NonPublic | BindingFlags.Instance); usesProxySemanticsAccessor = CreateFieldGetter<HttpWebResponse, bool>("m_UsesProxySemantics", BindingFlags.NonPublic | BindingFlags.Instance); coreResponseDataAccessor = CreateFieldGetter<HttpWebResponse, object>("m_CoreResponseData", BindingFlags.NonPublic | BindingFlags.Instance); isWebSocketResponseAccessor = CreateFieldGetter<HttpWebResponse, bool>("m_IsWebSocketResponse", BindingFlags.NonPublic | BindingFlags.Instance); connectionGroupNameAccessor = CreateFieldGetter<HttpWebResponse, string>("m_ConnectionGroupName", BindingFlags.NonPublic | BindingFlags.Instance); return httpWebResponseCtor != null && uriAccessor != null && verbAccessor != null && mediaTypeAccessor != null && usesProxySemanticsAccessor != null && coreResponseDataAccessor != null && isWebSocketResponseAccessor != null && connectionGroupNameAccessor != null; } private static void PerformInjection() { FieldInfo servicePointTableField = typeof(ServicePointManager).GetField("s_ServicePointTable", BindingFlags.Static | BindingFlags.NonPublic); if (servicePointTableField == null) { // If anything went wrong here, just return false. There is nothing we can do. throw new InvalidOperationException("Unable to access the ServicePointTable field"); } Hashtable originalTable = servicePointTableField.GetValue(null) as Hashtable; ServicePointHashtable newTable = new ServicePointHashtable(originalTable ?? new Hashtable()); foreach (DictionaryEntry existingServicePoint in originalTable) { HookServicePoint(existingServicePoint.Value); } servicePointTableField.SetValue(null, newTable); } private static void HookServicePoint(object value) { if (value is WeakReference weakRef && weakRef.IsAlive && weakRef.Target is ServicePoint servicePoint) { // Replace the ConnectionGroup hashtable inside this ServicePoint object, // which allows us to intercept each new ConnectionGroup object added under // this ServicePoint. Hashtable originalTable = connectionGroupListField.GetValue(servicePoint) as Hashtable; ConnectionGroupHashtable newTable = new ConnectionGroupHashtable(originalTable ?? new Hashtable()); foreach (DictionaryEntry existingConnectionGroup in originalTable) { HookConnectionGroup(existingConnectionGroup.Value); } connectionGroupListField.SetValue(servicePoint, newTable); } } private static void HookConnectionGroup(object value) { if (connectionGroupType.IsInstanceOfType(value)) { // Replace the Connection arraylist inside this ConnectionGroup object, // which allows us to intercept each new Connection object added under // this ConnectionGroup. ArrayList originalArrayList = connectionListField.GetValue(value) as ArrayList; ConnectionArrayList newArrayList = new ConnectionArrayList(originalArrayList ?? new ArrayList()); foreach (object connection in originalArrayList) { HookConnection(connection); } connectionListField.SetValue(value, newArrayList); } } private static void HookConnection(object value) { if (connectionType.IsInstanceOfType(value)) { // Replace the HttpWebRequest arraylist inside this Connection object, // which allows us to intercept each new HttpWebRequest object added under // this Connection. ArrayList originalArrayList = writeListField.GetValue(value) as ArrayList; HttpWebRequestArrayList newArrayList = new HttpWebRequestArrayList(originalArrayList ?? new ArrayList()); writeListField.SetValue(value, newArrayList); } } private static Func<TClass, TField> CreateFieldGetter<TClass, TField>(string fieldName, BindingFlags flags) where TClass : class { FieldInfo field = typeof(TClass).GetField(fieldName, flags); if (field != null) { string methodName = field.ReflectedType.FullName + ".get_" + field.Name; DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(TClass) }, true); ILGenerator generator = getterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, field); generator.Emit(OpCodes.Ret); return (Func<TClass, TField>)getterMethod.CreateDelegate(typeof(Func<TClass, TField>)); } return null; } /// <summary> /// Creates getter for a field defined in private or internal type /// repesented with classType variable. /// </summary> private static Func<object, TField> CreateFieldGetter<TField>(Type classType, string fieldName, BindingFlags flags) { FieldInfo field = classType.GetField(fieldName, flags); if (field != null) { string methodName = classType.FullName + ".get_" + field.Name; DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(object) }, true); ILGenerator generator = getterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, classType); generator.Emit(OpCodes.Ldfld, field); generator.Emit(OpCodes.Ret); return (Func<object, TField>)getterMethod.CreateDelegate(typeof(Func<object, TField>)); } return null; } /// <summary> /// Creates setter for a field defined in private or internal type /// repesented with classType variable. /// </summary> private static Action<object, TField> CreateFieldSetter<TField>(Type classType, string fieldName, BindingFlags flags) { FieldInfo field = classType.GetField(fieldName, flags); if (field != null) { string methodName = classType.FullName + ".set_" + field.Name; DynamicMethod setterMethod = new DynamicMethod(methodName, null, new[] { typeof(object), typeof(TField) }, true); ILGenerator generator = setterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, classType); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Stfld, field); generator.Emit(OpCodes.Ret); return (Action<object, TField>)setterMethod.CreateDelegate(typeof(Action<object, TField>)); } return null; } /// <summary> /// Creates an "is" method for the private or internal type. /// </summary> private static Func<object, bool> CreateTypeChecker(Type classType) { string methodName = classType.FullName + ".typeCheck"; DynamicMethod setterMethod = new DynamicMethod(methodName, typeof(bool), new[] { typeof(object) }, true); ILGenerator generator = setterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Isinst, classType); generator.Emit(OpCodes.Ldnull); generator.Emit(OpCodes.Cgt_Un); generator.Emit(OpCodes.Ret); return (Func<object, bool>)setterMethod.CreateDelegate(typeof(Func<object, bool>)); } /// <summary> /// Creates an instance of T using a private or internal ctor. /// </summary> private static Func<object[], T> CreateTypeInstance<T>(ConstructorInfo constructorInfo) { Type classType = typeof(T); string methodName = classType.FullName + ".ctor"; DynamicMethod setterMethod = new DynamicMethod(methodName, classType, new Type[] { typeof(object[]) }, true); ILGenerator generator = setterMethod.GetILGenerator(); ParameterInfo[] ctorParams = constructorInfo.GetParameters(); for (int i = 0; i < ctorParams.Length; i++) { generator.Emit(OpCodes.Ldarg_0); switch (i) { case 0: generator.Emit(OpCodes.Ldc_I4_0); break; case 1: generator.Emit(OpCodes.Ldc_I4_1); break; case 2: generator.Emit(OpCodes.Ldc_I4_2); break; case 3: generator.Emit(OpCodes.Ldc_I4_3); break; case 4: generator.Emit(OpCodes.Ldc_I4_4); break; case 5: generator.Emit(OpCodes.Ldc_I4_5); break; case 6: generator.Emit(OpCodes.Ldc_I4_6); break; case 7: generator.Emit(OpCodes.Ldc_I4_7); break; case 8: generator.Emit(OpCodes.Ldc_I4_8); break; default: generator.Emit(OpCodes.Ldc_I4, i); break; } generator.Emit(OpCodes.Ldelem_Ref); Type paramType = ctorParams[i].ParameterType; generator.Emit(paramType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, paramType); } generator.Emit(OpCodes.Newobj, constructorInfo); generator.Emit(OpCodes.Ret); return (Func<object[], T>)setterMethod.CreateDelegate(typeof(Func<object[], T>)); } private class HashtableWrapper : Hashtable, IEnumerable { private readonly Hashtable table; internal HashtableWrapper(Hashtable table) : base() { this.table = table; } public override int Count => this.table.Count; public override bool IsReadOnly => this.table.IsReadOnly; public override bool IsFixedSize => this.table.IsFixedSize; public override bool IsSynchronized => this.table.IsSynchronized; public override object SyncRoot => this.table.SyncRoot; public override ICollection Keys => this.table.Keys; public override ICollection Values => this.table.Values; public override object this[object key] { get => this.table[key]; set => this.table[key] = value; } public override void Add(object key, object value) { this.table.Add(key, value); } public override void Clear() { this.table.Clear(); } public override bool Contains(object key) { return this.table.Contains(key); } public override bool ContainsKey(object key) { return this.table.ContainsKey(key); } public override bool ContainsValue(object key) { return this.table.ContainsValue(key); } public override void CopyTo(Array array, int arrayIndex) { this.table.CopyTo(array, arrayIndex); } public override object Clone() { return new HashtableWrapper((Hashtable)this.table.Clone()); } IEnumerator IEnumerable.GetEnumerator() { return this.table.GetEnumerator(); } public override IDictionaryEnumerator GetEnumerator() { return this.table.GetEnumerator(); } public override void Remove(object key) { this.table.Remove(key); } } /// <summary> /// Helper class used for ServicePointManager.s_ServicePointTable. The goal here is to /// intercept each new ServicePoint object being added to ServicePointManager.s_ServicePointTable /// and replace its ConnectionGroupList hashtable field. /// </summary> private sealed class ServicePointHashtable : HashtableWrapper { public ServicePointHashtable(Hashtable table) : base(table) { } public override object this[object key] { get => base[key]; set { HookServicePoint(value); base[key] = value; } } } /// <summary> /// Helper class used for ServicePoint.m_ConnectionGroupList. The goal here is to /// intercept each new ConnectionGroup object being added to ServicePoint.m_ConnectionGroupList /// and replace its m_ConnectionList arraylist field. /// </summary> private sealed class ConnectionGroupHashtable : HashtableWrapper { public ConnectionGroupHashtable(Hashtable table) : base(table) { } public override object this[object key] { get => base[key]; set { HookConnectionGroup(value); base[key] = value; } } } /// <summary> /// Helper class used to wrap the array list object. This class itself doesn't actually /// have the array elements, but rather access another array list that's given at /// construction time. /// </summary> private class ArrayListWrapper : ArrayList { private ArrayList list; internal ArrayListWrapper(ArrayList list) : base() { this.list = list; } public override int Capacity { get => this.list.Capacity; set => this.list.Capacity = value; } public override int Count => this.list.Count; public override bool IsReadOnly => this.list.IsReadOnly; public override bool IsFixedSize => this.list.IsFixedSize; public override bool IsSynchronized => this.list.IsSynchronized; public override object SyncRoot => this.list.SyncRoot; public override object this[int index] { get => this.list[index]; set => this.list[index] = value; } public override int Add(object value) { return this.list.Add(value); } public override void AddRange(ICollection c) { this.list.AddRange(c); } public override int BinarySearch(object value) { return this.list.BinarySearch(value); } public override int BinarySearch(object value, IComparer comparer) { return this.list.BinarySearch(value, comparer); } public override int BinarySearch(int index, int count, object value, IComparer comparer) { return this.list.BinarySearch(index, count, value, comparer); } public override void Clear() { this.list.Clear(); } public override object Clone() { return new ArrayListWrapper((ArrayList)this.list.Clone()); } public override bool Contains(object item) { return this.list.Contains(item); } public override void CopyTo(Array array) { this.list.CopyTo(array); } public override void CopyTo(Array array, int index) { this.list.CopyTo(array, index); } public override void CopyTo(int index, Array array, int arrayIndex, int count) { this.list.CopyTo(index, array, arrayIndex, count); } public override IEnumerator GetEnumerator() { return this.list.GetEnumerator(); } public override IEnumerator GetEnumerator(int index, int count) { return this.list.GetEnumerator(index, count); } public override int IndexOf(object value) { return this.list.IndexOf(value); } public override int IndexOf(object value, int startIndex) { return this.list.IndexOf(value, startIndex); } public override int IndexOf(object value, int startIndex, int count) { return this.list.IndexOf(value, startIndex, count); } public override void Insert(int index, object value) { this.list.Insert(index, value); } public override void InsertRange(int index, ICollection c) { this.list.InsertRange(index, c); } public override int LastIndexOf(object value) { return this.list.LastIndexOf(value); } public override int LastIndexOf(object value, int startIndex) { return this.list.LastIndexOf(value, startIndex); } public override int LastIndexOf(object value, int startIndex, int count) { return this.list.LastIndexOf(value, startIndex, count); } public override void Remove(object value) { this.list.Remove(value); } public override void RemoveAt(int index) { this.list.RemoveAt(index); } public override void RemoveRange(int index, int count) { this.list.RemoveRange(index, count); } public override void Reverse(int index, int count) { this.list.Reverse(index, count); } public override void SetRange(int index, ICollection c) { this.list.SetRange(index, c); } public override ArrayList GetRange(int index, int count) { return this.list.GetRange(index, count); } public override void Sort() { this.list.Sort(); } public override void Sort(IComparer comparer) { this.list.Sort(comparer); } public override void Sort(int index, int count, IComparer comparer) { this.list.Sort(index, count, comparer); } public override object[] ToArray() { return this.list.ToArray(); } public override Array ToArray(Type type) { return this.list.ToArray(type); } public override void TrimToSize() { this.list.TrimToSize(); } public ArrayList Swap() { ArrayList old = this.list; this.list = new ArrayList(old.Capacity); return old; } } /// <summary> /// Helper class used for ConnectionGroup.m_ConnectionList. The goal here is to /// intercept each new Connection object being added to ConnectionGroup.m_ConnectionList /// and replace its m_WriteList arraylist field. /// </summary> private sealed class ConnectionArrayList : ArrayListWrapper { public ConnectionArrayList(ArrayList list) : base(list) { } public override int Add(object value) { HookConnection(value); return base.Add(value); } } /// <summary> /// Helper class used for Connection.m_WriteList. The goal here is to /// intercept all new HttpWebRequest objects being added to Connection.m_WriteList /// and notify the listener about the HttpWebRequest that's about to send a request. /// It also intercepts all HttpWebRequest objects that are about to get removed from /// Connection.m_WriteList as they have completed the request. /// </summary> private sealed class HttpWebRequestArrayList : ArrayListWrapper { public HttpWebRequestArrayList(ArrayList list) : base(list) { } public override int Add(object value) { // Add before firing events so if some user code cancels/aborts the request it will be found in the outstanding list. int index = base.Add(value); if (value is HttpWebRequest request) { ProcessRequest(request); } return index; } public override void RemoveAt(int index) { object request = this[index]; base.RemoveAt(index); if (request is HttpWebRequest webRequest) { HookOrProcessResult(webRequest); } } public override void Clear() { ArrayList oldList = this.Swap(); for (int i = 0; i < oldList.Count; i++) { if (oldList[i] is HttpWebRequest request) { HookOrProcessResult(request); } } } } /// <summary> /// A closure object so our state is available when our callback executes. /// </summary> private sealed class AsyncCallbackWrapper { public AsyncCallbackWrapper(HttpWebRequest request, Activity activity, AsyncCallback originalCallback) { this.Request = request; this.Activity = activity; this.OriginalCallback = originalCallback; } public HttpWebRequest Request { get; } public Activity Activity { get; } public AsyncCallback OriginalCallback { get; } public void AsyncCallback(IAsyncResult asyncResult) { object result = resultAccessor(asyncResult); if (result is Exception || result is HttpWebResponse) { ProcessResult(asyncResult, this.OriginalCallback, this.Activity, result, false); } this.OriginalCallback?.Invoke(asyncResult); } } } } #endif
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace DocuSign.eSign.Model { /// <summary> /// /// </summary> [DataContract] public class GroupInformation : IEquatable<GroupInformation> { /// <summary> /// A collection group objects containing information about the groups returned. /// </summary> /// <value>A collection group objects containing information about the groups returned.</value> [DataMember(Name="groups", EmitDefaultValue=false)] public List<Group> Groups { get; set; } /// <summary> /// The number of results returned in this response. /// </summary> /// <value>The number of results returned in this response.</value> [DataMember(Name="resultSetSize", EmitDefaultValue=false)] public string ResultSetSize { get; set; } /// <summary> /// The total number of items available in the result set. This will always be greater than or equal to the value of the `resultSetSize` property. /// </summary> /// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the `resultSetSize` property.</value> [DataMember(Name="totalSetSize", EmitDefaultValue=false)] public string TotalSetSize { get; set; } /// <summary> /// Starting position of the current result set. /// </summary> /// <value>Starting position of the current result set.</value> [DataMember(Name="startPosition", EmitDefaultValue=false)] public string StartPosition { get; set; } /// <summary> /// The last position in the result set. /// </summary> /// <value>The last position in the result set.</value> [DataMember(Name="endPosition", EmitDefaultValue=false)] public string EndPosition { get; set; } /// <summary> /// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. /// </summary> /// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.</value> [DataMember(Name="nextUri", EmitDefaultValue=false)] public string NextUri { get; set; } /// <summary> /// The postal code for the billing address. /// </summary> /// <value>The postal code for the billing address.</value> [DataMember(Name="previousUri", EmitDefaultValue=false)] public string PreviousUri { 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 GroupInformation {\n"); sb.Append(" Groups: ").Append(Groups).Append("\n"); sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n"); sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n"); sb.Append(" StartPosition: ").Append(StartPosition).Append("\n"); sb.Append(" EndPosition: ").Append(EndPosition).Append("\n"); sb.Append(" NextUri: ").Append(NextUri).Append("\n"); sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as GroupInformation); } /// <summary> /// Returns true if GroupInformation instances are equal /// </summary> /// <param name="other">Instance of GroupInformation to be compared</param> /// <returns>Boolean</returns> public bool Equals(GroupInformation other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Groups == other.Groups || this.Groups != null && this.Groups.SequenceEqual(other.Groups) ) && ( this.ResultSetSize == other.ResultSetSize || this.ResultSetSize != null && this.ResultSetSize.Equals(other.ResultSetSize) ) && ( this.TotalSetSize == other.TotalSetSize || this.TotalSetSize != null && this.TotalSetSize.Equals(other.TotalSetSize) ) && ( this.StartPosition == other.StartPosition || this.StartPosition != null && this.StartPosition.Equals(other.StartPosition) ) && ( this.EndPosition == other.EndPosition || this.EndPosition != null && this.EndPosition.Equals(other.EndPosition) ) && ( this.NextUri == other.NextUri || this.NextUri != null && this.NextUri.Equals(other.NextUri) ) && ( this.PreviousUri == other.PreviousUri || this.PreviousUri != null && this.PreviousUri.Equals(other.PreviousUri) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Groups != null) hash = hash * 57 + this.Groups.GetHashCode(); if (this.ResultSetSize != null) hash = hash * 57 + this.ResultSetSize.GetHashCode(); if (this.TotalSetSize != null) hash = hash * 57 + this.TotalSetSize.GetHashCode(); if (this.StartPosition != null) hash = hash * 57 + this.StartPosition.GetHashCode(); if (this.EndPosition != null) hash = hash * 57 + this.EndPosition.GetHashCode(); if (this.NextUri != null) hash = hash * 57 + this.NextUri.GetHashCode(); if (this.PreviousUri != null) hash = hash * 57 + this.PreviousUri.GetHashCode(); return hash; } } } }
using Saga.Packets; using Saga.Shared.PacketLib; using Saga.Shared.PacketLib.Gateway; using System; using System.Diagnostics; using System.Net; using System.Net.Sockets; namespace Saga.Gateway.Network { public class GatewayClient : Shared.NetworkCore.EncryptedClient { #region CORE public static TraceLog log = new TraceLog("GatewayClient.Packetlog", "Log class to log all packet trafic", 0); public static bool CheckCrc = false; public uint session = 0; public WorldClient world; public GatewayClient(Socket socket) : base(socket) { OnClose += new EventHandler(GatewayClient_OnClose); Console.WriteLine("New client opened"); } private void GatewayClient_OnClose(object sender, EventArgs e) { ReleaseResources(); } private void ReleaseResources() { try { //Close resource on the login SMSG_RELEASEAUTH spkt = new SMSG_RELEASEAUTH(); spkt.Session = this.session; spkt.SessionId = 0; LoginClient client; if (NetworkManager.TryGetLoginClient(out client)) client.Send((byte[])spkt); } catch (SocketException) { Trace.TraceWarning("Network error"); } catch (Exception) { Trace.TraceError("Unidentified error"); } finally { if (world != null) world.Close(); GatewayPool.Instance.lookup.Remove(this.session); } } protected override void ProcessPacket(ref byte[] body) { ushort packetIdentifier = (ushort)(body[7] + (body[6] << 8)); #if DEBUG switch (log.LogLevel) { case 1: log.WriteLine("Network debug gateway", "Packet Recieved: {0:X4}", packetIdentifier); break; case 2: log.WriteLine("Network debug gateway", "Packet Recieved: {0:X4}", packetIdentifier); Console.WriteLine("Packet received: {0:X4} from: {1}", packetIdentifier, "gateway client"); break; case 3: log.WriteLine("Network debug gateway", "Packet Recieved: {0:X4} data {1}", packetIdentifier, Saga.Shared.PacketLib.Other.Conversions.ByteToHexString(body)); break; case 4: log.WriteLine("Network debug gateway", "Packet Recieved: {0:X4} data {1}", packetIdentifier, Saga.Shared.PacketLib.Other.Conversions.ByteToHexString(body)); Console.WriteLine("Packet received: {0:X4} from: {1}", packetIdentifier, "gateway client"); break; } #endif switch (packetIdentifier) { case 0x0105: OnHeader(); return; case 0x0101: OnKey((CMSG_SENDKEY)body); return; case 0x0102: OnGUID((CMSG_GUID)body); return; case 0x0103: OnKey2(); return; case 0x0104: OnIdentify(); return; case 0x0501: RedirectMap(body); return; case 0x0301: RedirectLogin(body); return; default: Trace.TraceWarning("Unsupported packet found with id: {0:X4}", packetIdentifier); this.Close(); break; } } #endregion CORE #region Packet Handeling private void OnHeader() { Trace.TraceInformation("Header Recieved from {0}", this.socket.RemoteEndPoint); try { byte[] tempServerKey = Encryption.GenerateKey(); byte[] expandedServerKey = Encryption.GenerateDecExpKey(tempServerKey); SMSG_SENDKEY spkt = new SMSG_SENDKEY(); spkt.Key = expandedServerKey; spkt.Collumns = 4; spkt.Rounds = 10; spkt.Direction = 2; this.Send((byte[])spkt); this.serverKey = tempServerKey; } catch (Exception ex) { Trace.TraceError("An unhandled exception occured {0}", ex.Message); this.Close(); } } private void OnKey(CMSG_SENDKEY cpkt) { Trace.TraceInformation("Key Recieved from {0}", this.socket.RemoteEndPoint); try { this.clientKey = cpkt.Key; SMSG_GUID spkt = new SMSG_GUID(); spkt.Key = Program.CrcKey; this.Send((byte[])spkt); } catch (Exception ex) { Trace.TraceError("An unhandled exception occured {0}", ex.Message); this.Close(); } } private void OnGUID(CMSG_GUID cpkt) { Trace.TraceInformation("GUID Recieved from {0}", this.socket.RemoteEndPoint); try { string key = cpkt.Key; if (CheckCrc == true && key != Program.GuidKey) { IPEndPoint endpoint = (IPEndPoint)this.socket.RemoteEndPoint; Trace.TraceError(String.Format("GUID Mismatch on ip {1} key: {0} ", key, endpoint.Address)); this.Close(); return; } else { SMSG_IDENTIFY spkt2 = new SMSG_IDENTIFY(); this.Send((byte[])spkt2); } } catch (Exception ex) { Trace.TraceError("An unhandled exception occured {0}", ex.Message); this.Close(); } } private void OnKey2() { Trace.TraceInformation("Key2 received from: {0}", this.socket.RemoteEndPoint); } /// <summary> /// This packet indicates the client requests for a new /// session. First we'll set the session to 0 so we can /// set the session with the next packet we send. /// /// If all goes well, the next following code should be /// internal: SetSessionId() invoked by the SessionPool. /// </summary> private void OnIdentify() { Trace.TraceInformation("Identify Recieved from {0}", this.socket.RemoteEndPoint); try { SMSG_UKNOWN spkt = new SMSG_UKNOWN(); spkt.Result = 0; this.Send((byte[])spkt); //Invoke the session pool for an new request if (!SessionPool.Instance.Request(this)) { Trace.TraceInformation("Unable to request an new session for {0} - Reason {1}", this.socket.RemoteEndPoint, NetworkManager.LastError); this.Close(); } } catch (SessionRequestException ex) { Trace.TraceInformation("An unhandled exception occured has raised during session request {0} {1}", ex, ex.InnerException); this.Close(); } catch (Exception ex) { Trace.TraceInformation("An unhandled exception occured {0}", ex.Message); this.Close(); } } #endregion Packet Handeling #region Internal Methods internal void SetSessionId(uint session) { try { Trace.TraceInformation("Set session-id {1} received from: {0}", this.socket.RemoteEndPoint, session); if (session > 0) { //Update session, add session to lookup table this.session = session; GatewayPool.Instance.lookup.Add(session, this); //Exchange ip adress LoginClient client; if (NetworkManager.TryGetLoginClient(out client)) { IPEndPoint endpoint = (IPEndPoint)this.socket.RemoteEndPoint; SMSG_NETWORKADRESSIP spkt = new SMSG_NETWORKADRESSIP(); spkt.ConnectionFrom = endpoint.Address; spkt.SessionId = session; client.Send((byte[])spkt); } //Forward to out client SMSG_UKNOWN2 spkt2 = new SMSG_UKNOWN2(); spkt2.SessionId = this.session; this.Send((byte[])spkt2); } else { Trace.TraceError("Session with value 0 was given"); } } catch (ObjectDisposedException) { //Closing connection this.Close(); } catch (System.Net.Sockets.SocketException) { //Closing connection this.Close(); } } private void RedirectLogin(byte[] body) { try { LoginClient client; if (NetworkManager.TryGetLoginClient(out client)) { client.Send(body); } else { //Output a error byte[] buffer2 = new byte[] { 0x0B, 0x00, 0x74, 0x17, 0x91, 0x00, 0x02, 0x07, 0x00, 0x00, 0x01 }; Array.Copy(BitConverter.GetBytes(session), 0, buffer2, 2, 4); this.Send(buffer2); } } catch (ObjectDisposedException ex) { Trace.TraceError("Connection with the auth server has been lost, packet are discared"); } catch (Exception) { Trace.TraceError("Connection with the auth server has been lost, packet are discared"); } } private void RedirectMap(byte[] body) { try { if (world != null) { world.Send(body); } else { Console.WriteLine("world is null"); } } catch (ObjectDisposedException) { Trace.TraceError("Connection with the world server has been lost, packet are discared"); world = null; this.Close(); } catch (Exception) { Trace.TraceError("Connection with the world server has been lost, packet are discared"); this.Close(); } } #endregion Internal Methods } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// CustomerEmail /// </summary> [DataContract] public partial class CustomerEmail : IEquatable<CustomerEmail>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CustomerEmail" /> class. /// </summary> /// <param name="customerProfileEmailOid">ID of the email.</param> /// <param name="email">Email.</param> /// <param name="label">Label.</param> /// <param name="receiptNotification">CC this email on receipt notifications.</param> /// <param name="refundNotification">CC this email on refund notifications.</param> /// <param name="shipmentNotification">CC this email on shipment notifications.</param> public CustomerEmail(int? customerProfileEmailOid = default(int?), string email = default(string), string label = default(string), bool? receiptNotification = default(bool?), bool? refundNotification = default(bool?), bool? shipmentNotification = default(bool?)) { this.CustomerProfileEmailOid = customerProfileEmailOid; this.Email = email; this.Label = label; this.ReceiptNotification = receiptNotification; this.RefundNotification = refundNotification; this.ShipmentNotification = shipmentNotification; } /// <summary> /// ID of the email /// </summary> /// <value>ID of the email</value> [DataMember(Name="customer_profile_email_oid", EmitDefaultValue=false)] public int? CustomerProfileEmailOid { get; set; } /// <summary> /// Email /// </summary> /// <value>Email</value> [DataMember(Name="email", EmitDefaultValue=false)] public string Email { get; set; } /// <summary> /// Label /// </summary> /// <value>Label</value> [DataMember(Name="label", EmitDefaultValue=false)] public string Label { get; set; } /// <summary> /// CC this email on receipt notifications /// </summary> /// <value>CC this email on receipt notifications</value> [DataMember(Name="receipt_notification", EmitDefaultValue=false)] public bool? ReceiptNotification { get; set; } /// <summary> /// CC this email on refund notifications /// </summary> /// <value>CC this email on refund notifications</value> [DataMember(Name="refund_notification", EmitDefaultValue=false)] public bool? RefundNotification { get; set; } /// <summary> /// CC this email on shipment notifications /// </summary> /// <value>CC this email on shipment notifications</value> [DataMember(Name="shipment_notification", EmitDefaultValue=false)] public bool? ShipmentNotification { 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 CustomerEmail {\n"); sb.Append(" CustomerProfileEmailOid: ").Append(CustomerProfileEmailOid).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" Label: ").Append(Label).Append("\n"); sb.Append(" ReceiptNotification: ").Append(ReceiptNotification).Append("\n"); sb.Append(" RefundNotification: ").Append(RefundNotification).Append("\n"); sb.Append(" ShipmentNotification: ").Append(ShipmentNotification).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 JsonConvert.SerializeObject(this, 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 CustomerEmail); } /// <summary> /// Returns true if CustomerEmail instances are equal /// </summary> /// <param name="input">Instance of CustomerEmail to be compared</param> /// <returns>Boolean</returns> public bool Equals(CustomerEmail input) { if (input == null) return false; return ( this.CustomerProfileEmailOid == input.CustomerProfileEmailOid || (this.CustomerProfileEmailOid != null && this.CustomerProfileEmailOid.Equals(input.CustomerProfileEmailOid)) ) && ( this.Email == input.Email || (this.Email != null && this.Email.Equals(input.Email)) ) && ( this.Label == input.Label || (this.Label != null && this.Label.Equals(input.Label)) ) && ( this.ReceiptNotification == input.ReceiptNotification || (this.ReceiptNotification != null && this.ReceiptNotification.Equals(input.ReceiptNotification)) ) && ( this.RefundNotification == input.RefundNotification || (this.RefundNotification != null && this.RefundNotification.Equals(input.RefundNotification)) ) && ( this.ShipmentNotification == input.ShipmentNotification || (this.ShipmentNotification != null && this.ShipmentNotification.Equals(input.ShipmentNotification)) ); } /// <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.CustomerProfileEmailOid != null) hashCode = hashCode * 59 + this.CustomerProfileEmailOid.GetHashCode(); if (this.Email != null) hashCode = hashCode * 59 + this.Email.GetHashCode(); if (this.Label != null) hashCode = hashCode * 59 + this.Label.GetHashCode(); if (this.ReceiptNotification != null) hashCode = hashCode * 59 + this.ReceiptNotification.GetHashCode(); if (this.RefundNotification != null) hashCode = hashCode * 59 + this.RefundNotification.GetHashCode(); if (this.ShipmentNotification != null) hashCode = hashCode * 59 + this.ShipmentNotification.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) { // Email (string) maxLength if(this.Email != null && this.Email.Length > 100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Email, length must be less than 100.", new [] { "Email" }); } // Label (string) maxLength if(this.Label != null && this.Label.Length > 100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Label, length must be less than 100.", new [] { "Label" }); } yield break; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { public partial class TestWorkspace { private const string CSharpExtension = ".cs"; private const string CSharpScriptExtension = ".csx"; private const string VisualBasicExtension = ".vb"; private const string VisualBasicScriptExtension = ".vbx"; private const string WorkspaceElementName = "Workspace"; private const string ProjectElementName = "Project"; private const string SubmissionElementName = "Submission"; private const string MetadataReferenceElementName = "MetadataReference"; private const string MetadataReferenceFromSourceElementName = "MetadataReferenceFromSource"; private const string ProjectReferenceElementName = "ProjectReference"; private const string CompilationOptionsElementName = "CompilationOptions"; private const string RootNamespaceAttributeName = "RootNamespace"; private const string OutputTypeAttributeName = "OutputType"; private const string ReportDiagnosticAttributeName = "ReportDiagnostic"; private const string ParseOptionsElementName = "ParseOptions"; private const string LanguageVersionAttributeName = "LanguageVersion"; private const string DocumentationModeAttributeName = "DocumentationMode"; private const string DocumentElementName = "Document"; private const string AnalyzerElementName = "Analyzer"; private const string AssemblyNameAttributeName = "AssemblyName"; private const string CommonReferencesAttributeName = "CommonReferences"; private const string CommonReferencesWinRTAttributeName = "CommonReferencesWinRT"; private const string CommonReferencesNet45AttributeName = "CommonReferencesNet45"; private const string CommonReferencesPortableAttributeName = "CommonReferencesPortable"; private const string CommonReferenceFacadeSystemRuntimeAttributeName = "CommonReferenceFacadeSystemRuntime"; private const string FilePathAttributeName = "FilePath"; private const string FoldersAttributeName = "Folders"; private const string KindAttributeName = "Kind"; private const string LanguageAttributeName = "Language"; private const string GlobalImportElementName = "GlobalImport"; private const string IncludeXmlDocCommentsAttributeName = "IncludeXmlDocComments"; private const string IsLinkFileAttributeName = "IsLinkFile"; private const string LinkAssemblyNameAttributeName = "LinkAssemblyName"; private const string LinkProjectNameAttributeName = "LinkProjectName"; private const string LinkFilePathAttributeName = "LinkFilePath"; private const string PreprocessorSymbolsAttributeName = "PreprocessorSymbols"; private const string AnalyzerDisplayAttributeName = "Name"; private const string AnalyzerFullPathAttributeName = "FullPath"; private const string AliasAttributeName = "Alias"; private const string ProjectNameAttribute = "Name"; /// <summary> /// Creates a single buffer in a workspace. /// </summary> /// <param name="content">Lines of text, the buffer contents</param> internal static Task<TestWorkspace> CreateAsync( string language, CompilationOptions compilationOptions, ParseOptions parseOptions, string content) { return CreateAsync(language, compilationOptions, parseOptions, new[] { content }); } /// <summary> /// Creates a single buffer in a workspace. /// </summary> /// <param name="content">Lines of text, the buffer contents</param> internal static Task<TestWorkspace> CreateAsync( string workspaceKind, string language, CompilationOptions compilationOptions, ParseOptions parseOptions, string content) { return CreateAsync(workspaceKind, language, compilationOptions, parseOptions, new[] { content }); } /// <param name="files">Can pass in multiple file contents: files will be named test1.cs, test2.cs, etc.</param> internal static Task<TestWorkspace> CreateAsync( string language, CompilationOptions compilationOptions, ParseOptions parseOptions, params string[] files) { return CreateAsync(language, compilationOptions, parseOptions, files, exportProvider: null); } /// <param name="files">Can pass in multiple file contents: files will be named test1.cs, test2.cs, etc.</param> internal static Task<TestWorkspace> CreateAsync( string workspaceKind, string language, CompilationOptions compilationOptions, ParseOptions parseOptions, params string[] files) { return CreateAsync(language, compilationOptions, parseOptions, files, exportProvider: null, workspaceKind: workspaceKind); } internal static async Task<TestWorkspace> CreateAsync( string language, CompilationOptions compilationOptions, ParseOptions parseOptions, string[] files, ExportProvider exportProvider, string[] metadataReferences = null, string workspaceKind = null, string extension = null, bool commonReferences = true) { var documentElements = new List<XElement>(); var index = 1; if (extension == null) { extension = language == LanguageNames.CSharp ? CSharpExtension : VisualBasicExtension; } foreach (var file in files) { documentElements.Add(CreateDocumentElement(file, "test" + index++ + extension, parseOptions)); } metadataReferences = metadataReferences ?? SpecializedCollections.EmptyArray<string>(); foreach (var reference in metadataReferences) { documentElements.Add(CreateMetadataReference(reference)); } var workspaceElement = CreateWorkspaceElement( CreateProjectElement(compilationOptions?.ModuleName ?? "Test", language, commonReferences, parseOptions, compilationOptions, documentElements)); return await CreateAsync(workspaceElement, exportProvider: exportProvider, workspaceKind: workspaceKind); } internal static Task<TestWorkspace> CreateAsync( string language, CompilationOptions compilationOptions, ParseOptions[] parseOptions, string[] files, ExportProvider exportProvider) { Contract.Requires(parseOptions == null || (files.Length == parseOptions.Length), "Please specify a parse option for each file."); var documentElements = new List<XElement>(); var index = 1; var extension = ""; for (int i = 0; i < files.Length; i++) { if (language == LanguageNames.CSharp) { extension = parseOptions[i].Kind == SourceCodeKind.Regular ? CSharpExtension : CSharpScriptExtension; } else if (language == LanguageNames.VisualBasic) { extension = parseOptions[i].Kind == SourceCodeKind.Regular ? VisualBasicExtension : VisualBasicScriptExtension; } else { extension = language; } documentElements.Add(CreateDocumentElement(files[i], "test" + index++ + extension, parseOptions == null ? null : parseOptions[i])); } var workspaceElement = CreateWorkspaceElement( CreateProjectElement("Test", language, true, parseOptions.FirstOrDefault(), compilationOptions, documentElements)); return CreateAsync(workspaceElement, exportProvider: exportProvider); } #region C# public static Task<TestWorkspace> CreateCSharpAsync( string file, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, ExportProvider exportProvider = null, string[] metadataReferences = null) { return CreateCSharpAsync(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences); } public static Task<TestWorkspace> CreateCSharpAsync( string[] files, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, ExportProvider exportProvider = null, string[] metadataReferences = null) { return CreateAsync(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider, metadataReferences); } public static Task<TestWorkspace> CreateCSharpAsync( string[] files, ParseOptions[] parseOptions = null, CompilationOptions compilationOptions = null, ExportProvider exportProvider = null) { return CreateAsync(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider); } #endregion #region VB public static Task<TestWorkspace> CreateVisualBasicAsync( string file, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, ExportProvider exportProvider = null, string[] metadataReferences = null) { return CreateVisualBasicAsync(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences); } public static Task<TestWorkspace> CreateVisualBasicAsync( string[] files, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, ExportProvider exportProvider = null, string[] metadataReferences = null) { return CreateAsync(LanguageNames.VisualBasic, compilationOptions, parseOptions, files, exportProvider, metadataReferences); } /// <param name="files">Can pass in multiple file contents with individual source kind: files will be named test1.vb, test2.vbx, etc.</param> public static Task<TestWorkspace> CreateVisualBasicAsync( string[] files, ParseOptions[] parseOptions = null, CompilationOptions compilationOptions = null, ExportProvider exportProvider = null) { return CreateAsync(LanguageNames.VisualBasic, compilationOptions, parseOptions, files, exportProvider); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { // SecureChannel - a wrapper on SSPI based functionality. // Provides an additional abstraction layer over SSPI for SslStream. internal class SecureChannel { // When reading a frame from the wire first read this many bytes for the header. internal const int ReadHeaderSize = 5; private SafeFreeCredentials _credentialsHandle; private SafeDeleteSslContext _securityContext; private SslConnectionInfo _connectionInfo; private X509Certificate _selectedClientCertificate; private bool _isRemoteCertificateAvailable; // These are the MAX encrypt buffer output sizes, not the actual sizes. private int _headerSize = 5; //ATTN must be set to at least 5 by default private int _trailerSize = 16; private int _maxDataSize = 16354; private bool _refreshCredentialNeeded; private readonly SslAuthenticationOptions _sslAuthenticationOptions; private SslApplicationProtocol _negotiatedApplicationProtocol; private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1"); private static readonly Oid s_clientAuthOid = new Oid("1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.2"); internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates); NetEventSource.Log.SecureChannelCtor(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy); } SslStreamPal.VerifyPackageInfo(); if (sslAuthenticationOptions.TargetHost == null) { NetEventSource.Fail(this, "sslAuthenticationOptions.TargetHost == null"); } _securityContext = null; _refreshCredentialNeeded = true; _sslAuthenticationOptions = sslAuthenticationOptions; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } // // SecureChannel properties // // LocalServerCertificate - local certificate for server mode channel // LocalClientCertificate - selected certificated used in the client channel mode otherwise null // IsRemoteCertificateAvailable - true if the remote side has provided a certificate // HeaderSize - Header & trailer sizes used in the TLS stream // TrailerSize - // internal X509Certificate LocalServerCertificate { get { return _sslAuthenticationOptions.ServerCertificate; } } internal X509Certificate LocalClientCertificate { get { return _selectedClientCertificate; } } internal bool IsRemoteCertificateAvailable { get { return _isRemoteCertificateAvailable; } } internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, kind); ChannelBinding result = null; if (_securityContext != null) { result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind); } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result); return result; } internal X509RevocationMode CheckCertRevocationStatus { get { return _sslAuthenticationOptions.CertificateRevocationCheckMode; } } internal int MaxDataSize { get { return _maxDataSize; } } internal SslConnectionInfo ConnectionInfo { get { return _connectionInfo; } } internal bool IsValidContext { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return !(_securityContext == null || _securityContext.IsInvalid); } } internal bool IsServer { get { return _sslAuthenticationOptions.IsServer; } } internal bool RemoteCertRequired { get { return _sslAuthenticationOptions.RemoteCertRequired; } } internal SslApplicationProtocol NegotiatedApplicationProtocol { get { return _negotiatedApplicationProtocol; } } internal void SetRefreshCredentialNeeded() { _refreshCredentialNeeded = true; } internal void Close() { _securityContext?.Dispose(); _credentialsHandle?.Dispose(); GC.SuppressFinalize(this); } // // SECURITY: we open a private key container on behalf of the caller // and we require the caller to have permission associated with that operation. // private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) { if (certificate == null) { return null; } if (NetEventSource.IsEnabled) NetEventSource.Log.LocatingPrivateKey(certificate, this); try { // Protecting from X509Certificate2 derived classes. X509Certificate2 certEx = MakeEx(certificate); if (certEx != null) { if (certEx.HasPrivateKey) { if (NetEventSource.IsEnabled) NetEventSource.Log.CertIsType2(this); return certEx; } if ((object)certificate != (object)certEx) { certEx.Dispose(); } } X509Certificate2Collection collectionEx; string certHash = certEx.Thumbprint; // ELSE Try the MY user and machine stores for private key check. // For server side mode MY machine store takes priority. X509Store store = CertificateValidationPal.EnsureStoreOpened(_sslAuthenticationOptions.IsServer); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (NetEventSource.IsEnabled) NetEventSource.Log.FoundCertInStore(_sslAuthenticationOptions.IsServer, this); return collectionEx[0]; } } store = CertificateValidationPal.EnsureStoreOpened(!_sslAuthenticationOptions.IsServer); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (NetEventSource.IsEnabled) NetEventSource.Log.FoundCertInStore(_sslAuthenticationOptions.IsServer, this); return collectionEx[0]; } } } catch (CryptographicException) { } if (NetEventSource.IsEnabled) NetEventSource.Log.NotFoundCertInStore(this); return null; } private static X509Certificate2 MakeEx(X509Certificate certificate) { Debug.Assert(certificate != null, "certificate != null"); if (certificate.GetType() == typeof(X509Certificate2)) { return (X509Certificate2)certificate; } X509Certificate2 certificateEx = null; try { if (certificate.Handle != IntPtr.Zero) { certificateEx = new X509Certificate2(certificate); } } catch (SecurityException) { } catch (CryptographicException) { } return certificateEx; } // // Get certificate_authorities list, according to RFC 5246, Section 7.4.4. // Used only by client SSL code, never returns null. // private string[] GetRequestCertificateAuthorities() { string[] issuers = Array.Empty<string>(); if (IsValidContext) { issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext); } return issuers; } /*++ AcquireCredentials - Attempts to find Client Credential Information, that can be sent to the server. In our case, this is only Client Certificates, that we have Credential Info. How it works: case 0: Cert Selection delegate is present Always use its result as the client cert answer. Try to use cached credential handle whenever feasible. Do not use cached anonymous creds if the delegate has returned null and the collection is not empty (allow responding with the cert later). case 1: Certs collection is empty Always use the same statically acquired anonymous SSL Credential case 2: Before our Connection with the Server If we have a cached credential handle keyed by first X509Certificate **content** in the passed collection, then we use that cached credential and hoping to restart a session. Otherwise create a new anonymous (allow responding with the cert later). case 3: After our Connection with the Server (i.e. during handshake or re-handshake) The server has requested that we send it a Certificate then we Enumerate a list of server sent Issuers trying to match against our list of Certificates, the first match is sent to the server. Once we got a cert we again try to match cached credential handle if possible. This will not restart a session but helps minimizing the number of handles we create. In the case of an error getting a Certificate or checking its private Key we fall back to the behavior of having no certs, case 1. Returns: True if cached creds were used, false otherwise. --*/ private bool AcquireClientCredentials(ref byte[] thumbPrint) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); // Acquire possible Client Certificate information and set it on the handle. X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart. List<X509Certificate> filteredCerts = null; // This is an intermediate client certs collection that try to use if no selectedCert is available yet. string[] issuers; // This is a list of issuers sent by the server, only valid is we do know what the server cert is. bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds. if (_sslAuthenticationOptions.CertSelectionDelegate != null) { issuers = GetRequestCertificateAuthorities(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling CertificateSelectionCallback"); X509Certificate2 remoteCert = null; try { remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext); if (_sslAuthenticationOptions.ClientCertificates == null) { _sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection(); } clientCertificate = _sslAuthenticationOptions.CertSelectionDelegate(_sslAuthenticationOptions.TargetHost, _sslAuthenticationOptions.ClientCertificates, remoteCert, issuers); } finally { remoteCert?.Dispose(); } if (clientCertificate != null) { if (_credentialsHandle == null) { sessionRestartAttempt = true; } EnsureInitialized(ref filteredCerts).Add(clientCertificate); if (NetEventSource.IsEnabled) NetEventSource.Log.CertificateFromDelegate(this); } else { if (_sslAuthenticationOptions.ClientCertificates == null || _sslAuthenticationOptions.ClientCertificates.Count == 0) { if (NetEventSource.IsEnabled) NetEventSource.Log.NoDelegateNoClientCert(this); sessionRestartAttempt = true; } else { if (NetEventSource.IsEnabled) NetEventSource.Log.NoDelegateButClientCert(this); } } } else if (_credentialsHandle == null && _sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0) { // This is where we attempt to restart a session by picking the FIRST cert from the collection. // Otherwise it is either server sending a client cert request or the session is renegotiated. clientCertificate = _sslAuthenticationOptions.ClientCertificates[0]; sessionRestartAttempt = true; if (clientCertificate != null) { EnsureInitialized(ref filteredCerts).Add(clientCertificate); } if (NetEventSource.IsEnabled) NetEventSource.Log.AttemptingRestartUsingCert(clientCertificate, this); } else if (_sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0) { // // This should be a server request for the client cert sent over currently anonymous sessions. // issuers = GetRequestCertificateAuthorities(); if (NetEventSource.IsEnabled) { if (issuers == null || issuers.Length == 0) { NetEventSource.Log.NoIssuersTryAllCerts(this); } else { NetEventSource.Log.LookForMatchingCerts(issuers.Length, this); } } for (int i = 0; i < _sslAuthenticationOptions.ClientCertificates.Count; ++i) { // // Make sure we add only if the cert matches one of the issuers. // If no issuers were sent and then try all client certs starting with the first one. // if (issuers != null && issuers.Length != 0) { X509Certificate2 certificateEx = null; X509Chain chain = null; try { certificateEx = MakeEx(_sslAuthenticationOptions.ClientCertificates[i]); if (certificateEx == null) { continue; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Root cert: {certificateEx}"); chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName; chain.Build(certificateEx); bool found = false; // // We ignore any errors happened with chain. // if (chain.ChainElements.Count > 0) { int elementsCount = chain.ChainElements.Count; for (int ii = 0; ii < elementsCount; ++ii) { string issuer = chain.ChainElements[ii].Certificate.Issuer; found = Array.IndexOf(issuers, issuer) != -1; if (found) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Matched {issuer}"); break; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"No match: {issuer}"); } } if (!found) { continue; } } finally { if (chain != null) { chain.Dispose(); int elementsCount = chain.ChainElements.Count; for (int element = 0; element < elementsCount; element++) { chain.ChainElements[element].Certificate.Dispose(); } } if (certificateEx != null && (object)certificateEx != (object)_sslAuthenticationOptions.ClientCertificates[i]) { certificateEx.Dispose(); } } } if (NetEventSource.IsEnabled) NetEventSource.Log.SelectedCert(_sslAuthenticationOptions.ClientCertificates[i], this); EnsureInitialized(ref filteredCerts).Add(_sslAuthenticationOptions.ClientCertificates[i]); } } bool cachedCred = false; // This is a return result from this method. X509Certificate2 selectedCert = null; // This is a final selected cert (ensured that it does have private key with it). clientCertificate = null; if (NetEventSource.IsEnabled) { if (filteredCerts != null && filteredCerts.Count != 0) { NetEventSource.Log.CertsAfterFiltering(filteredCerts.Count, this); NetEventSource.Log.FindingMatchingCerts(this); } else { NetEventSource.Log.CertsAfterFiltering(0, this); NetEventSource.Info(this, "No client certificate to choose from"); } } // // ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key, // THEN anonymous (no client cert) credential will be used. // // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. if (filteredCerts != null) { for (int i = 0; i < filteredCerts.Count; ++i) { clientCertificate = filteredCerts[i]; if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null) { break; } clientCertificate = null; selectedCert = null; } } if ((object)clientCertificate != (object)selectedCert && !clientCertificate.Equals(selectedCert)) { NetEventSource.Fail(this, "'selectedCert' does not match 'clientCertificate'."); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Selected cert = {selectedCert}"); try { // Try to locate cached creds first. // // SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type. // byte[] guessedThumbPrint = selectedCert?.GetCertHash(); SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); // We can probably do some optimization here. If the selectedCert is returned by the delegate // we can always go ahead and use the certificate to create our credential // (instead of going anonymous as we do here). if (sessionRestartAttempt && cachedCredentialHandle == null && selectedCert != null && SslStreamPal.StartMutualAuthAsAnonymous) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Reset to anonymous session."); // IIS does not renegotiate a restarted session if client cert is needed. // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate. // The following block happens if client did specify a certificate but no cached creds were found in the cache. // Since we don't restart a session the server side can still challenge for a client cert. if ((object)clientCertificate != (object)selectedCert) { selectedCert.Dispose(); } guessedThumbPrint = null; selectedCert = null; clientCertificate = null; } if (cachedCredentialHandle != null) { if (NetEventSource.IsEnabled) NetEventSource.Log.UsingCachedCredential(this); _credentialsHandle = cachedCredentialHandle; _selectedClientCertificate = clientCertificate; cachedCred = true; } else { _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer); thumbPrint = guessedThumbPrint; // Delay until here in case something above threw. _selectedClientCertificate = clientCertificate; } } finally { // An extra cert could have been created, dispose it now. if (selectedCert != null && (object)clientCertificate != (object)selectedCert) { selectedCert.Dispose(); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, cachedCred, _credentialsHandle); return cachedCred; } private static List<T> EnsureInitialized<T>(ref List<T> list) => list ?? (list = new List<T>()); // // Acquire Server Side Certificate information and set it on the class. // private bool AcquireServerCredentials(ref byte[] thumbPrint, byte[] clientHello) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); X509Certificate localCertificate = null; bool cachedCred = false; // There are three options for selecting the server certificate. When // selecting which to use, we prioritize the new ServerCertSelectionDelegate // API. If the new API isn't used we call LocalCertSelectionCallback (for compat // with .NET Framework), and if neither is set we fall back to using ServerCertificate. if (_sslAuthenticationOptions.ServerCertSelectionDelegate != null) { string serverIdentity = SniHelper.GetServerName(clientHello); localCertificate = _sslAuthenticationOptions.ServerCertSelectionDelegate(serverIdentity); if (localCertificate == null) { throw new AuthenticationException(SR.net_ssl_io_no_server_cert); } } else if (_sslAuthenticationOptions.CertSelectionDelegate != null) { X509CertificateCollection tempCollection = new X509CertificateCollection(); tempCollection.Add(_sslAuthenticationOptions.ServerCertificate); // We pass string.Empty here to maintain strict compatability with .NET Framework. localCertificate = _sslAuthenticationOptions.CertSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>()); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Use delegate selected Cert"); } else { localCertificate = _sslAuthenticationOptions.ServerCertificate; } if (localCertificate == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate); if (selectedCert == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } if (!localCertificate.Equals(selectedCert)) { NetEventSource.Fail(this, "'selectedCert' does not match 'localCertificate'."); } // // Note selectedCert is a safe ref possibly cloned from the user passed Cert object // byte[] guessedThumbPrint = selectedCert.GetCertHash(); try { SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); if (cachedCredentialHandle != null) { _credentialsHandle = cachedCredentialHandle; _sslAuthenticationOptions.ServerCertificate = localCertificate; cachedCred = true; } else { _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer); thumbPrint = guessedThumbPrint; _sslAuthenticationOptions.ServerCertificate = localCertificate; } } finally { // An extra cert could have been created, dispose it now. if ((object)localCertificate != (object)selectedCert) { selectedCert.Dispose(); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, cachedCred, _credentialsHandle); return cachedCred; } // internal ProtocolToken NextMessage(byte[] incoming, int offset, int count) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); byte[] nextmsg = null; SecurityStatusPal status = GenerateToken(incoming, offset, count, ref nextmsg); if (!_sslAuthenticationOptions.IsServer && status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "NextMessage() returned SecurityStatusPal.CredentialsNeeded"); SetRefreshCredentialNeeded(); status = GenerateToken(incoming, offset, count, ref nextmsg); } ProtocolToken token = new ProtocolToken(nextmsg, status); if (NetEventSource.IsEnabled) { if (token.Failed) { NetEventSource.Error(this, $"Authentication failed. Status: {status.ToString()}, Exception message: {token.GetException().Message}"); } NetEventSource.Exit(this, token); } return token; } /*++ GenerateToken - Called after each successive state in the Client - Server handshake. This function generates a set of bytes that will be sent next to the server. The server responds, each response, is pass then into this function, again, and the cycle repeats until successful connection, or failure. Input: input - bytes from the wire output - ref to byte [], what we will send to the server in response Return: status - error information --*/ private SecurityStatusPal GenerateToken(byte[] input, int offset, int count, ref byte[] output) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"_refreshCredentialNeeded = {_refreshCredentialNeeded}"); if (offset < 0 || offset > (input == null ? 0 : input.Length)) { NetEventSource.Fail(this, "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || count > (input == null ? 0 : input.Length - offset)) { NetEventSource.Fail(this, "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } byte[] result = Array.Empty<byte>(); SecurityStatusPal status = default; bool cachedCreds = false; byte[] thumbPrint = null; // // Looping through ASC or ISC with potentially cached credential that could have been // already disposed from a different thread before ISC or ASC dir increment a cred ref count. // try { do { thumbPrint = null; if (_refreshCredentialNeeded) { cachedCreds = _sslAuthenticationOptions.IsServer ? AcquireServerCredentials(ref thumbPrint, input) : AcquireClientCredentials(ref thumbPrint); } if (_sslAuthenticationOptions.IsServer) { status = SslStreamPal.AcceptSecurityContext( ref _credentialsHandle, ref _securityContext, input != null ? new ArraySegment<byte>(input, offset, count) : default, ref result, _sslAuthenticationOptions); } else { status = SslStreamPal.InitializeSecurityContext( ref _credentialsHandle, ref _securityContext, _sslAuthenticationOptions.TargetHost, input != null ? new ArraySegment<byte>(input, offset, count) : default, ref result, _sslAuthenticationOptions); } } while (cachedCreds && _credentialsHandle == null); } finally { if (_refreshCredentialNeeded) { _refreshCredentialNeeded = false; // // Assuming the ISC or ASC has referenced the credential, // we want to call dispose so to decrement the effective ref count. // _credentialsHandle?.Dispose(); // // This call may bump up the credential reference count further. // Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert. // if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid) { SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); } } } output = result; if (_negotiatedApplicationProtocol == default) { // try to get ALPN info unless we already have it. (this function can be called multiple times) byte[] alpnResult = SslStreamPal.GetNegotiatedApplicationProtocol(_securityContext); _negotiatedApplicationProtocol = alpnResult == null ? default : new SslApplicationProtocol(alpnResult, false); } if (NetEventSource.IsEnabled) { NetEventSource.Exit(this); } return status; } /*++ ProcessHandshakeSuccess - Called on successful completion of Handshake - used to set header/trailer sizes for encryption use Fills in the information about established protocol --*/ internal void ProcessHandshakeSuccess() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); SslStreamPal.QueryContextStreamSizes(_securityContext, out StreamSizes streamSizes); try { _headerSize = streamSizes.Header; _trailerSize = streamSizes.Trailer; _maxDataSize = checked(streamSizes.MaximumMessage - (_headerSize + _trailerSize)); Debug.Assert(_maxDataSize > 0, "_maxDataSize > 0"); } catch (Exception e) when (!ExceptionCheck.IsFatal(e)) { NetEventSource.Fail(this, "StreamSizes out of range."); throw; } SslStreamPal.QueryContextConnectionInfo(_securityContext, out _connectionInfo); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } /*++ Encrypt - Encrypts our bytes before we send them over the wire PERF: make more efficient, this does an extra copy when the offset is non-zero. Input: buffer - bytes for sending offset - size - output - Encrypted bytes --*/ internal SecurityStatusPal Encrypt(ReadOnlyMemory<byte> buffer, ref byte[] output, out int resultSize) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this, buffer, buffer.Length); NetEventSource.DumpBuffer(this, buffer); } byte[] writeBuffer = output; SecurityStatusPal secStatus = SslStreamPal.EncryptMessage( _securityContext, buffer, _headerSize, _trailerSize, ref writeBuffer, out resultSize); if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"ERROR {secStatus}"); } else { output = writeBuffer; if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"OK data size:{resultSize}"); } return secStatus; } internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, payload, offset, count); if ((uint)offset > (uint)(payload == null ? 0 : payload.Length)) { NetEventSource.Fail(this, "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } if ((uint)count > (uint)(payload == null ? 0 : payload.Length - offset)) { NetEventSource.Fail(this, "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } return SslStreamPal.DecryptMessage(_securityContext, payload, ref offset, ref count); } /*++ VerifyRemoteCertificate - Validates the content of a Remote Certificate checkCRL if true, checks the certificate revocation list for validity. checkCertName, if true checks the CN field of the certificate --*/ //This method validates a remote certificate. internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback, ref ProtocolToken alertToken) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; // We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true. bool success = false; X509Chain chain = null; X509Certificate2 remoteCertificateEx = null; X509Certificate2Collection remoteCertificateStore = null; try { remoteCertificateEx = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore); _isRemoteCertificateAvailable = remoteCertificateEx != null; if (remoteCertificateEx == null) { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"No remote certificate received. RemoteCertRequired: {RemoteCertRequired}"); sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable; } else { chain = new X509Chain(); chain.ChainPolicy.RevocationMode = _sslAuthenticationOptions.CertificateRevocationCheckMode; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; // Authenticate the remote party: (e.g. when operating in server mode, authenticate the client). chain.ChainPolicy.ApplicationPolicy.Add(_sslAuthenticationOptions.IsServer ? s_clientAuthOid : s_serverAuthOid); if (remoteCertificateStore != null) { chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore); } sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties( _securityContext, chain, remoteCertificateEx, _sslAuthenticationOptions.CheckCertName, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.TargetHost); } if (remoteCertValidationCallback != null) { success = remoteCertValidationCallback(_sslAuthenticationOptions.TargetHost, remoteCertificateEx, chain, sslPolicyErrors); } else { if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable && !_sslAuthenticationOptions.RemoteCertRequired) { success = true; } else { success = (sslPolicyErrors == SslPolicyErrors.None); } } if (NetEventSource.IsEnabled) { LogCertificateValidation(remoteCertValidationCallback, sslPolicyErrors, success, chain); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Cert validation, remote cert = {remoteCertificateEx}"); } if (!success) { alertToken = CreateFatalHandshakeAlertToken(sslPolicyErrors, chain); } } finally { // At least on Win2k server the chain is found to have dependencies on the original cert context. // So it should be closed first. if (chain != null) { int elementsCount = chain.ChainElements.Count; for (int i = 0; i < elementsCount; i++) { chain.ChainElements[i].Certificate.Dispose(); } chain.Dispose(); } if (remoteCertificateStore != null) { int certCount = remoteCertificateStore.Count; for (int i = 0; i < certCount; i++) { remoteCertificateStore[i].Dispose(); } } remoteCertificateEx?.Dispose(); } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, success); return success; } public ProtocolToken CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); TlsAlertMessage alertMessage; switch (sslPolicyErrors) { case SslPolicyErrors.RemoteCertificateChainErrors: alertMessage = GetAlertMessageFromChain(chain); break; case SslPolicyErrors.RemoteCertificateNameMismatch: alertMessage = TlsAlertMessage.BadCertificate; break; case SslPolicyErrors.RemoteCertificateNotAvailable: default: alertMessage = TlsAlertMessage.CertificateUnknown; break; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"alertMessage:{alertMessage}"); SecurityStatusPal status; status = SslStreamPal.ApplyAlertToken(ref _credentialsHandle, _securityContext, TlsAlertType.Fatal, alertMessage); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); if (status.Exception != null) { ExceptionDispatchInfo.Throw(status.Exception); } return null; } ProtocolToken token = GenerateAlertToken(); if (NetEventSource.IsEnabled) NetEventSource.Exit(this, token); return token; } public ProtocolToken CreateShutdownToken() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); SecurityStatusPal status; status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); if (status.Exception != null) { ExceptionDispatchInfo.Throw(status.Exception); } return null; } ProtocolToken token = GenerateAlertToken(); if (NetEventSource.IsEnabled) NetEventSource.Exit(this, token); return token; } private ProtocolToken GenerateAlertToken() { byte[] nextmsg = null; SecurityStatusPal status; status = GenerateToken(null, 0, 0, ref nextmsg); ProtocolToken token = new ProtocolToken(nextmsg, status); return token; } private static TlsAlertMessage GetAlertMessageFromChain(X509Chain chain) { foreach (X509ChainStatus chainStatus in chain.ChainStatus) { if (chainStatus.Status == X509ChainStatusFlags.NoError) { continue; } if ((chainStatus.Status & (X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.PartialChain | X509ChainStatusFlags.Cyclic)) != 0) { return TlsAlertMessage.UnknownCA; } if ((chainStatus.Status & (X509ChainStatusFlags.Revoked | X509ChainStatusFlags.OfflineRevocation)) != 0) { return TlsAlertMessage.CertificateRevoked; } if ((chainStatus.Status & (X509ChainStatusFlags.CtlNotTimeValid | X509ChainStatusFlags.NotTimeNested | X509ChainStatusFlags.NotTimeValid)) != 0) { return TlsAlertMessage.CertificateExpired; } if ((chainStatus.Status & X509ChainStatusFlags.CtlNotValidForUsage) != 0) { return TlsAlertMessage.UnsupportedCert; } if ((chainStatus.Status & (X509ChainStatusFlags.CtlNotSignatureValid | X509ChainStatusFlags.InvalidExtension | X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.InvalidPolicyConstraints) | X509ChainStatusFlags.NoIssuanceChainPolicy | X509ChainStatusFlags.NotValidForUsage) != 0) { return TlsAlertMessage.BadCertificate; } // All other errors: return TlsAlertMessage.CertificateUnknown; } Debug.Fail("GetAlertMessageFromChain was called but none of the chain elements had errors."); return TlsAlertMessage.BadCertificate; } private void LogCertificateValidation(RemoteCertValidationCallback remoteCertValidationCallback, SslPolicyErrors sslPolicyErrors, bool success, X509Chain chain) { if (!NetEventSource.IsEnabled) return; if (sslPolicyErrors != SslPolicyErrors.None) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_has_errors); if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_not_available); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_name_mismatch); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) { string chainStatusString = "ChainStatus: "; foreach (X509ChainStatus chainStatus in chain.ChainStatus) { chainStatusString += "\t" + chainStatus.StatusInformation; } NetEventSource.Log.RemoteCertificateError(this, chainStatusString); } } if (success) { if (remoteCertValidationCallback != null) { NetEventSource.Log.RemoteCertDeclaredValid(this); } else { NetEventSource.Log.RemoteCertHasNoErrors(this); } } else { if (remoteCertValidationCallback != null) { NetEventSource.Log.RemoteCertUserDeclaredInvalid(this); } } } } // ProtocolToken - used to process and handle the return codes from the SSPI wrapper internal class ProtocolToken { internal SecurityStatusPal Status; internal byte[] Payload; internal int Size; internal bool Failed { get { return ((Status.ErrorCode != SecurityStatusPalErrorCode.OK) && (Status.ErrorCode != SecurityStatusPalErrorCode.ContinueNeeded)); } } internal bool Done { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.OK); } } internal bool Renegotiate { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate); } } internal bool CloseConnection { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.ContextExpired); } } internal ProtocolToken(byte[] data, SecurityStatusPal status) { Status = status; Payload = data; Size = data != null ? data.Length : 0; } internal Exception GetException() { // If it's not done, then there's got to be an error, even if it's // a Handshake message up, and we only have a Warning message. return Done ? null : SslStreamPal.GetException(Status); } #if TRACE_VERBOSE public override string ToString() { return "Status=" + Status.ToString() + ", data size=" + Size; } #endif } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Base data reader class to read external data into the framework /// </summary> public class OTDataReader : Object { public delegate void DataReaderDelegate(OTDataReader reader); protected bool _available = false; /// <summary> /// This delegate is executed when the data becomes available /// </summary> public DataReaderDelegate onDataAvailable = null; /// <summary> /// If true, readers will stay open /// </summary> /// <remarks> /// When you are keeping the readers and register a new reader using OTDataReader.Register(newReader) and the new reader has the same id as /// one that is already available the reader will re-use that already available reader. /// </remarks> static bool keepReaders = false; static List<OTDataReader> all = new List<OTDataReader>(); static Dictionary<string, OTDataReader>lookup = new Dictionary<string, OTDataReader>(); /// <summary> /// Registeres the specified newReader. /// </summary> /// <remarks> /// When OTDataReader.keepReaders is true and you are registering a new reader using OTDataReader.Register(newReader) and the new reader has /// the same id as one that is already available the reader will re-use that already available reader. /// </remarks> public static OTDataReader Register(OTDataReader newReader) { string id = newReader.id; if (lookup.ContainsKey(id) && !keepReaders) lookup[id].Close(); if (!lookup.ContainsKey(id)) { all.Add(newReader); lookup.Add(id,newReader); } return lookup[id]; } public virtual object GetRow (object dsData, int row) { return null; } public virtual object GetData (object dsData, int row, string variable) { return null; } public virtual int RowCount (object dsData) { return 0; } protected void Available() { _available = true; if (onDataAvailable!=null) onDataAvailable(this); } string _id; /// <summary> /// Gets the id of this reader /// </summary> public string id { get { return _id; } } /// <summary> /// Closes all readers /// </summary> static public void CloseAll() { while (all.Count>0) { if (all[0].available) all[0].Close(); else all.RemoveAt(0); } all.Clear(); } /// <summary> /// True if the reader is opened and available /// </summary> public bool available { get { return _available; } } /// <summary> /// Opens the reader /// </summary> public virtual bool Open() { _available = false; return _available; } /// <summary> /// Closes the reader /// </summary> public virtual void Close() { if (lookup.ContainsKey(id)) lookup.Remove(id); if (all.Contains(this)) all.Remove(this); } public OTDataReader(string id) { this._id = id; } protected virtual object OpenDataset(object data, string datasource) { return null; } protected object OpenDataset(string datasource) { return OpenDataset(null,datasource); } /// <summary> /// Loads a dataset /// </summary> /// <remarks> /// This first row of this dataset becomes the active dataset row /// </remarks> public OTDataset Dataset(string datasource) { return new OTDataset(this,OpenDataset(datasource)); } /// <summary> /// Loads a sub dataset within the current row of a dataset /// </summary> /// <remarks> /// This first row of this dataset becomes the active dataset row /// </remarks> public OTDataset Dataset(object data,string datasource) { return new OTDataset(this,OpenDataset(data,datasource)); } } public class OTDataset { object _data; OTDataReader reader; public object data { get { return _data; } } public object currentRow { get { return CurrentRow(); } } /// <summary> /// Gets a (sub)dataset from the current record of this dataset /// </summary> public OTDataset Dataset(string datasource) { return reader.Dataset(this,datasource); } public OTDataset(OTDataReader reader, object data) { this.reader = reader; this._data = data; _row = -1; _bof = _eof = true; if (data!=null) { _row = 0; _bof = _eof = false; } } /// <summary> /// Gets or sets the active row of the current dataset /// </summary> public int rowCount { get { if (data == null) return 0; else return reader.RowCount(data); } } int _row = -1; /// <summary> /// Gets or sets the active row of the current dataset /// </summary> public int row { get { return _row; } set { if (data==null || value<0 || value>=rowCount) throw new System.Exception("Invalid dataset row!"); else { _row = value; _bof = false; _eof = false; } } } /// <summary> /// To first row of current dataset /// </summary> public void First() { _bof = false; _eof = false; row = 0; } /// <summary> /// To last row of current dataset /// </summary> public void Last() { _bof = false; _eof = false; row = rowCount-1; } /// <summary> /// To previous row of current dataset /// </summary> public void Previous() { if (row>1) row--; else { _bof = true; _row = 0; } } /// <summary> /// To next row of current dataset /// </summary> public void Next() { if (row<rowCount-1) row++; else { _eof = true; _row = rowCount-1; } } bool _eof = false; /// <summary> /// True if we got to the last row of the dataset /// </summary> public bool EOF { get { if (data==null) return true; return _eof; } } bool _bof = false; /// <summary> /// True if we got to the first row of the dataset /// </summary> public bool BOF { get { if (data==null) return true; return _bof; } } protected virtual object GetData(string variable) { return null; } object Data(string variable) { return reader.GetData(data,row,variable); } object CurrentRow() { return reader.GetRow(data,row); } /// <summary> /// Gets data as a string from the reader /// </summary> public string AsString(string variable) { try { return System.Convert.ToString(Data(variable)); } catch(System.Exception) { return ""; } } /// <summary> /// Gets data as an integer from the reader /// </summary> public int AsInt(string variable) { try { return System.Convert.ToInt32(Data(variable)); } catch(System.Exception) { return 0; } } /// <summary> /// Gets data as an integer from the reader /// </summary> public float AsFloat(string variable) { try { return System.Convert.ToSingle(Data(variable)); } catch(System.Exception) { return 0.0f; } } /// <summary> /// Gets data as an integer from the reader /// </summary> public bool AsBool(string variable) { try { return System.Convert.ToBoolean(Data(variable)); } catch(System.Exception) { return false; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleans; using Orleans.Concurrency; using Orleans.Runtime; using Raft.Interfaces; namespace Raft.Grains { /// <summary> /// Grain implementation class Server. /// </summary> [Reentrant] public class Server : Grain<int>, IServer { #region fields /// <summary> /// The id of this server. /// </summary> private int ServerId; /// <summary> /// The server role. /// </summary> private Role Role; /// <summary> /// The cluster manager machine. /// </summary> private IClusterManager ClusterManager; /// <summary> /// The servers. /// </summary> private IDictionary<int, IServer> Servers; /// <summary> /// Leader. /// </summary> IServer Leader; /// <summary> /// The election timer of this server. /// </summary> IDisposable ElectionTimer; /// <summary> /// The periodic timer of this server. /// </summary> IDisposable PeriodicTimer; /// <summary> /// Latest term server has seen (initialized to 0 on /// first boot, increases monotonically). /// </summary> int CurrentTerm; /// <summary> /// Candidate that received vote in current term (or null if none). /// </summary> IServer VotedForCandidate; /// <summary> /// Log entries. /// </summary> List<Log> Logs; /// <summary> /// Index of highest log entry known to be committed (initialized /// to 0, increases monotonically). /// </summary> int CommitIndex; /// <summary> /// Index of highest log entry applied to state machine (initialized /// to 0, increases monotonically). /// </summary> int LastApplied; /// <summary> /// For each server, index of the next log entry to send to that /// server (initialized to leader last log index + 1). /// </summary> Dictionary<IServer, int> NextIndex; /// <summary> /// For each server, index of highest log entry known to be replicated /// on server (initialized to 0, increases monotonically). /// </summary> Dictionary<IServer, int> MatchIndex; /// <summary> /// Number of received votes. /// </summary> int VotesReceived; /// <summary> /// The latest client id. /// </summary> int? LatestClientId; /// <summary> /// The latest client command. /// </summary> int? LatestClientCommand; /// <summary> /// Random number generator. /// </summary> private Random Random; /// <summary> /// Safety monitor. /// </summary> private ISafetyMonitor SafetyMonitor; #endregion #region methods public override async Task OnActivateAsync() { Console.WriteLine($"<RaftLog> Server is activating."); if (this.CurrentTerm == 0) { this.Leader = null; this.VotedForCandidate = null; this.Logs = new List<Log>(); this.CommitIndex = 0; this.LastApplied = 0; this.Servers = new Dictionary<int, IServer>(); this.NextIndex = new Dictionary<IServer, int>(); this.MatchIndex = new Dictionary<IServer, int>(); this.Random = new Random(DateTime.Now.Millisecond); } await base.OnActivateAsync(); } public Task Configure(int id, List<int> serverIds, int clusterId) { if (this.Servers.Count == 0) { this.ServerId = id; Console.WriteLine($"<RaftLog> Server {id} is configuring."); foreach (var idx in serverIds) { this.Servers.Add(idx, this.GrainFactory.GetGrain<IServer>(idx)); } this.ClusterManager = this.GrainFactory.GetGrain<IClusterManager>(clusterId); this.BecomeFollower(); } return TaskDone.Done; } private void BecomeFollower() { Console.WriteLine($"<RaftLog> Server {this.ServerId} became FOLLOWER."); this.Role = Role.Follower; this.Leader = null; this.VotesReceived = 0; if (this.ElectionTimer != null) { this.ElectionTimer.Dispose(); } if (this.PeriodicTimer != null) { this.PeriodicTimer.Dispose(); } this.ElectionTimer = this.RegisterTimer(StartLeaderElection, null, TimeSpan.FromSeconds(5 + this.Random.Next(30)), TimeSpan.FromSeconds(5 + this.Random.Next(30))); } private void BecomeCandidate() { Console.WriteLine($"<RaftLog> Server {this.ServerId} became CANDIDATE."); this.Role = Role.Candidate; this.CurrentTerm++; this.VotedForCandidate = this.GrainFactory.GetGrain<IServer>(this.ServerId); this.VotesReceived = 1; Console.WriteLine($"<RaftLog> Candidate {this.ServerId} | term {this.CurrentTerm} " + $"| election votes {this.VotesReceived} | log {this.Logs.Count}."); this.BroadcastVoteRequests(); } private async void BecomeLeader() { Console.WriteLine($"<RaftLog> Server {this.ServerId} became LEADER."); Console.WriteLine($"<RaftLog> Leader {this.ServerId} | term {this.CurrentTerm} " + $"| election votes {this.VotesReceived} | log {this.Logs.Count}."); this.Role = Role.Leader; this.VotesReceived = 0; this.SafetyMonitor = this.GrainFactory.GetGrain<ISafetyMonitor>(100); await this.SafetyMonitor.NotifyLeaderElected(this.CurrentTerm); await this.ClusterManager.NotifyLeaderUpdate(this.ServerId, this.CurrentTerm); var logIndex = this.Logs.Count; var logTerm = this.GetLogTermForIndex(logIndex); this.NextIndex.Clear(); this.MatchIndex.Clear(); foreach (var server in this.Servers) { if (server.Key == this.ServerId) continue; this.NextIndex.Add(server.Value, logIndex + 1); this.MatchIndex.Add(server.Value, 0); } foreach (var server in this.Servers) { if (server.Key == this.ServerId) continue; await server.Value.AppendEntriesRequest(this.CurrentTerm, this.ServerId, logIndex, logTerm, new List<Log>(), this.CommitIndex, -1); } } private void BroadcastVoteRequests() { // BUG: duplicate votes from same follower if (this.PeriodicTimer != null) { this.PeriodicTimer.Dispose(); } this.PeriodicTimer = this.RegisterTimer(RebroadcastVoteRequests, null, TimeSpan.FromSeconds(5 + this.Random.Next(20)), TimeSpan.FromSeconds(5 + this.Random.Next(20))); foreach (var server in this.Servers) { if (server.Key == this.ServerId) continue; var lastLogIndex = this.Logs.Count; var lastLogTerm = this.GetLogTermForIndex(lastLogIndex); Console.WriteLine($"<RaftLog> Server {this.ServerId} sending vote request " + $"to server {server.Key}."); server.Value.VoteRequest(this.CurrentTerm, this.ServerId, lastLogIndex, lastLogTerm); } } public Task VoteRequest(int term, int candidateId, int lastLogIndex, int lastLogTerm) { if (this.Role == Role.Follower) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; } this.ProcessVoteRequest(term, candidateId, lastLogIndex, lastLogTerm); } else if (this.Role == Role.Candidate) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; this.ProcessVoteRequest(term, candidateId, lastLogIndex, lastLogTerm); this.BecomeFollower(); } else { this.ProcessVoteRequest(term, candidateId, lastLogIndex, lastLogTerm); } } else if (this.Role == Role.Leader) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; if (this.LatestClientId != null) { this.ClusterManager.RelayClientRequest(this.LatestClientId.Value, this.LatestClientCommand.Value); } this.ProcessVoteRequest(term, candidateId, lastLogIndex, lastLogTerm); this.BecomeFollower(); } else { this.ProcessVoteRequest(term, candidateId, lastLogIndex, lastLogTerm); } } return TaskDone.Done; } void ProcessVoteRequest(int term, int candidateId, int lastLogIndex, int lastLogTerm) { var candidate = this.GrainFactory.GetGrain<IServer>(candidateId); if (term < this.CurrentTerm || (this.VotedForCandidate != null && this.VotedForCandidate != candidate) || this.Logs.Count > lastLogIndex || this.GetLogTermForIndex(this.Logs.Count) > lastLogTerm) { Console.WriteLine($"<RaftLog> Server {this.ServerId} | term {this.CurrentTerm} " + $"| log {this.Logs.Count} | vote granted {false}."); candidate.VoteResponse(this.CurrentTerm, false); } else { this.VotedForCandidate = candidate; this.Leader = null; Console.WriteLine($"<RaftLog> Server {this.ServerId} | term {this.CurrentTerm} " + $"| log {this.Logs.Count} | vote granted {true}."); candidate.VoteResponse(this.CurrentTerm, true); } } public Task VoteResponse(int term, bool voteGranted) { if (this.Role == Role.Follower) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; } } else if (this.Role == Role.Candidate) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; this.BecomeFollower(); } else if (term != this.CurrentTerm) { new Task(() => { }); } if (voteGranted) { this.VotesReceived++; if (this.VotesReceived >= (this.Servers.Count / 2) + 1) { this.BecomeLeader(); } } } else if (this.Role == Role.Leader) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; if (this.LatestClientId != null) { this.ClusterManager.RelayClientRequest(this.LatestClientId.Value, this.LatestClientCommand.Value); } this.BecomeFollower(); } } return TaskDone.Done; } public Task AppendEntriesRequest(int term, int leaderId, int prevLogIndex, int prevLogTerm, List<Log> entries, int leaderCommit, int clientId) { if (this.Role == Role.Follower) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; } this.AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries, leaderCommit, clientId); } else if (this.Role == Role.Candidate) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; this.AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries, leaderCommit, clientId); this.BecomeFollower(); } else { this.AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries, leaderCommit, clientId); } } else if (this.Role == Role.Leader) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; if (this.LatestClientId != null) { this.ClusterManager.RelayClientRequest(this.LatestClientId.Value, this.LatestClientCommand.Value); } this.AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries, leaderCommit, clientId); this.BecomeFollower(); } } return TaskDone.Done; } private void AppendEntries(int term, int leaderId, int prevLogIndex, int prevLogTerm, List<Log> entries, int leaderCommit, int clientId) { var leader = this.GrainFactory.GetGrain<IServer>(leaderId); if (term < this.CurrentTerm) { Console.WriteLine($"<RaftLog> Server {this.ServerId} | term {this.CurrentTerm} | log " + $"{this.Logs.Count} | last applied {this.LastApplied} | append false (< term)."); leader.AppendEntriesResponse(this.CurrentTerm, false, this.ServerId, clientId); } else { if (prevLogIndex > 0 && (this.Logs.Count < prevLogIndex || this.Logs[prevLogIndex - 1].Term != prevLogTerm)) { Console.WriteLine($"<RaftLog> Server {this.ServerId} | term {this.CurrentTerm} | log " + $"{this.Logs.Count} | last applied {this.LastApplied} | append false (not in log)."); leader.AppendEntriesResponse(this.CurrentTerm, false, this.ServerId, clientId); } else { if (entries.Count > 0) { var currentIndex = prevLogIndex + 1; foreach (var entry in entries) { if (this.Logs.Count < currentIndex) { this.Logs.Add(entry); } else if (this.Logs[currentIndex - 1].Term != entry.Term) { this.Logs.RemoveRange(currentIndex - 1, this.Logs.Count - (currentIndex - 1)); this.Logs.Add(entry); } currentIndex++; } } if (leaderCommit > this.CommitIndex && this.Logs.Count < leaderCommit) { this.CommitIndex = this.Logs.Count; } else if (leaderCommit > this.CommitIndex) { this.CommitIndex = leaderCommit; } if (this.CommitIndex > this.LastApplied) { this.LastApplied++; } Console.WriteLine($"<RaftLog> Server {this.ServerId} | term {this.CurrentTerm} | log " + $"{this.Logs.Count} | entries received {entries.Count} | last applied " + $"{this.LastApplied} | append true."); leader.AppendEntriesResponse(this.CurrentTerm, true, this.ServerId, clientId); } } } public Task AppendEntriesResponse(int term, bool success, int serverId, int clientId) { Console.WriteLine($"<RaftLog> Server {this.ServerId} | term {this.CurrentTerm} " + $"| append response {success}."); if (this.Role == Role.Follower) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; } } else if (this.Role == Role.Candidate) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; this.BecomeFollower(); } } else if (this.Role == Role.Leader) { if (term > this.CurrentTerm) { this.CurrentTerm = term; this.VotedForCandidate = null; if (this.LatestClientId != null) { this.ClusterManager.RelayClientRequest(this.LatestClientId.Value, this.LatestClientCommand.Value); } this.BecomeFollower(); } else if (term != this.CurrentTerm) { return TaskDone.Done; } var server = this.GrainFactory.GetGrain<IServer>(serverId); if (success) { this.NextIndex[server] = this.Logs.Count + 1; this.MatchIndex[server] = this.Logs.Count; this.VotesReceived++; if (clientId >= 0 && this.VotesReceived >= (this.Servers.Count / 2) + 1) { Console.WriteLine($"<RaftLog> Leader {this.ServerId} | term {this.CurrentTerm} " + $"| append votes {this.VotesReceived} | append success."); var commitIndex = this.MatchIndex[server]; if (commitIndex > this.CommitIndex && this.Logs[commitIndex - 1].Term == this.CurrentTerm) { this.CommitIndex = commitIndex; Console.WriteLine($"<RaftLog> Leader {this.ServerId} | term {this.CurrentTerm} " + $"| log {this.Logs.Count} | command {this.Logs[commitIndex - 1].Command}."); } this.VotesReceived = 0; this.LatestClientId = null; this.LatestClientCommand = null; var client = this.GrainFactory.GetGrain<IClient>(clientId); client.ProcessResponse(); } } else { if (this.NextIndex[server] > 1) { this.NextIndex[server] = this.NextIndex[server] - 1; } var logs = this.Logs.GetRange(this.NextIndex[server] - 1, this.Logs.Count - (this.NextIndex[server] - 1)); var prevLogIndex = this.NextIndex[server] - 1; var prevLogTerm = this.GetLogTermForIndex(prevLogIndex); Console.WriteLine($"<RaftLog> Leader {this.ServerId} | term {this.CurrentTerm} | log " + $"{this.Logs.Count} | append votes {this.VotesReceived} " + $"append fail (next idx = {this.NextIndex[server]})."); server.AppendEntriesRequest(this.CurrentTerm, this.ServerId, prevLogIndex, prevLogTerm, logs, this.CommitIndex, clientId); } } return TaskDone.Done; } public Task RedirectClientRequest(int clientId, int command) { if (this.Leader != null) { this.Leader.ProcessClientRequest(clientId, command); } else { this.ClusterManager.RedirectClientRequest(clientId, command); } return TaskDone.Done; } public Task ProcessClientRequest(int clientId, int command) { this.LatestClientId = clientId; this.LatestClientCommand = command; var log = new Log(this.CurrentTerm, command); this.Logs.Add(log); this.BroadcastLastClientRequest(); return TaskDone.Done; } private void BroadcastLastClientRequest() { Console.WriteLine($"<RaftLog> Leader {this.ServerId} sends append requests | term " + $"{this.CurrentTerm} | log {this.Logs.Count}."); var lastLogIndex = this.Logs.Count; this.VotesReceived = 1; foreach (var server in this.Servers) { if (server.Key == this.ServerId) continue; if (lastLogIndex < this.NextIndex[server.Value]) continue; var logs = this.Logs.GetRange(this.NextIndex[server.Value] - 1, this.Logs.Count - (this.NextIndex[server.Value] - 1)); var prevLogIndex = this.NextIndex[server.Value] - 1; var prevLogTerm = this.GetLogTermForIndex(prevLogIndex); server.Value.AppendEntriesRequest(this.CurrentTerm, this.ServerId, prevLogIndex, prevLogTerm, logs, this.CommitIndex, this.LatestClientId.Value); } } private Task StartLeaderElection(object args) { this.BecomeCandidate(); return TaskDone.Done; } private Task RebroadcastVoteRequests(object args) { this.BroadcastVoteRequests(); return TaskDone.Done; } int GetLogTermForIndex(int logIndex) { var logTerm = 0; if (logIndex > 0) { logTerm = this.Logs[logIndex - 1].Term; } return logTerm; } #endregion } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Common { using JetBrains.Annotations; using System; using System.ComponentModel; public static partial class InternalLogger { /// <summary> /// Gets a value indicating whether internal log includes Trace messages. /// </summary> public static bool IsTraceEnabled => IsLogLevelEnabled(LogLevel.Trace); /// <summary> /// Gets a value indicating whether internal log includes Debug messages. /// </summary> public static bool IsDebugEnabled => IsLogLevelEnabled(LogLevel.Debug); /// <summary> /// Gets a value indicating whether internal log includes Info messages. /// </summary> public static bool IsInfoEnabled => IsLogLevelEnabled(LogLevel.Info); /// <summary> /// Gets a value indicating whether internal log includes Warn messages. /// </summary> public static bool IsWarnEnabled => IsLogLevelEnabled(LogLevel.Warn); /// <summary> /// Gets a value indicating whether internal log includes Error messages. /// </summary> public static bool IsErrorEnabled => IsLogLevelEnabled(LogLevel.Error); /// <summary> /// Gets a value indicating whether internal log includes Fatal messages. /// </summary> public static bool IsFatalEnabled => IsLogLevelEnabled(LogLevel.Fatal); /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Trace([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Trace, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <param name="message">Log message.</param> public static void Trace([Localizable(false)] string message) { Write(null, LogLevel.Trace, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Trace. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Trace([Localizable(false)] Func<string> messageFunc) { if (IsTraceEnabled) Write(null, LogLevel.Trace, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Trace level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Trace(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Trace, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Trace<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsTraceEnabled) Log(null, LogLevel.Trace, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Trace<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsTraceEnabled) Log(null, LogLevel.Trace, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Trace<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsTraceEnabled) Log(null, LogLevel.Trace, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Trace level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Trace(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Trace, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Trace level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Trace. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Trace(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsTraceEnabled) Write(ex, LogLevel.Trace, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Debug level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Debug([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Debug, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Debug level. /// </summary> /// <param name="message">Log message.</param> public static void Debug([Localizable(false)] string message) { Write(null, LogLevel.Debug, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Debug level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Debug. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Debug([Localizable(false)] Func<string> messageFunc) { if (IsDebugEnabled) Write(null, LogLevel.Debug, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Debug level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Debug(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Debug, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Debug<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsDebugEnabled) Log(null, LogLevel.Debug, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Debug<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsDebugEnabled) Log(null, LogLevel.Debug, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Debug<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsDebugEnabled) Log(null, LogLevel.Debug, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Debug level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Debug(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Debug, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Debug level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Debug. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Debug(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsDebugEnabled) Write(ex, LogLevel.Debug, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Info level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Info([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Info, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Info level. /// </summary> /// <param name="message">Log message.</param> public static void Info([Localizable(false)] string message) { Write(null, LogLevel.Info, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Info level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Info. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Info([Localizable(false)] Func<string> messageFunc) { if (IsInfoEnabled) Write(null, LogLevel.Info, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Info level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Info(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Info, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Info<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsInfoEnabled) Log(null, LogLevel.Info, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Info<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsInfoEnabled) Log(null, LogLevel.Info, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Info<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsInfoEnabled) Log(null, LogLevel.Info, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Info level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Info(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Info, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Info level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Info. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Info(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsInfoEnabled) Write(ex, LogLevel.Info, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Warn level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Warn([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Warn, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Warn level. /// </summary> /// <param name="message">Log message.</param> public static void Warn([Localizable(false)] string message) { Write(null, LogLevel.Warn, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Warn level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Warn. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Warn([Localizable(false)] Func<string> messageFunc) { if (IsWarnEnabled) Write(null, LogLevel.Warn, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Warn level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Warn(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Warn, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Warn<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsWarnEnabled) Log(null, LogLevel.Warn, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Warn<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsWarnEnabled) Log(null, LogLevel.Warn, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Warn<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsWarnEnabled) Log(null, LogLevel.Warn, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Warn level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Warn(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Warn, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Warn level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Warn. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Warn(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsWarnEnabled) Write(ex, LogLevel.Warn, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Error level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Error([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Error, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Error level. /// </summary> /// <param name="message">Log message.</param> public static void Error([Localizable(false)] string message) { Write(null, LogLevel.Error, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Error level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Error. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Error([Localizable(false)] Func<string> messageFunc) { if (IsErrorEnabled) Write(null, LogLevel.Error, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Error level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Error(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Error, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Error<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsErrorEnabled) Log(null, LogLevel.Error, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Error<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsErrorEnabled) Log(null, LogLevel.Error, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Error<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsErrorEnabled) Log(null, LogLevel.Error, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Error level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Error(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Error, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Error level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Error. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Error(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsErrorEnabled) Write(ex, LogLevel.Error, messageFunc(), null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Fatal level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Fatal([Localizable(false)] string message, params object[] args) { Write(null, LogLevel.Fatal, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Fatal level. /// </summary> /// <param name="message">Log message.</param> public static void Fatal([Localizable(false)] string message) { Write(null, LogLevel.Fatal, message, null); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Fatal level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Fatal. /// </summary> /// <param name="messageFunc">Function that returns the log message.</param> public static void Fatal([Localizable(false)] Func<string> messageFunc) { if (IsFatalEnabled) Write(null, LogLevel.Fatal, messageFunc(), null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Fatal level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> [StringFormatMethod("message")] public static void Fatal(Exception ex, [Localizable(false)] string message, params object[] args) { Write(ex, LogLevel.Fatal, message, args); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> [StringFormatMethod("message")] public static void Fatal<TArgument1>([Localizable(false)] string message, TArgument1 arg0) { if (IsFatalEnabled) Log(null, LogLevel.Fatal, message, arg0); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> [StringFormatMethod("message")] public static void Fatal<TArgument1, TArgument2>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1) { if (IsFatalEnabled) Log(null, LogLevel.Fatal, message, arg0, arg1); } /// <summary> /// Logs the specified message without an <see cref="Exception"/> at the Trace level. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">Message which may include positional parameters.</param> /// <param name="arg0">Argument {0} to the message.</param> /// <param name="arg1">Argument {1} to the message.</param> /// <param name="arg2">Argument {2} to the message.</param> [StringFormatMethod("message")] public static void Fatal<TArgument1, TArgument2, TArgument3>([Localizable(false)] string message, TArgument1 arg0, TArgument2 arg1, TArgument3 arg2) { if (IsFatalEnabled) Log(null, LogLevel.Fatal, message, arg0, arg1, arg2); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Fatal level. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="message">Log message.</param> public static void Fatal(Exception ex, [Localizable(false)] string message) { Write(ex, LogLevel.Fatal, message, null); } /// <summary> /// Logs the specified message with an <see cref="Exception"/> at the Fatal level. /// <paramref name="messageFunc"/> will be only called when logging is enabled for level Fatal. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="messageFunc">Function that returns the log message.</param> public static void Fatal(Exception ex, [Localizable(false)] Func<string> messageFunc) { if (IsFatalEnabled) Write(ex, LogLevel.Fatal, messageFunc(), null); } } }
using VkApi.Wrapper.Objects; using VkApi.Wrapper.Responses; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace VkApi.Wrapper.Methods { public class Messages { private readonly Vkontakte _vkontakte; internal Messages(Vkontakte vkontakte) => _vkontakte = vkontakte; ///<summary> /// Adds a new user to a chat. ///</summary> public Task<BaseOkResponse> AddChatUser(int? chatId = null, int? userId = null, int? visibleMessagesCount = null) { var parameters = new Dictionary<string, string>(); if (chatId != null) parameters.Add("chat_id", chatId.ToApiString()); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (visibleMessagesCount != null) parameters.Add("visible_messages_count", visibleMessagesCount.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.addChatUser", parameters); } ///<summary> /// Allows sending messages from community to the current user. ///</summary> public Task<BaseOkResponse> AllowMessagesFromGroup(int? groupId = null, String key = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (key != null) parameters.Add("key", key.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.allowMessagesFromGroup", parameters); } ///<summary> /// Creates a chat with several participants. ///</summary> public Task<int> CreateChat(int[] userIds = null, String title = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (userIds != null) parameters.Add("user_ids", userIds.ToApiString()); if (title != null) parameters.Add("title", title.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<int>("messages.createChat", parameters); } //TODO: fix /////<summary> ///// Deletes one or more messages. /////</summary> //public Task<MessagesDeleteResponse> Delete(int[] messageIds = null, Boolean? spam = null, int? groupId = null, Boolean? deleteForAll = null) //{ // var parameters = new Dictionary<string, string>(); // if (messageIds != null) // parameters.Add("message_ids", messageIds.ToApiString()); // if (spam != null) // parameters.Add("spam", spam.ToApiString()); // if (groupId != null) // parameters.Add("group_id", groupId.ToApiString()); // if (deleteForAll != null) // parameters.Add("delete_for_all", deleteForAll.ToApiString()); // return _vkontakte.RequestAsync<MessagesDeleteResponse>("messages.delete", parameters); //} ///<summary> /// Deletes a chat's cover picture. ///</summary> public Task<MessagesDeleteChatPhotoResponse> DeleteChatPhoto(int? chatId = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (chatId != null) parameters.Add("chat_id", chatId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesDeleteChatPhotoResponse>("messages.deleteChatPhoto", parameters); } ///<summary> /// Deletes all private messages in a conversation. ///</summary> public Task<MessagesDeleteConversationResponse> DeleteConversation(int? userId = null, int? peerId = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesDeleteConversationResponse>("messages.deleteConversation", parameters); } ///<summary> /// Denies sending message from community to the current user. ///</summary> public Task<BaseOkResponse> DenyMessagesFromGroup(int? groupId = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.denyMessagesFromGroup", parameters); } ///<summary> /// Edits the message. ///</summary> public Task<int> Edit(int? peerId = null, String message = null, double? lat = null, double? @long = null, String attachment = null, Boolean? keepForwardMessages = null, Boolean? keepSnippets = null, int? groupId = null, Boolean? dontParseLinks = null, int? messageId = null) { var parameters = new Dictionary<string, string>(); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (message != null) parameters.Add("message", message.ToApiString()); if (lat != null) parameters.Add("lat", lat.ToApiString()); if (@long != null) parameters.Add("long", @long.ToApiString()); if (attachment != null) parameters.Add("attachment", attachment.ToApiString()); if (keepForwardMessages != null) parameters.Add("keep_forward_messages", keepForwardMessages.ToApiString()); if (keepSnippets != null) parameters.Add("keep_snippets", keepSnippets.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (dontParseLinks != null) parameters.Add("dont_parse_links", dontParseLinks.ToApiString()); if (messageId != null) parameters.Add("message_id", messageId.ToApiString()); return _vkontakte.RequestAsync<int>("messages.edit", parameters); } ///<summary> /// Edits the title of a chat. ///</summary> public Task<BaseOkResponse> EditChat(int? chatId = null, String title = null) { var parameters = new Dictionary<string, string>(); if (chatId != null) parameters.Add("chat_id", chatId.ToApiString()); if (title != null) parameters.Add("title", title.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.editChat", parameters); } ///<summary> /// Returns messages by their IDs within the conversation. ///</summary> public Task<MessagesGetByConversationMessageIdResponse> GetByConversationMessageId(int? peerId = null, int[] conversationMessageIds = null, Boolean? extended = null, UsersFields[] fields = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (conversationMessageIds != null) parameters.Add("conversation_message_ids", conversationMessageIds.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesGetByConversationMessageIdResponse>("messages.getByConversationMessageId", parameters); } ///<summary> /// Returns messages by their IDs. ///</summary> public Task<MessagesGetByIdResponse> GetById(int[] messageIds = null, int? previewLength = null, Boolean? extended = null, UsersFields[] fields = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (messageIds != null) parameters.Add("message_ids", messageIds.ToApiString()); if (previewLength != null) parameters.Add("preview_length", previewLength.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesGetByIdResponse>("messages.getById", parameters); } ///<summary> /// Returns a list of IDs of users participating in a chat. ///</summary> public Task<MessagesGetConversationMembersResponse> GetConversationMembers(int? peerId = null, UsersFields[] fields = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesGetConversationMembersResponse>("messages.getConversationMembers", parameters); } ///<summary> /// Returns a list of the current user's conversations. ///</summary> public Task<MessagesGetConversationsResponse> GetConversations(int? offset = null, int? count = null, String filter = null, Boolean? extended = null, int? startMessageId = null, BaseUserGroupFields[] fields = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (filter != null) parameters.Add("filter", filter.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (startMessageId != null) parameters.Add("start_message_id", startMessageId.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesGetConversationsResponse>("messages.getConversations", parameters); } ///<summary> /// Returns conversations by their IDs ///</summary> public Task<MessagesGetConversationsByIdResponse> GetConversationsById(int[] peerIds = null, Boolean? extended = null, BaseUserGroupFields[] fields = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (peerIds != null) parameters.Add("peer_ids", peerIds.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesGetConversationsByIdResponse>("messages.getConversationsById", parameters); } ///<summary> /// Returns message history for the specified user or group chat. ///</summary> public Task<MessagesGetHistoryResponse> GetHistory(int? offset = null, int? count = null, int? userId = null, int? peerId = null, int? startMessageId = null, int? rev = null, Boolean? extended = null, UsersFields[] fields = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (startMessageId != null) parameters.Add("start_message_id", startMessageId.ToApiString()); if (rev != null) parameters.Add("rev", rev.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesGetHistoryResponse>("messages.getHistory", parameters); } ///<summary> /// Returns media files from the dialog or group chat. ///</summary> public Task<MessagesGetHistoryAttachmentsResponse> GetHistoryAttachments(int? peerId = null, String mediaType = null, String startFrom = null, int? count = null, Boolean? photoSizes = null, UsersFields[] fields = null, int? groupId = null, Boolean? preserveOrder = null, int? maxForwardsLevel = null) { var parameters = new Dictionary<string, string>(); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (mediaType != null) parameters.Add("media_type", mediaType.ToApiString()); if (startFrom != null) parameters.Add("start_from", startFrom.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (photoSizes != null) parameters.Add("photo_sizes", photoSizes.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (preserveOrder != null) parameters.Add("preserve_order", preserveOrder.ToApiString()); if (maxForwardsLevel != null) parameters.Add("max_forwards_level", maxForwardsLevel.ToApiString()); return _vkontakte.RequestAsync<MessagesGetHistoryAttachmentsResponse>("messages.getHistoryAttachments", parameters); } ///<summary> /// Returns a user's current status and date of last activity. ///</summary> public Task<MessagesLastActivity> GetLastActivity(int? userId = null) { var parameters = new Dictionary<string, string>(); if (userId != null) parameters.Add("user_id", userId.ToApiString()); return _vkontakte.RequestAsync<MessagesLastActivity>("messages.getLastActivity", parameters); } ///<summary> /// Returns updates in user's private messages. ///</summary> public Task<MessagesGetLongPollHistoryResponse> GetLongPollHistory(int? ts = null, int? pts = null, int? previewLength = null, Boolean? onlines = null, UsersFields[] fields = null, int? eventsLimit = null, int? msgsLimit = null, int? maxMsgId = null, int? groupId = null, int? lpVersion = null, int? lastN = null, Boolean? credentials = null) { var parameters = new Dictionary<string, string>(); if (ts != null) parameters.Add("ts", ts.ToApiString()); if (pts != null) parameters.Add("pts", pts.ToApiString()); if (previewLength != null) parameters.Add("preview_length", previewLength.ToApiString()); if (onlines != null) parameters.Add("onlines", onlines.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (eventsLimit != null) parameters.Add("events_limit", eventsLimit.ToApiString()); if (msgsLimit != null) parameters.Add("msgs_limit", msgsLimit.ToApiString()); if (maxMsgId != null) parameters.Add("max_msg_id", maxMsgId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (lpVersion != null) parameters.Add("lp_version", lpVersion.ToApiString()); if (lastN != null) parameters.Add("last_n", lastN.ToApiString()); if (credentials != null) parameters.Add("credentials", credentials.ToApiString()); return _vkontakte.RequestAsync<MessagesGetLongPollHistoryResponse>("messages.getLongPollHistory", parameters); } ///<summary> /// Returns data required for connection to a Long Poll server. ///</summary> public Task<MessagesLongpollParams> GetLongPollServer(Boolean? needPts = null, int? groupId = null, int? lpVersion = null) { var parameters = new Dictionary<string, string>(); if (needPts != null) parameters.Add("need_pts", needPts.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (lpVersion != null) parameters.Add("lp_version", lpVersion.ToApiString()); return _vkontakte.RequestAsync<MessagesLongpollParams>("messages.getLongPollServer", parameters); } ///<summary> /// Returns information whether sending messages from the community to current user is allowed. ///</summary> public Task<MessagesIsMessagesFromGroupAllowedResponse> IsMessagesFromGroupAllowed(int? groupId = null, int? userId = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (userId != null) parameters.Add("user_id", userId.ToApiString()); return _vkontakte.RequestAsync<MessagesIsMessagesFromGroupAllowedResponse>("messages.isMessagesFromGroupAllowed", parameters); } ///<summary> /// Marks and unmarks conversations as unanswered. ///</summary> public Task<BaseOkResponse> MarkAsAnsweredConversation(int? peerId = null, Boolean? answered = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (answered != null) parameters.Add("answered", answered.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.markAsAnsweredConversation", parameters); } ///<summary> /// Marks and unmarks messages as important (starred). ///</summary> public Task<int[]> MarkAsImportant(int[] messageIds = null, int? important = null) { var parameters = new Dictionary<string, string>(); if (messageIds != null) parameters.Add("message_ids", messageIds.ToApiString()); if (important != null) parameters.Add("important", important.ToApiString()); return _vkontakte.RequestAsync<int[]>("messages.markAsImportant", parameters); } ///<summary> /// Marks and unmarks conversations as important. ///</summary> public Task<BaseOkResponse> MarkAsImportantConversation(int? peerId = null, Boolean? important = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (important != null) parameters.Add("important", important.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.markAsImportantConversation", parameters); } ///<summary> /// Marks messages as read. ///</summary> public Task<BaseOkResponse> MarkAsRead(int[] messageIds = null, int? peerId = null, int? startMessageId = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (messageIds != null) parameters.Add("message_ids", messageIds.ToApiString()); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (startMessageId != null) parameters.Add("start_message_id", startMessageId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.markAsRead", parameters); } ///<summary> /// Pin a message. ///</summary> public Task<MessagesPinnedMessage> Pin(int? peerId = null, int? messageId = null) { var parameters = new Dictionary<string, string>(); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (messageId != null) parameters.Add("message_id", messageId.ToApiString()); return _vkontakte.RequestAsync<MessagesPinnedMessage>("messages.pin", parameters); } ///<summary> /// Allows the current user to leave a chat or, if the current user started the chat, allows the user to remove another user from the chat. ///</summary> public Task<BaseOkResponse> RemoveChatUser(int? chatId = null, int? userId = null, int? memberId = null) { var parameters = new Dictionary<string, string>(); if (chatId != null) parameters.Add("chat_id", chatId.ToApiString()); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (memberId != null) parameters.Add("member_id", memberId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.removeChatUser", parameters); } ///<summary> /// Restores a deleted message. ///</summary> public Task<BaseOkResponse> Restore(int? messageId = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (messageId != null) parameters.Add("message_id", messageId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.restore", parameters); } ///<summary> /// Returns a list of the current user's private messages that match search criteria. ///</summary> public Task<MessagesSearchResponse> Search(String q = null, int? peerId = null, int? date = null, int? previewLength = null, int? offset = null, int? count = null, Boolean? extended = null, String[] fields = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (q != null) parameters.Add("q", q.ToApiString()); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (date != null) parameters.Add("date", date.ToApiString()); if (previewLength != null) parameters.Add("preview_length", previewLength.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesSearchResponse>("messages.search", parameters); } ///<summary> /// Returns a list of the current user's conversations that match search criteria. ///</summary> public Task<MessagesSearchConversationsResponse> SearchConversations(String q = null, int? count = null, Boolean? extended = null, UsersFields[] fields = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (q != null) parameters.Add("q", q.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<MessagesSearchConversationsResponse>("messages.searchConversations", parameters); } ///<summary> /// Sends a message. ///</summary> public Task<int> Send(int? userId = null, int? randomId = null, int? peerId = null, String domain = null, int? chatId = null, int[] userIds = null, String message = null, double? lat = null, double? @long = null, String attachment = null, int? replyTo = null, int[] forwardMessages = null, int? stickerId = null, int? groupId = null, String keyboard = null, String payload = null, Boolean? dontParseLinks = null, Boolean? disableMentions = null, String intent = null) { var parameters = new Dictionary<string, string>(); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (randomId != null) parameters.Add("random_id", randomId.ToApiString()); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (domain != null) parameters.Add("domain", domain.ToApiString()); if (chatId != null) parameters.Add("chat_id", chatId.ToApiString()); if (userIds != null) parameters.Add("user_ids", userIds.ToApiString()); if (message != null) parameters.Add("message", message.ToApiString()); if (lat != null) parameters.Add("lat", lat.ToApiString()); if (@long != null) parameters.Add("long", @long.ToApiString()); if (attachment != null) parameters.Add("attachment", attachment.ToApiString()); if (replyTo != null) parameters.Add("reply_to", replyTo.ToApiString()); if (forwardMessages != null) parameters.Add("forward_messages", forwardMessages.ToApiString()); if (stickerId != null) parameters.Add("sticker_id", stickerId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (keyboard != null) parameters.Add("keyboard", keyboard.ToApiString()); if (payload != null) parameters.Add("payload", payload.ToApiString()); if (dontParseLinks != null) parameters.Add("dont_parse_links", dontParseLinks.ToApiString()); if (disableMentions != null) parameters.Add("disable_mentions", disableMentions.ToApiString()); if (intent != null) parameters.Add("intent", intent.ToApiString()); return _vkontakte.RequestAsync<int>("messages.send", parameters); } ///<summary> /// Changes the status of a user as typing in a conversation. ///</summary> public Task<BaseOkResponse> SetActivity(int? userId = null, String type = null, int? peerId = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (userId != null) parameters.Add("user_id", userId.ToApiString()); if (type != null) parameters.Add("type", type.ToApiString()); if (peerId != null) parameters.Add("peer_id", peerId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("messages.setActivity", parameters); } ///<summary> /// Sets a previously-uploaded picture as the cover picture of a chat. ///</summary> public Task<MessagesSetChatPhotoResponse> SetChatPhoto(String file = null) { var parameters = new Dictionary<string, string>(); if (file != null) parameters.Add("file", file.ToApiString()); return _vkontakte.RequestAsync<MessagesSetChatPhotoResponse>("messages.setChatPhoto", parameters); } } }