context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections; using System.Collections.Generic; using NUnit.Compatibility; using System.Reflection; using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { /// <summary> /// EqualityAdapter class handles all equality comparisons /// that use an <see cref="IEqualityComparer"/>, <see cref="IEqualityComparer{T}"/> /// or a <see cref="ComparisonAdapter"/>. /// </summary> public abstract class EqualityAdapter { /// <summary> /// Compares two objects, returning true if they are equal /// </summary> public abstract bool AreEqual(object x, object y); /// <summary> /// Returns true if the two objects can be compared by this adapter. /// The base adapter cannot handle IEnumerables except for strings. /// </summary> public virtual bool CanCompare(object x, object y) { return (x is string || !(x is IEnumerable)) && (y is string || !(y is IEnumerable)); } #region Nested IComparer Adapter /// <summary> /// Returns an <see cref="EqualityAdapter"/> that wraps an <see cref="IComparer"/>. /// </summary> public static EqualityAdapter For(IComparer comparer) { return new ComparerAdapter(comparer); } /// <summary> /// <see cref="EqualityAdapter"/> that wraps an <see cref="IComparer"/>. /// </summary> class ComparerAdapter : EqualityAdapter { private readonly IComparer comparer; public ComparerAdapter(IComparer comparer) { this.comparer = comparer; } public override bool AreEqual(object x, object y) { return comparer.Compare(x, y) == 0; } } #endregion #region Nested IEqualityComparer Adapter /// <summary> /// Returns an <see cref="EqualityAdapter"/> that wraps an <see cref="IEqualityComparer"/>. /// </summary> public static EqualityAdapter For(IEqualityComparer comparer) { return new EqualityComparerAdapter(comparer); } class EqualityComparerAdapter : EqualityAdapter { private readonly IEqualityComparer comparer; public EqualityComparerAdapter(IEqualityComparer comparer) { this.comparer = comparer; } public override bool AreEqual(object x, object y) { return comparer.Equals(x, y); } } /// <summary> /// Returns an EqualityAdapter that uses a predicate function for items comparison. /// </summary> /// <typeparam name="TExpected"></typeparam> /// <typeparam name="TActual"></typeparam> /// <param name="comparison"></param> /// <returns></returns> public static EqualityAdapter For<TExpected, TActual>(Func<TExpected, TActual, bool> comparison) { return new PredicateEqualityAdapter<TExpected, TActual>(comparison); } internal sealed class PredicateEqualityAdapter<TActual, TExpected> : EqualityAdapter { private readonly Func<TActual, TExpected, bool> _comparison; /// <summary> /// Returns true if the two objects can be compared by this adapter. /// The base adapter cannot handle IEnumerables except for strings. /// </summary> public override bool CanCompare(object x, object y) { return TypeHelper.CanCast<TExpected>(x) && TypeHelper.CanCast<TActual>(y); } /// <summary> /// Compares two objects, returning true if they are equal /// </summary> public override bool AreEqual(object x, object y) { return _comparison.Invoke((TActual)y, (TExpected)x); } public PredicateEqualityAdapter(Func<TActual, TExpected, bool> comparison) { _comparison = comparison; } } #endregion #region Nested GenericEqualityAdapter<T> abstract class GenericEqualityAdapter<T> : EqualityAdapter { /// <summary> /// Returns true if the two objects can be compared by this adapter. /// Generic adapter requires objects of the specified type. /// </summary> public override bool CanCompare(object x, object y) { return TypeHelper.CanCast<T>(x) && TypeHelper.CanCast<T>(y); } protected void CastOrThrow(object x, object y, out T xValue, out T yValue) { if (!TypeHelper.TryCast(x, out xValue)) throw new ArgumentException($"Cannot compare {x?.ToString() ?? "null"}"); if (!TypeHelper.TryCast(y, out yValue)) throw new ArgumentException($"Cannot compare {y?.ToString() ?? "null"}"); } } #endregion #region Nested IEqualityComparer<T> Adapter /// <summary> /// Returns an <see cref="EqualityAdapter"/> that wraps an <see cref="IEqualityComparer{T}"/>. /// </summary> public static EqualityAdapter For<T>(IEqualityComparer<T> comparer) { return new EqualityComparerAdapter<T>(comparer); } class EqualityComparerAdapter<T> : GenericEqualityAdapter<T> { private readonly IEqualityComparer<T> comparer; public EqualityComparerAdapter(IEqualityComparer<T> comparer) { this.comparer = comparer; } public override bool AreEqual(object x, object y) { CastOrThrow(x, y, out var xValue, out var yValue); return comparer.Equals(xValue, yValue); } } #endregion #region Nested IComparer<T> Adapter /// <summary> /// Returns an <see cref="EqualityAdapter"/> that wraps an <see cref="IComparer{T}"/>. /// </summary> public static EqualityAdapter For<T>(IComparer<T> comparer) { return new ComparerAdapter<T>(comparer); } /// <summary> /// <see cref="EqualityAdapter"/> that wraps an <see cref="IComparer"/>. /// </summary> class ComparerAdapter<T> : GenericEqualityAdapter<T> { private readonly IComparer<T> comparer; public ComparerAdapter(IComparer<T> comparer) { this.comparer = comparer; } public override bool AreEqual(object x, object y) { CastOrThrow(x, y, out var xValue, out var yValue); return comparer.Compare(xValue, yValue) == 0; } } #endregion #region Nested Comparison<T> Adapter /// <summary> /// Returns an <see cref="EqualityAdapter"/> that wraps a <see cref="Comparison{T}"/>. /// </summary> public static EqualityAdapter For<T>(Comparison<T> comparer) { return new ComparisonAdapter<T>(comparer); } class ComparisonAdapter<T> : GenericEqualityAdapter<T> { private readonly Comparison<T> comparer; public ComparisonAdapter(Comparison<T> comparer) { this.comparer = comparer; } public override bool AreEqual(object x, object y) { CastOrThrow(x, y, out var xValue, out var yValue); return comparer.Invoke(xValue, yValue) == 0; } } #endregion } }
using System; using System.Collections.Generic; using UnityEngine; using MessageStream2; using DarkMultiPlayerCommon; namespace DarkMultiPlayer { public class ScreenshotWorker { //Height setting public int screenshotHeight = 720; //GUI stuff private bool initialized; private bool isWindowLocked = false; public bool workerEnabled; private GUIStyle windowStyle; private GUILayoutOption[] windowLayoutOption; private GUIStyle buttonStyle; private GUIStyle highlightStyle; private GUILayoutOption[] fixedButtonSizeOption; private GUIStyle scrollStyle; public bool display; private bool safeDisplay; private Rect windowRect; private Rect moveRect; private Vector2 scrollPos; //State tracking public bool screenshotButtonHighlighted; List<string> highlightedPlayers = new List<string>(); private string selectedPlayer = ""; private string safeSelectedPlayer = ""; private Dictionary<string, Texture2D> screenshots = new Dictionary<string, Texture2D>(); private bool uploadEventHandled = true; public bool uploadScreenshot = false; private float lastScreenshotSend; private Queue<ScreenshotEntry> newScreenshotQueue = new Queue<ScreenshotEntry>(); private Queue<ScreenshotWatchEntry> newScreenshotWatchQueue = new Queue<ScreenshotWatchEntry>(); private Queue<string> newScreenshotNotifiyQueue = new Queue<string>(); private Dictionary<string, string> watchPlayers = new Dictionary<string, string>(); //Screenshot uploading message private bool displayScreenshotUploadingMessage = false; public bool finishedUploadingScreenshot = false; public string downloadingScreenshotFromPlayer; private float lastScreenshotMessageCheck; ScreenMessage screenshotUploadMessage; ScreenMessage screenshotDownloadMessage; //delay the screenshot message until we've taken a screenshot public bool screenshotTaken; //const private const float MIN_WINDOW_HEIGHT = 200; private const float MIN_WINDOW_WIDTH = 150; private const float BUTTON_WIDTH = 150; private const float SCREENSHOT_MESSAGE_CHECK_INTERVAL = .2f; private const float MIN_SCREENSHOT_SEND_INTERVAL = 3f; //Services private DMPGame dmpGame; private Settings dmpSettings; private ChatWorker chatWorker; private NetworkWorker networkWorker; private PlayerStatusWorker playerStatusWorker; public ScreenshotWorker(DMPGame dmpGame, Settings dmpSettings, ChatWorker chatWorker, NetworkWorker networkWorker, PlayerStatusWorker playerStatusWorker) { this.dmpGame = dmpGame; this.dmpSettings = dmpSettings; this.chatWorker = chatWorker; this.networkWorker = networkWorker; this.playerStatusWorker = playerStatusWorker; dmpGame.updateEvent.Add(Update); dmpGame.drawEvent.Add(Draw); } private void InitGUI() { windowRect = new Rect(50, (Screen.height / 2f) - (MIN_WINDOW_HEIGHT / 2f), MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT); moveRect = new Rect(0, 0, 10000, 20); windowLayoutOption = new GUILayoutOption[4]; windowLayoutOption[0] = GUILayout.MinWidth(MIN_WINDOW_WIDTH); windowLayoutOption[1] = GUILayout.MinHeight(MIN_WINDOW_HEIGHT); windowLayoutOption[2] = GUILayout.ExpandWidth(true); windowLayoutOption[3] = GUILayout.ExpandHeight(true); windowStyle = new GUIStyle(GUI.skin.window); buttonStyle = new GUIStyle(GUI.skin.button); highlightStyle = new GUIStyle(GUI.skin.button); highlightStyle.normal.textColor = Color.red; highlightStyle.active.textColor = Color.red; highlightStyle.hover.textColor = Color.red; fixedButtonSizeOption = new GUILayoutOption[2]; fixedButtonSizeOption[0] = GUILayout.Width(BUTTON_WIDTH); fixedButtonSizeOption[1] = GUILayout.ExpandWidth(true); scrollStyle = new GUIStyle(GUI.skin.scrollView); scrollPos = new Vector2(0, 0); } private void Update() { safeDisplay = display; if (workerEnabled) { while (newScreenshotNotifiyQueue.Count > 0) { string notifyPlayer = newScreenshotNotifiyQueue.Dequeue(); if (!display) { screenshotButtonHighlighted = true; } if (selectedPlayer != notifyPlayer) { if (!highlightedPlayers.Contains(notifyPlayer)) { highlightedPlayers.Add(notifyPlayer); } } chatWorker.QueueChannelMessage("Server", "", notifyPlayer + " shared screenshot"); } //Update highlights if (screenshotButtonHighlighted && display) { screenshotButtonHighlighted = false; } if (highlightedPlayers.Contains(selectedPlayer)) { highlightedPlayers.Remove(selectedPlayer); } while (newScreenshotQueue.Count > 0) { ScreenshotEntry se = newScreenshotQueue.Dequeue(); Texture2D screenshotTexture = new Texture2D(4, 4, TextureFormat.RGB24, false, true); if (screenshotTexture.LoadImage(se.screenshotData)) { screenshotTexture.Apply(); //Make sure screenshots aren't bigger than 2/3rds of the screen. ResizeTextureIfNeeded(ref screenshotTexture); //Save the texture in memory screenshots[se.fromPlayer] = screenshotTexture; DarkLog.Debug("Loaded screenshot from " + se.fromPlayer); } else { DarkLog.Debug("Error loading screenshot from " + se.fromPlayer); } } while (newScreenshotWatchQueue.Count > 0) { ScreenshotWatchEntry swe = newScreenshotWatchQueue.Dequeue(); if (swe.watchPlayer != "") { watchPlayers[swe.fromPlayer] = swe.watchPlayer; } else { if (watchPlayers.ContainsKey(swe.fromPlayer)) { watchPlayers.Remove(swe.fromPlayer); } } } if (safeSelectedPlayer != selectedPlayer) { windowRect.height = 0; windowRect.width = 0; safeSelectedPlayer = selectedPlayer; WatchPlayer(selectedPlayer); } if (Input.GetKey(dmpSettings.screenshotKey)) { uploadEventHandled = false; } if (!uploadEventHandled) { uploadEventHandled = true; if ((Client.realtimeSinceStartup - lastScreenshotSend) > MIN_SCREENSHOT_SEND_INTERVAL) { lastScreenshotSend = Client.realtimeSinceStartup; screenshotTaken = false; finishedUploadingScreenshot = false; uploadScreenshot = true; displayScreenshotUploadingMessage = true; } } if ((Client.realtimeSinceStartup - lastScreenshotMessageCheck) > SCREENSHOT_MESSAGE_CHECK_INTERVAL) { if (screenshotTaken && displayScreenshotUploadingMessage) { lastScreenshotMessageCheck = Client.realtimeSinceStartup; if (screenshotUploadMessage != null) { screenshotUploadMessage.duration = 0f; } if (finishedUploadingScreenshot) { displayScreenshotUploadingMessage = false; screenshotUploadMessage = ScreenMessages.PostScreenMessage("Screenshot uploaded!", 2f, ScreenMessageStyle.UPPER_CENTER); } else { screenshotUploadMessage = ScreenMessages.PostScreenMessage("Uploading screenshot...", 1f, ScreenMessageStyle.UPPER_CENTER); } } if (downloadingScreenshotFromPlayer != null) { if (screenshotDownloadMessage != null) { screenshotDownloadMessage.duration = 0f; } screenshotDownloadMessage = ScreenMessages.PostScreenMessage("Downloading screenshot...", 1f, ScreenMessageStyle.UPPER_CENTER); } } if (downloadingScreenshotFromPlayer == null && screenshotDownloadMessage != null) { screenshotDownloadMessage.duration = 0f; screenshotDownloadMessage = null; } } } private void ResizeTextureIfNeeded(ref Texture2D screenshotTexture) { //Make sure screenshots aren't bigger than 2/3rds of the screen. int resizeWidth = (int)(Screen.width * .66); int resizeHeight = (int)(Screen.height * .66); if (screenshotTexture.width > resizeWidth || screenshotTexture.height > resizeHeight) { RenderTexture renderTexture = new RenderTexture(resizeWidth, resizeHeight, 24); renderTexture.useMipMap = false; Graphics.Blit(screenshotTexture, renderTexture); RenderTexture.active = renderTexture; Texture2D resizeTexture = new Texture2D(resizeWidth, resizeHeight, TextureFormat.RGB24, false); resizeTexture.ReadPixels(new Rect(0, 0, resizeWidth, resizeHeight), 0, 0); resizeTexture.Apply(); screenshotTexture = resizeTexture; RenderTexture.active = null; } } private void Draw() { if (!initialized) { initialized = true; InitGUI(); } if (safeDisplay) { windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6710 + Client.WINDOW_OFFSET, windowRect, DrawContent, "Screenshots", windowStyle, windowLayoutOption)); } CheckWindowLock(); } private void DrawContent(int windowID) { GUI.DragWindow(moveRect); GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); scrollPos = GUILayout.BeginScrollView(scrollPos, scrollStyle, fixedButtonSizeOption); DrawPlayerButton(dmpSettings.playerName); foreach (PlayerStatus player in playerStatusWorker.playerStatusList) { DrawPlayerButton(player.playerName); } GUILayout.EndScrollView(); GUILayout.FlexibleSpace(); GUI.enabled = ((Client.realtimeSinceStartup - lastScreenshotSend) > MIN_SCREENSHOT_SEND_INTERVAL); if (GUILayout.Button("Upload (" + dmpSettings.screenshotKey.ToString() + ")", buttonStyle)) { uploadEventHandled = false; } GUI.enabled = true; GUILayout.EndVertical(); if (safeSelectedPlayer != "") { if (screenshots.ContainsKey(safeSelectedPlayer)) { GUILayout.Box(screenshots[safeSelectedPlayer]); } } GUILayout.EndHorizontal(); } private void CheckWindowLock() { if (!dmpGame.running) { RemoveWindowLock(); return; } if (HighLogic.LoadedSceneIsFlight) { RemoveWindowLock(); return; } if (safeDisplay) { Vector2 mousePos = Input.mousePosition; mousePos.y = Screen.height - mousePos.y; bool shouldLock = windowRect.Contains(mousePos); if (shouldLock && !isWindowLocked) { InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, "DMP_ScreenshotLock"); isWindowLocked = true; } if (!shouldLock && isWindowLocked) { RemoveWindowLock(); } } if (!safeDisplay && isWindowLocked) { RemoveWindowLock(); } } private void RemoveWindowLock() { if (isWindowLocked) { isWindowLocked = false; InputLockManager.RemoveControlLock("DMP_ScreenshotLock"); } } private void DrawPlayerButton(string playerName) { GUIStyle playerButtonStyle = buttonStyle; if (highlightedPlayers.Contains(playerName)) { playerButtonStyle = highlightStyle; } bool newValue = GUILayout.Toggle(safeSelectedPlayer == playerName, playerName, playerButtonStyle); if (newValue && (safeSelectedPlayer != playerName)) { selectedPlayer = playerName; } if (!newValue && (safeSelectedPlayer == playerName)) { selectedPlayer = ""; } } private void WatchPlayer(string playerName) { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ScreenshotMessageType.WATCH); mw.Write<string>(dmpSettings.playerName); mw.Write<string>(playerName); networkWorker.SendScreenshotMessage(mw.GetMessageBytes()); } } //Called from main due to WaitForEndOfFrame timing. public void SendScreenshot() { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ScreenshotMessageType.SCREENSHOT); mw.Write<string>(dmpSettings.playerName); mw.Write<byte[]>(GetScreenshotBytes()); networkWorker.SendScreenshotMessage(mw.GetMessageBytes()); } } //Adapted from KMP. private byte[] GetScreenshotBytes() { int screenshotWidth = (int)(Screen.width * (screenshotHeight / (float)Screen.height)); //Read the screen pixels into a texture Texture2D fullScreenTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); fullScreenTexture.filterMode = FilterMode.Bilinear; fullScreenTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false); fullScreenTexture.Apply(); RenderTexture renderTexture = new RenderTexture(screenshotWidth, screenshotHeight, 24); renderTexture.useMipMap = false; Graphics.Blit(fullScreenTexture, renderTexture); //Blit the screen texture to a render texture RenderTexture.active = renderTexture; //Read the pixels from the render texture into a Texture2D Texture2D resizedTexture = new Texture2D(screenshotWidth, screenshotHeight, TextureFormat.RGB24, false); Texture2D ourTexture = new Texture2D(screenshotWidth, screenshotHeight, TextureFormat.RGB24, false); resizedTexture.ReadPixels(new Rect(0, 0, screenshotWidth, screenshotHeight), 0, 0); resizedTexture.Apply(); //Save a copy locally in case we need to resize it. ourTexture.ReadPixels(new Rect(0, 0, screenshotWidth, screenshotHeight), 0, 0); ourTexture.Apply(); ResizeTextureIfNeeded(ref ourTexture); //Save our texture in memory. screenshots[dmpSettings.playerName] = ourTexture; RenderTexture.active = null; return resizedTexture.EncodeToPNG(); } public void QueueNewScreenshot(string fromPlayer, byte[] screenshotData) { downloadingScreenshotFromPlayer = null; ScreenshotEntry se = new ScreenshotEntry(); se.fromPlayer = fromPlayer; se.screenshotData = screenshotData; newScreenshotQueue.Enqueue(se); } public void QueueNewScreenshotWatch(string fromPlayer, string watchPlayer) { ScreenshotWatchEntry swe = new ScreenshotWatchEntry(); swe.fromPlayer = fromPlayer; swe.watchPlayer = watchPlayer; newScreenshotWatchQueue.Enqueue(swe); } public void QueueNewNotify(string fromPlayer) { newScreenshotNotifiyQueue.Enqueue(fromPlayer); } public void Stop() { workerEnabled = false; RemoveWindowLock(); dmpGame.updateEvent.Remove(Update); dmpGame.drawEvent.Remove(Draw); } } } class ScreenshotEntry { public string fromPlayer; public byte[] screenshotData; } class ScreenshotWatchEntry { public string fromPlayer; public string watchPlayer; }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Tests task result. /// </summary> public class TaskResultTest : AbstractTaskTest { /** Grid name. */ private static volatile string _gridName; /// <summary> /// Constructor. /// </summary> public TaskResultTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="forked">Fork flag.</param> protected TaskResultTest(bool forked) : base(forked) { } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultInt() { TestTask<int> task = new TestTask<int>(); int res = Grid1.GetCompute().Execute(task, new Tuple<bool, int>(true, 10)); Assert.AreEqual(10, res); res = Grid1.GetCompute().Execute(task, new Tuple<bool, int>(false, 11)); Assert.AreEqual(11, res); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultLong() { TestTask<long> task = new TestTask<long>(); long res = Grid1.GetCompute().Execute(task, new Tuple<bool, long>(true, 10000000000)); Assert.AreEqual(10000000000, res); res = Grid1.GetCompute().Execute(task, new Tuple<bool, long>(false, 10000000001)); Assert.AreEqual(10000000001, res); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultFloat() { TestTask<float> task = new TestTask<float>(); float res = Grid1.GetCompute().Execute(task, new Tuple<bool, float>(true, 1.1f)); Assert.AreEqual(1.1f, res); res = Grid1.GetCompute().Execute(task, new Tuple<bool, float>(false, -1.1f)); Assert.AreEqual(-1.1f, res); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultBinarizable() { TestTask<BinarizableResult> task = new TestTask<BinarizableResult>(); BinarizableResult val = new BinarizableResult(100); BinarizableResult res = Grid1.GetCompute().Execute(task, new Tuple<bool, BinarizableResult>(true, val)); Assert.AreEqual(val.Val, res.Val); val.Val = 101; res = Grid1.GetCompute().Execute(task, new Tuple<bool, BinarizableResult>(false, val)); Assert.AreEqual(val.Val, res.Val); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultSerializable() { TestTask<SerializableResult> task = new TestTask<SerializableResult>(); SerializableResult val = new SerializableResult(100); SerializableResult res = Grid1.GetCompute().Execute(task, new Tuple<bool, SerializableResult>(true, val)); Assert.AreEqual(val.Val, res.Val); val.Val = 101; res = Grid1.GetCompute().Execute(task, new Tuple<bool, SerializableResult>(false, val)); Assert.AreEqual(val.Val, res.Val); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultLarge() { TestTask<byte[]> task = new TestTask<byte[]>(); byte[] res = Grid1.GetCompute().Execute(task, new Tuple<bool, byte[]>(true, new byte[100 * 1024])); Assert.AreEqual(100 * 1024, res.Length); res = Grid1.GetCompute().Execute(task, new Tuple<bool, byte[]>(false, new byte[101 * 1024])); Assert.AreEqual(101 * 1024, res.Length); } [Test] public void TestOutFuncResultPrimitive1() { ICollection<int> res = Grid1.GetCompute().Broadcast(new BinarizableOutFunc()); Assert.AreEqual(2, res.Count); foreach (int r in res) Assert.AreEqual(10, r); } [Test] public void TestOutFuncResultPrimitive2() { ICollection<int> res = Grid1.GetCompute().Broadcast(new SerializableOutFunc()); Assert.AreEqual(2, res.Count); foreach (int r in res) Assert.AreEqual(10, r); } [Test] public void TestFuncResultPrimitive1() { ICollection<int> res = Grid1.GetCompute().Broadcast(new BinarizableFunc(), 10); Assert.AreEqual(2, res.Count); foreach (int r in res) Assert.AreEqual(11, r); } [Test] public void TestFuncResultPrimitive2() { ICollection<int> res = Grid1.GetCompute().Broadcast(new SerializableFunc(), 10); Assert.AreEqual(2, res.Count); foreach (int r in res) Assert.AreEqual(11, r); } interface IUserInterface<in T, out TR> { TR Invoke(T arg); } /// <summary> /// Test function. /// </summary> public class BinarizableFunc : IComputeFunc<int, int>, IUserInterface<int, int> { int IComputeFunc<int, int>.Invoke(int arg) { return arg + 1; } int IUserInterface<int, int>.Invoke(int arg) { // Same signature as IComputeFunc<int, int>, but from different interface throw new Exception("Invalid method"); } public int Invoke(int arg) { // Same signature as IComputeFunc<int, int>, // but due to explicit interface implementation this is a wrong method throw new Exception("Invalid method"); } } /// <summary> /// Test function. /// </summary> [Serializable] public class SerializableFunc : IComputeFunc<int, int> { public int Invoke(int arg) { return arg + 1; } } /// <summary> /// Test function. /// </summary> public class BinarizableOutFunc : IComputeFunc<int> { public int Invoke() { return 10; } } /// <summary> /// Test function. /// </summary> [Serializable] public class SerializableOutFunc : IComputeFunc<int> { public int Invoke() { return 10; } } /// <summary> /// Test task. /// </summary> public class TestTask<T> : ComputeTaskAdapter<Tuple<bool, T>, T, T> { /** <inheritDoc /> */ override public IDictionary<IComputeJob<T>, IClusterNode> Map(IList<IClusterNode> subgrid, Tuple<bool, T> arg) { _gridName = null; Assert.AreEqual(2, subgrid.Count); bool local = arg.Item1; T res = arg.Item2; var jobs = new Dictionary<IComputeJob<T>, IClusterNode>(); IComputeJob<T> job; if (res is BinarizableResult) { TestBinarizableJob job0 = new TestBinarizableJob(); job0.SetArguments(res); job = (IComputeJob<T>) job0; } else { TestJob<T> job0 = new TestJob<T>(); job0.SetArguments(res); job = job0; } foreach (IClusterNode node in subgrid) { bool add = local ? node.IsLocal : !node.IsLocal; if (add) { jobs.Add(job, node); break; } } Assert.AreEqual(1, jobs.Count); return jobs; } /** <inheritDoc /> */ override public T Reduce(IList<IComputeJobResult<T>> results) { Assert.AreEqual(1, results.Count); var res = results[0]; Assert.IsNull(res.Exception); Assert.IsFalse(res.Cancelled); Assert.IsNotNull(_gridName); Assert.AreEqual(GridId(_gridName), res.NodeId); var job = res.Job; Assert.IsNotNull(job); return res.Data; } } private static Guid GridId(string gridName) { if (gridName.Equals(Grid1Name)) return Ignition.GetIgnite(Grid1Name).GetCluster().GetLocalNode().Id; if (gridName.Equals(Grid2Name)) return Ignition.GetIgnite(Grid2Name).GetCluster().GetLocalNode().Id; if (gridName.Equals(Grid3Name)) return Ignition.GetIgnite(Grid3Name).GetCluster().GetLocalNode().Id; Assert.Fail("Failed to find grid " + gridName); return new Guid(); } /// <summary> /// /// </summary> class BinarizableResult { /** */ public int Val; public BinarizableResult(int val) { Val = val; } } /// <summary> /// /// </summary> [Serializable] class SerializableResult { /** */ public int Val; public SerializableResult(int val) { Val = val; } } /// <summary> /// /// </summary> [Serializable] class TestJob<T> : ComputeJobAdapter<T> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ override public T Execute() { Assert.IsNotNull(_grid); _gridName = _grid.Name; T res = GetArgument<T>(0); return res; } } /// <summary> /// /// </summary> class TestBinarizableJob : ComputeJobAdapter<BinarizableResult> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ override public BinarizableResult Execute() { Assert.IsNotNull(_grid); _gridName = _grid.Name; BinarizableResult res = GetArgument<BinarizableResult>(0); return res; } } } }
// // 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 // // 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 Microsoft.PackageManagement.Internal.Utility.Plugin { using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Extensions; internal static class DynamicTypeExtensions { private static readonly Type[] _emptyTypes = { }; private static MethodInfo _asMethod; private static MethodInfo AsMethod { get { var methods = typeof(DynamicInterfaceExtensions).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (_asMethod == null) { _asMethod = methods.FirstOrDefault(method => String.Equals(method.Name, "As", StringComparison.OrdinalIgnoreCase) && method.GetParameterTypes().Count() == 1 && method.GetParameterTypes().First() == typeof(Object)); } return _asMethod; } } internal static void OverrideInitializeLifetimeService(this TypeBuilder dynamicType) { // add override of InitLifetimeService so this object doesn't fall prey to timeouts var il = dynamicType.DefineMethod("InitializeLifetimeService", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, CallingConventions.HasThis, typeof(object), _emptyTypes).GetILGenerator(); il.LoadNull(); il.Return(); } internal static void GenerateIsMethodImplemented(this TypeBuilder dynamicType) { // special case -- the IsMethodImplemented method can give the interface owner information as to // which methods are actually implemented. var implementedMethodsField = dynamicType.DefineField("__implementedMethods", typeof(HashSet<string>), FieldAttributes.Private); var il = dynamicType.CreateMethod("IsMethodImplemented", typeof(bool), typeof(string)); il.LoadThis(); il.LoadField(implementedMethodsField); il.LoadArgument(1); il.CallVirtual(typeof(HashSet<string>).GetMethod("Contains")); il.Return(); } internal static void GenerateMethodForDirectCall(this TypeBuilder dynamicType, MethodInfo method, FieldBuilder backingField, MethodInfo instanceMethod, MethodInfo onUnhandledException) { var il = dynamicType.CreateMethod(method); // the target object has a method that matches. // let's use that. var hasReturn = method.ReturnType != typeof(void); var hasOue = onUnhandledException != null; var exit = il.DefineLabel(); var setDefaultReturn = il.DefineLabel(); var ret = hasReturn ? il.DeclareLocal(method.ReturnType) : null; var exc = hasOue ? il.DeclareLocal(typeof(Exception)) : null; il.BeginExceptionBlock(); il.LoadThis(); il.LoadField(backingField); var imTypes = instanceMethod.GetParameterTypes(); var dmTypes = method.GetParameterTypes(); for (var i = 0; i < dmTypes.Length; i++) { il.LoadArgument(i + 1); // if the types are assignable, if (imTypes[i].IsAssignableFrom(dmTypes[i])) { // it assigns straight across. } else { // it doesn't, we'll ducktype it. if (dmTypes[i].GetTypeInfo().IsPrimitive) { // box it first? il.Emit(OpCodes.Box, dmTypes[i]); } il.Call(AsMethod.MakeGenericMethod(imTypes[i])); } } // call the actual method implementation il.CallVirtual(instanceMethod); if (hasReturn) { // copy the return value in the return // check to see if we need to ducktype the return value here. if (method.ReturnType.IsAssignableFrom(instanceMethod.ReturnType)) { // it can store it directly. } else { // it doesn't assign directly, let's ducktype it. if (instanceMethod.ReturnType.GetTypeInfo().IsPrimitive) { il.Emit(OpCodes.Box, instanceMethod.ReturnType); } il.Call(AsMethod.MakeGenericMethod(method.ReturnType)); } il.StoreLocation(ret); } else { // this method isn't returning anything. if (instanceMethod.ReturnType != typeof(void)) { // pop the return value beacuse the generated method is void and the // method we called actually gave us a result. il.Emit(OpCodes.Pop); } } il.Emit(OpCodes.Leave_S, exit); il.BeginCatchBlock(typeof(Exception)); if (hasOue) { // we're going to call the handler. il.StoreLocation(exc.LocalIndex); il.LoadArgument(0); il.Emit(OpCodes.Ldstr, instanceMethod.ToSignatureString()); il.LoadLocation(exc.LocalIndex); il.CallVirtual(onUnhandledException); il.Emit(OpCodes.Leave_S, setDefaultReturn); } else { // suppress the exception quietly il.Emit(OpCodes.Pop); il.Emit(OpCodes.Leave_S, setDefaultReturn); } il.EndExceptionBlock(); // if we can't return the appropriate value, we're returning default(T) il.MarkLabel(setDefaultReturn); SetDefaultReturnValue(il, method.ReturnType); il.Return(); // looks like we're returning the value that we got back from the implementation. il.MarkLabel(exit); if (hasReturn) { il.LoadLocation(ret.LocalIndex); } il.Return(); } internal static ILGenerator CreateMethod(this TypeBuilder dynamicType, MethodInfo method) { return dynamicType.CreateMethod(method.Name, method.ReturnType, method.GetParameterTypes()); } internal static ILGenerator CreateMethod(this TypeBuilder dynamicType, string methodName, Type returnType, params Type[] parameterTypes) { var methodBuilder = dynamicType.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, returnType, parameterTypes); return methodBuilder.GetILGenerator(); } internal static void GenerateMethodForDelegateCall(this TypeBuilder dynamicType, MethodInfo method, FieldBuilder field, MethodInfo onUnhandledException) { var il = dynamicType.CreateMethod(method); // the target object has a property or field that matches the signature we're looking for. // let's use that. var delegateType = WrappedDelegate.GetFuncOrActionType(method.GetParameterTypes(), method.ReturnType); il.LoadThis(); il.LoadField(field); for (var i = 0; i < method.GetParameterTypes().Length; i++) { il.LoadArgument(i + 1); } il.CallVirtual(delegateType.GetMethod("Invoke")); il.Return(); } internal static void GenerateStubMethod(this TypeBuilder dynamicType, MethodInfo method) { var il = dynamicType.CreateMethod(method); do { if (method.ReturnType != typeof(void)) { if (method.ReturnType.GetTypeInfo().IsPrimitive) { if (method.ReturnType == typeof(double)) { il.LoadDouble(0.0); break; } if (method.ReturnType == typeof(float)) { il.LoadFloat(0.0F); break; } il.LoadInt32(0); if (method.ReturnType == typeof(long) || method.ReturnType == typeof(ulong)) { il.ConvertToInt64(); } break; } if (method.ReturnType.GetTypeInfo().IsEnum) { // should really find out the actual default? il.LoadInt32(0); break; } if (method.ReturnType.GetTypeInfo().IsValueType) { var result = il.DeclareLocal(method.ReturnType); il.LoadLocalAddress(result); il.InitObject(method.ReturnType); il.LoadLocation(0); break; } il.LoadNull(); } } while (false); il.Return(); } private static void SetDefaultReturnValue(ILGenerator il, Type returnType) { if (returnType != typeof(void)) { if (returnType.GetTypeInfo().IsPrimitive) { if (returnType == typeof(double)) { il.LoadDouble(0.0); return; } if (returnType == typeof(float)) { il.LoadFloat(0.0F); return; } il.LoadInt32(0); if (returnType == typeof(long) || returnType == typeof(ulong)) { il.ConvertToInt64(); } return; } if (returnType.GetTypeInfo().IsEnum) { // should really find out the actual default? il.LoadInt32(0); return; } if (returnType.GetTypeInfo().IsValueType) { var result = il.DeclareLocal(returnType); il.LoadLocalAddress(result); il.InitObject(returnType); il.LoadLocation(result.LocalIndex); return; } // otherwise load null. il.LoadNull(); } } } }
namespace Azure { public abstract partial class AsyncPageable<T> : System.Collections.Generic.IAsyncEnumerable<T> where T : notnull { protected AsyncPageable() { } protected AsyncPageable(System.Threading.CancellationToken cancellationToken) { } protected virtual System.Threading.CancellationToken CancellationToken { get { throw null; } } public abstract System.Collections.Generic.IAsyncEnumerable<Azure.Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = default(int?)); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } public static Azure.AsyncPageable<T> FromPages(System.Collections.Generic.IEnumerable<Azure.Page<T>> pages) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } } public static partial class AzureCoreExtensions { public static System.Threading.Tasks.ValueTask<T?> ToObjectAsync<T>(this System.BinaryData data, Azure.Core.Serialization.ObjectSerializer serializer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static T? ToObject<T>(this System.BinaryData data, Azure.Core.Serialization.ObjectSerializer serializer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class AzureKeyCredential { public AzureKeyCredential(string key) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string Key { get { throw null; } } public void Update(string key) { } } public partial class AzureNamedKeyCredential { public AzureNamedKeyCredential(string name, string key) { } public string Name { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Deconstruct(out string name, out string key) { throw null; } public void Update(string name, string key) { } } public partial class AzureSasCredential { public AzureSasCredential(string signature) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string Signature { get { throw null; } } public void Update(string signature) { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ETag : System.IEquatable<Azure.ETag> { private readonly object _dummy; private readonly int _dummyPrimitive; public static readonly Azure.ETag All; public ETag(string etag) { throw null; } public bool Equals(Azure.ETag other) { throw null; } public override bool Equals(object? obj) { throw null; } public bool Equals(string? other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ETag left, Azure.ETag right) { throw null; } public static bool operator !=(Azure.ETag left, Azure.ETag right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } public string ToString(string format) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct HttpRange : System.IEquatable<Azure.HttpRange> { private readonly int _dummyPrimitive; public HttpRange(long offset = (long)0, long? length = default(long?)) { throw null; } public long? Length { get { throw null; } } public long Offset { get { throw null; } } public bool Equals(Azure.HttpRange other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.HttpRange left, Azure.HttpRange right) { throw null; } public static bool operator !=(Azure.HttpRange left, Azure.HttpRange right) { throw null; } public override string ToString() { throw null; } } public partial class JsonPatchDocument { public JsonPatchDocument() { } public JsonPatchDocument(Azure.Core.Serialization.ObjectSerializer serializer) { } public JsonPatchDocument(System.ReadOnlyMemory<byte> rawDocument) { } public JsonPatchDocument(System.ReadOnlyMemory<byte> rawDocument, Azure.Core.Serialization.ObjectSerializer serializer) { } public void AppendAddRaw(string path, string rawJsonValue) { } public void AppendAdd<T>(string path, T value) { } public void AppendCopy(string from, string path) { } public void AppendMove(string from, string path) { } public void AppendRemove(string path) { } public void AppendReplaceRaw(string path, string rawJsonValue) { } public void AppendReplace<T>(string path, T value) { } public void AppendTestRaw(string path, string rawJsonValue) { } public void AppendTest<T>(string path, T value) { } public System.ReadOnlyMemory<byte> ToBytes() { throw null; } public override string ToString() { throw null; } } public partial class MatchConditions { public MatchConditions() { } public Azure.ETag? IfMatch { get { throw null; } set { } } public Azure.ETag? IfNoneMatch { get { throw null; } set { } } } public abstract partial class Operation { protected Operation() { } public abstract bool HasCompleted { get; } public abstract string Id { get; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public abstract Azure.Response GetRawResponse(); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } public abstract Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public abstract System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public abstract System.Threading.Tasks.ValueTask<Azure.Response> WaitForCompletionResponseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public abstract System.Threading.Tasks.ValueTask<Azure.Response> WaitForCompletionResponseAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } public abstract partial class Operation<T> : Azure.Operation where T : notnull { protected Operation() { } public abstract bool HasValue { get; } public abstract T Value { get; } public abstract System.Threading.Tasks.ValueTask<Azure.Response<T>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public abstract System.Threading.Tasks.ValueTask<Azure.Response<T>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override System.Threading.Tasks.ValueTask<Azure.Response> WaitForCompletionResponseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override System.Threading.Tasks.ValueTask<Azure.Response> WaitForCompletionResponseAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public abstract partial class Pageable<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable where T : notnull { protected Pageable() { } protected Pageable(System.Threading.CancellationToken cancellationToken) { } protected virtual System.Threading.CancellationToken CancellationToken { get { throw null; } } public abstract System.Collections.Generic.IEnumerable<Azure.Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = default(int?)); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } public static Azure.Pageable<T> FromPages(System.Collections.Generic.IEnumerable<Azure.Page<T>> pages) { throw null; } public virtual System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } } public abstract partial class Page<T> { protected Page() { } public abstract string? ContinuationToken { get; } public abstract System.Collections.Generic.IReadOnlyList<T> Values { get; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } public static Azure.Page<T> FromValues(System.Collections.Generic.IReadOnlyList<T> values, string? continuationToken, Azure.Response response) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public abstract Azure.Response GetRawResponse(); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } } public partial class RequestConditions : Azure.MatchConditions { public RequestConditions() { } public System.DateTimeOffset? IfModifiedSince { get { throw null; } set { } } public System.DateTimeOffset? IfUnmodifiedSince { get { throw null; } set { } } } public partial class RequestFailedException : System.Exception, System.Runtime.Serialization.ISerializable { public RequestFailedException(int status, string message) { } public RequestFailedException(int status, string message, System.Exception? innerException) { } public RequestFailedException(int status, string message, string? errorCode, System.Exception? innerException) { } protected RequestFailedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public RequestFailedException(string message) { } public RequestFailedException(string message, System.Exception? innerException) { } public string? ErrorCode { get { throw null; } } public int Status { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public abstract partial class Response : System.IDisposable { protected Response() { } public abstract string ClientRequestId { get; set; } public virtual System.BinaryData Content { get { throw null; } } public abstract System.IO.Stream? ContentStream { get; set; } public virtual Azure.Core.ResponseHeaders Headers { get { throw null; } } public abstract string ReasonPhrase { get; } public abstract int Status { get; } protected internal abstract bool ContainsHeader(string name); public abstract void Dispose(); protected internal abstract System.Collections.Generic.IEnumerable<Azure.Core.HttpHeader> EnumerateHeaders(); public static Azure.Response<T> FromValue<T>(T value, Azure.Response response) { throw null; } public override string ToString() { throw null; } protected internal abstract bool TryGetHeader(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out string? value); protected internal abstract bool TryGetHeaderValues(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Collections.Generic.IEnumerable<string>? values); } public abstract partial class Response<T> { protected Response() { } public abstract T Value { get; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public abstract Azure.Response GetRawResponse(); public static implicit operator T (Azure.Response<T> response) { throw null; } public override string ToString() { throw null; } } public partial class SyncAsyncEventArgs : System.EventArgs { public SyncAsyncEventArgs(bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public bool IsRunningSynchronously { get { throw null; } } } } namespace Azure.Core { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct AccessToken { private object _dummy; private int _dummyPrimitive; public AccessToken(string accessToken, System.DateTimeOffset expiresOn) { throw null; } public System.DateTimeOffset ExpiresOn { get { throw null; } } public string Token { get { throw null; } } public override bool Equals(object? obj) { throw null; } public override int GetHashCode() { throw null; } } public abstract partial class ClientOptions { protected ClientOptions() { } public Azure.Core.DiagnosticsOptions Diagnostics { get { throw null; } } public Azure.Core.RetryOptions Retry { get { throw null; } } public Azure.Core.Pipeline.HttpPipelineTransport Transport { get { throw null; } set { } } public void AddPolicy(Azure.Core.Pipeline.HttpPipelinePolicy policy, Azure.Core.HttpPipelinePosition position) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } } public partial class DiagnosticsOptions { internal DiagnosticsOptions() { } public string? ApplicationId { get { throw null; } set { } } public static string? DefaultApplicationId { get { throw null; } set { } } public bool IsDistributedTracingEnabled { get { throw null; } set { } } public bool IsLoggingContentEnabled { get { throw null; } set { } } public bool IsLoggingEnabled { get { throw null; } set { } } public bool IsTelemetryEnabled { get { throw null; } set { } } public int LoggedContentSizeLimit { get { throw null; } set { } } public System.Collections.Generic.IList<string> LoggedHeaderNames { get { throw null; } } public System.Collections.Generic.IList<string> LoggedQueryParameters { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct HttpHeader : System.IEquatable<Azure.Core.HttpHeader> { private readonly object _dummy; private readonly int _dummyPrimitive; public HttpHeader(string name, string value) { throw null; } public string Name { get { throw null; } } public string Value { get { throw null; } } public bool Equals(Azure.Core.HttpHeader other) { throw null; } public override bool Equals(object? obj) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } public static partial class Common { public static readonly Azure.Core.HttpHeader FormUrlEncodedContentType; public static readonly Azure.Core.HttpHeader JsonAccept; public static readonly Azure.Core.HttpHeader JsonContentType; public static readonly Azure.Core.HttpHeader OctetStreamContentType; } public static partial class Names { public static string Accept { get { throw null; } } public static string Authorization { get { throw null; } } public static string ContentDisposition { get { throw null; } } public static string ContentLength { get { throw null; } } public static string ContentType { get { throw null; } } public static string Date { get { throw null; } } public static string ETag { get { throw null; } } public static string Host { get { throw null; } } public static string IfMatch { get { throw null; } } public static string IfModifiedSince { get { throw null; } } public static string IfNoneMatch { get { throw null; } } public static string IfUnmodifiedSince { get { throw null; } } public static string Range { get { throw null; } } public static string Referer { get { throw null; } } public static string UserAgent { get { throw null; } } public static string WwwAuthenticate { get { throw null; } } public static string XMsDate { get { throw null; } } public static string XMsRange { get { throw null; } } public static string XMsRequestId { get { throw null; } } } } public sealed partial class HttpMessage : System.IDisposable { public HttpMessage(Azure.Core.Request request, Azure.Core.ResponseClassifier responseClassifier) { } public bool BufferResponse { get { throw null; } set { } } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public bool HasResponse { get { throw null; } } public Azure.Core.Request Request { get { throw null; } } public Azure.Response Response { get { throw null; } set { } } public Azure.Core.ResponseClassifier ResponseClassifier { get { throw null; } } public void Dispose() { } public System.IO.Stream? ExtractResponseContent() { throw null; } public void SetProperty(string name, object value) { } public bool TryGetProperty(string name, out object? value) { throw null; } } public enum HttpPipelinePosition { PerCall = 0, PerRetry = 1, } public abstract partial class Request : System.IDisposable { protected Request() { } public abstract string ClientRequestId { get; set; } public virtual Azure.Core.RequestContent? Content { get { throw null; } set { } } public Azure.Core.RequestHeaders Headers { get { throw null; } } public virtual Azure.Core.RequestMethod Method { get { throw null; } set { } } public virtual Azure.Core.RequestUriBuilder Uri { get { throw null; } set { } } protected internal abstract void AddHeader(string name, string value); protected internal abstract bool ContainsHeader(string name); public abstract void Dispose(); protected internal abstract System.Collections.Generic.IEnumerable<Azure.Core.HttpHeader> EnumerateHeaders(); protected internal abstract bool RemoveHeader(string name); protected internal virtual void SetHeader(string name, string value) { } protected internal abstract bool TryGetHeader(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out string? value); protected internal abstract bool TryGetHeaderValues(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Collections.Generic.IEnumerable<string>? values); } public abstract partial class RequestContent : System.IDisposable { protected RequestContent() { } public static Azure.Core.RequestContent Create(System.BinaryData content) { throw null; } public static Azure.Core.RequestContent Create(System.Buffers.ReadOnlySequence<byte> bytes) { throw null; } public static Azure.Core.RequestContent Create(byte[] bytes) { throw null; } public static Azure.Core.RequestContent Create(byte[] bytes, int index, int length) { throw null; } public static Azure.Core.RequestContent Create(System.IO.Stream stream) { throw null; } public static Azure.Core.RequestContent Create(object serializable, Azure.Core.Serialization.ObjectSerializer? serializer = null) { throw null; } public static Azure.Core.RequestContent Create(System.ReadOnlyMemory<byte> bytes) { throw null; } public static Azure.Core.RequestContent Create(string content) { throw null; } public abstract void Dispose(); public static implicit operator Azure.Core.RequestContent (System.BinaryData content) { throw null; } public static implicit operator Azure.Core.RequestContent (string content) { throw null; } public abstract bool TryComputeLength(out long length); public abstract void WriteTo(System.IO.Stream stream, System.Threading.CancellationToken cancellation); public abstract System.Threading.Tasks.Task WriteToAsync(System.IO.Stream stream, System.Threading.CancellationToken cancellation); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct RequestHeaders : System.Collections.Generic.IEnumerable<Azure.Core.HttpHeader>, System.Collections.IEnumerable { private readonly object _dummy; private readonly int _dummyPrimitive; public void Add(Azure.Core.HttpHeader header) { } public void Add(string name, string value) { } public bool Contains(string name) { throw null; } public System.Collections.Generic.IEnumerator<Azure.Core.HttpHeader> GetEnumerator() { throw null; } public bool Remove(string name) { throw null; } public void SetValue(string name, string value) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out string? value) { throw null; } public bool TryGetValues(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Collections.Generic.IEnumerable<string>? values) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct RequestMethod : System.IEquatable<Azure.Core.RequestMethod> { private readonly object _dummy; private readonly int _dummyPrimitive; public RequestMethod(string method) { throw null; } public static Azure.Core.RequestMethod Delete { get { throw null; } } public static Azure.Core.RequestMethod Get { get { throw null; } } public static Azure.Core.RequestMethod Head { get { throw null; } } public string Method { get { throw null; } } public static Azure.Core.RequestMethod Options { get { throw null; } } public static Azure.Core.RequestMethod Patch { get { throw null; } } public static Azure.Core.RequestMethod Post { get { throw null; } } public static Azure.Core.RequestMethod Put { get { throw null; } } public static Azure.Core.RequestMethod Trace { get { throw null; } } public bool Equals(Azure.Core.RequestMethod other) { throw null; } public override bool Equals(object? obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Core.RequestMethod left, Azure.Core.RequestMethod right) { throw null; } public static bool operator !=(Azure.Core.RequestMethod left, Azure.Core.RequestMethod right) { throw null; } public static Azure.Core.RequestMethod Parse(string method) { throw null; } public override string ToString() { throw null; } } public partial class RequestUriBuilder { public RequestUriBuilder() { } public string? Host { get { throw null; } set { } } public string Path { get { throw null; } set { } } public string PathAndQuery { get { throw null; } } public int Port { get { throw null; } set { } } public string Query { get { throw null; } set { } } public string? Scheme { get { throw null; } set { } } public void AppendPath(string value) { } public void AppendPath(string value, bool escape) { } public void AppendQuery(string name, string value) { } public void AppendQuery(string name, string value, bool escapeValue) { } public void Reset(System.Uri value) { } public override string ToString() { throw null; } public System.Uri ToUri() { throw null; } } public partial class ResponseClassifier { public ResponseClassifier() { } public virtual bool IsErrorResponse(Azure.Core.HttpMessage message) { throw null; } public virtual bool IsRetriable(Azure.Core.HttpMessage message, System.Exception exception) { throw null; } public virtual bool IsRetriableException(System.Exception exception) { throw null; } public virtual bool IsRetriableResponse(Azure.Core.HttpMessage message) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ResponseHeaders : System.Collections.Generic.IEnumerable<Azure.Core.HttpHeader>, System.Collections.IEnumerable { private readonly object _dummy; private readonly int _dummyPrimitive; public int? ContentLength { get { throw null; } } public string? ContentType { get { throw null; } } public System.DateTimeOffset? Date { get { throw null; } } public Azure.ETag? ETag { get { throw null; } } public string? RequestId { get { throw null; } } public bool Contains(string name) { throw null; } public System.Collections.Generic.IEnumerator<Azure.Core.HttpHeader> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out string? value) { throw null; } public bool TryGetValues(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Collections.Generic.IEnumerable<string>? values) { throw null; } } public enum RetryMode { Fixed = 0, Exponential = 1, } public partial class RetryOptions { internal RetryOptions() { } public System.TimeSpan Delay { get { throw null; } set { } } public System.TimeSpan MaxDelay { get { throw null; } set { } } public int MaxRetries { get { throw null; } set { } } public Azure.Core.RetryMode Mode { get { throw null; } set { } } public System.TimeSpan NetworkTimeout { get { throw null; } set { } } } public delegate System.Threading.Tasks.Task SyncAsyncEventHandler<T>(T e) where T : Azure.SyncAsyncEventArgs; public abstract partial class TokenCredential { protected TokenCredential() { } public abstract Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken); public abstract System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct TokenRequestContext { private readonly object _dummy; private readonly int _dummyPrimitive; public TokenRequestContext(string[] scopes, string? parentRequestId) { throw null; } public TokenRequestContext(string[] scopes, string? parentRequestId = null, string? claims = null) { throw null; } public string? Claims { get { throw null; } } public string? ParentRequestId { get { throw null; } } public string[] Scopes { get { throw null; } } } } namespace Azure.Core.Cryptography { public partial interface IKeyEncryptionKey { string KeyId { get; } byte[] UnwrapKey(string algorithm, System.ReadOnlyMemory<byte> encryptedKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); System.Threading.Tasks.Task<byte[]> UnwrapKeyAsync(string algorithm, System.ReadOnlyMemory<byte> encryptedKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); byte[] WrapKey(string algorithm, System.ReadOnlyMemory<byte> key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); System.Threading.Tasks.Task<byte[]> WrapKeyAsync(string algorithm, System.ReadOnlyMemory<byte> key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } public partial interface IKeyEncryptionKeyResolver { Azure.Core.Cryptography.IKeyEncryptionKey Resolve(string keyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); System.Threading.Tasks.Task<Azure.Core.Cryptography.IKeyEncryptionKey> ResolveAsync(string keyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } namespace Azure.Core.Diagnostics { public partial class AzureEventSourceListener : System.Diagnostics.Tracing.EventListener { public const string TraitName = "AzureEventSource"; public const string TraitValue = "true"; public AzureEventSourceListener(System.Action<System.Diagnostics.Tracing.EventWrittenEventArgs, string> log, System.Diagnostics.Tracing.EventLevel level) { } public static Azure.Core.Diagnostics.AzureEventSourceListener CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; } public static Azure.Core.Diagnostics.AzureEventSourceListener CreateTraceLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; } protected sealed override void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { } protected sealed override void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData) { } } } namespace Azure.Core.Extensions { public partial interface IAzureClientBuilder<TClient, TOptions> where TOptions : class { } public partial interface IAzureClientFactoryBuilder { Azure.Core.Extensions.IAzureClientBuilder<TClient, TOptions> RegisterClientFactory<TClient, TOptions>(System.Func<TOptions, TClient> clientFactory) where TOptions : class; } public partial interface IAzureClientFactoryBuilderWithConfiguration<in TConfiguration> : Azure.Core.Extensions.IAzureClientFactoryBuilder { Azure.Core.Extensions.IAzureClientBuilder<TClient, TOptions> RegisterClientFactory<TClient, TOptions>(TConfiguration configuration) where TOptions : class; } public partial interface IAzureClientFactoryBuilderWithCredential { Azure.Core.Extensions.IAzureClientBuilder<TClient, TOptions> RegisterClientFactory<TClient, TOptions>(System.Func<TOptions, Azure.Core.TokenCredential, TClient> clientFactory, bool requiresCredential = true) where TOptions : class; } } namespace Azure.Core.Pipeline { public partial class BearerTokenAuthenticationPolicy : Azure.Core.Pipeline.HttpPipelinePolicy { public BearerTokenAuthenticationPolicy(Azure.Core.TokenCredential credential, System.Collections.Generic.IEnumerable<string> scopes) { } public BearerTokenAuthenticationPolicy(Azure.Core.TokenCredential credential, string scope) { } public override void Process(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { } public override System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { throw null; } } public partial class HttpClientTransport : Azure.Core.Pipeline.HttpPipelineTransport { public static readonly Azure.Core.Pipeline.HttpClientTransport Shared; public HttpClientTransport() { } public HttpClientTransport(System.Net.Http.HttpClient client) { } public HttpClientTransport(System.Net.Http.HttpMessageHandler messageHandler) { } public sealed override Azure.Core.Request CreateRequest() { throw null; } public override void Process(Azure.Core.HttpMessage message) { } public sealed override System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message) { throw null; } } public partial class HttpPipeline { public HttpPipeline(Azure.Core.Pipeline.HttpPipelineTransport transport, Azure.Core.Pipeline.HttpPipelinePolicy[]? policies = null, Azure.Core.ResponseClassifier? responseClassifier = null) { } public Azure.Core.ResponseClassifier ResponseClassifier { get { throw null; } } public static System.IDisposable CreateClientRequestIdScope(string? clientRequestId) { throw null; } public static System.IDisposable CreateHttpMessagePropertiesScope(System.Collections.Generic.IDictionary<string, object?> messageProperties) { throw null; } public Azure.Core.HttpMessage CreateMessage() { throw null; } public Azure.Core.Request CreateRequest() { throw null; } public void Send(Azure.Core.HttpMessage message, System.Threading.CancellationToken cancellationToken) { } public System.Threading.Tasks.ValueTask SendAsync(Azure.Core.HttpMessage message, System.Threading.CancellationToken cancellationToken) { throw null; } public Azure.Response SendRequest(Azure.Core.Request request, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.ValueTask<Azure.Response> SendRequestAsync(Azure.Core.Request request, System.Threading.CancellationToken cancellationToken) { throw null; } } public static partial class HttpPipelineBuilder { public static Azure.Core.Pipeline.HttpPipeline Build(Azure.Core.ClientOptions options, params Azure.Core.Pipeline.HttpPipelinePolicy[] perRetryPolicies) { throw null; } public static Azure.Core.Pipeline.HttpPipeline Build(Azure.Core.ClientOptions options, Azure.Core.Pipeline.HttpPipelinePolicy[] perCallPolicies, Azure.Core.Pipeline.HttpPipelinePolicy[] perRetryPolicies, Azure.Core.ResponseClassifier responseClassifier) { throw null; } } public abstract partial class HttpPipelinePolicy { protected HttpPipelinePolicy() { } public abstract void Process(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline); public abstract System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline); protected static void ProcessNext(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { } protected static System.Threading.Tasks.ValueTask ProcessNextAsync(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { throw null; } } public abstract partial class HttpPipelineSynchronousPolicy : Azure.Core.Pipeline.HttpPipelinePolicy { protected HttpPipelineSynchronousPolicy() { } public virtual void OnReceivedResponse(Azure.Core.HttpMessage message) { } public virtual void OnSendingRequest(Azure.Core.HttpMessage message) { } public override void Process(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { } public override System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { throw null; } } public abstract partial class HttpPipelineTransport { protected HttpPipelineTransport() { } public abstract Azure.Core.Request CreateRequest(); public abstract void Process(Azure.Core.HttpMessage message); public abstract System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message); } } namespace Azure.Core.Serialization { public partial interface IMemberNameConverter { string? ConvertMemberName(System.Reflection.MemberInfo member); } public partial class JsonObjectSerializer : Azure.Core.Serialization.ObjectSerializer, Azure.Core.Serialization.IMemberNameConverter { public JsonObjectSerializer() { } public JsonObjectSerializer(System.Text.Json.JsonSerializerOptions options) { } public static Azure.Core.Serialization.JsonObjectSerializer Default { get { throw null; } } string? Azure.Core.Serialization.IMemberNameConverter.ConvertMemberName(System.Reflection.MemberInfo member) { throw null; } public override object? Deserialize(System.IO.Stream stream, System.Type returnType, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<object?> DeserializeAsync(System.IO.Stream stream, System.Type returnType, System.Threading.CancellationToken cancellationToken) { throw null; } public override void Serialize(System.IO.Stream stream, object? value, System.Type inputType, System.Threading.CancellationToken cancellationToken) { } public override System.BinaryData Serialize(object? value, System.Type? inputType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask SerializeAsync(System.IO.Stream stream, object? value, System.Type inputType, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<System.BinaryData> SerializeAsync(object? value, System.Type? inputType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public abstract partial class ObjectSerializer { protected ObjectSerializer() { } public abstract object? Deserialize(System.IO.Stream stream, System.Type returnType, System.Threading.CancellationToken cancellationToken); public abstract System.Threading.Tasks.ValueTask<object?> DeserializeAsync(System.IO.Stream stream, System.Type returnType, System.Threading.CancellationToken cancellationToken); public abstract void Serialize(System.IO.Stream stream, object? value, System.Type inputType, System.Threading.CancellationToken cancellationToken); public virtual System.BinaryData Serialize(object? value, System.Type? inputType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public abstract System.Threading.Tasks.ValueTask SerializeAsync(System.IO.Stream stream, object? value, System.Type inputType, System.Threading.CancellationToken cancellationToken); public virtual System.Threading.Tasks.ValueTask<System.BinaryData> SerializeAsync(object? value, System.Type? inputType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } } namespace Azure.Messaging { public partial class CloudEvent { public CloudEvent(string source, string type, System.BinaryData? data, string? dataContentType, Azure.Messaging.CloudEventDataFormat dataFormat = Azure.Messaging.CloudEventDataFormat.Binary) { } public CloudEvent(string source, string type, object? jsonSerializableData, System.Type? dataSerializationType = null) { } public System.BinaryData? Data { get { throw null; } set { } } public string? DataContentType { get { throw null; } set { } } public string? DataSchema { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, object> ExtensionAttributes { get { throw null; } } public string Id { get { throw null; } set { } } public string Source { get { throw null; } set { } } public string? Subject { get { throw null; } set { } } public System.DateTimeOffset? Time { get { throw null; } set { } } public string Type { get { throw null; } set { } } public static Azure.Messaging.CloudEvent? Parse(System.BinaryData json, bool skipValidation = false) { throw null; } public static Azure.Messaging.CloudEvent[] ParseMany(System.BinaryData json, bool skipValidation = false) { throw null; } } public enum CloudEventDataFormat { Binary = 0, Json = 1, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; namespace System.IO { /// <summary>Contains internal path helpers that are shared between many projects.</summary> internal static partial class PathInternal { // All paths in Win32 ultimately end up becoming a path to a File object in the Windows object manager. Passed in paths get mapped through // DosDevice symbolic links in the object tree to actual File objects under \Devices. To illustrate, this is what happens with a typical // path "Foo" passed as a filename to any Win32 API: // // 1. "Foo" is recognized as a relative path and is appended to the current directory (say, "C:\" in our example) // 2. "C:\Foo" is prepended with the DosDevice namespace "\??\" // 3. CreateFile tries to create an object handle to the requested file "\??\C:\Foo" // 4. The Object Manager recognizes the DosDevices prefix and looks // a. First in the current session DosDevices ("\Sessions\1\DosDevices\" for example, mapped network drives go here) // b. If not found in the session, it looks in the Global DosDevices ("\GLOBAL??\") // 5. "C:" is found in DosDevices (in our case "\GLOBAL??\C:", which is a symbolic link to "\Device\HarddiskVolume6") // 6. The full path is now "\Device\HarddiskVolume6\Foo", "\Device\HarddiskVolume6" is a File object and parsing is handed off // to the registered parsing method for Files // 7. The registered open method for File objects is invoked to create the file handle which is then returned // // There are multiple ways to directly specify a DosDevices path. The final format of "\??\" is one way. It can also be specified // as "\\.\" (the most commonly documented way) and "\\?\". If the question mark syntax is used the path will skip normalization // (essentially GetFullPathName()) and path length checks. // Windows Kernel-Mode Object Manager // https://msdn.microsoft.com/en-us/library/windows/hardware/ff565763.aspx // https://channel9.msdn.com/Shows/Going+Deep/Windows-NT-Object-Manager // // Introduction to MS-DOS Device Names // https://msdn.microsoft.com/en-us/library/windows/hardware/ff548088.aspx // // Local and Global MS-DOS Device Names // https://msdn.microsoft.com/en-us/library/windows/hardware/ff554302.aspx internal const string ExtendedPathPrefix = @"\\?\"; internal const string UncPathPrefix = @"\\"; internal const string UncExtendedPrefixToInsert = @"?\UNC\"; internal const string UncExtendedPathPrefix = @"\\?\UNC\"; internal const string DevicePathPrefix = @"\\.\"; internal const string ParentDirectoryPrefix = @"..\"; internal const int MaxShortPath = 260; internal const int MaxShortDirectoryPath = 248; internal const int MaxLongPath = short.MaxValue; // \\?\, \\.\, \??\ internal const int DevicePrefixLength = 4; // \\ internal const int UncPrefixLength = 2; // \\?\UNC\, \\.\UNC\ internal const int UncExtendedPrefixLength = 8; internal static readonly int MaxComponentLength = 255; internal static char[] GetInvalidPathChars() => new char[] { '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31 }; // [MS - FSA] 2.1.4.4 Algorithm for Determining if a FileName Is in an Expression // https://msdn.microsoft.com/en-us/library/ff469270.aspx private static readonly char[] s_wildcardChars = { '\"', '<', '>', '*', '?' }; /// <summary> /// Returns true if the given character is a valid drive letter /// </summary> internal static bool IsValidDriveChar(char value) { return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z')); } /// <summary> /// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative, /// AND the path is more than 259 characters. (> MAX_PATH + null) /// </summary> internal static string EnsureExtendedPrefixOverMaxPath(string path) { if (path != null && path.Length >= MaxShortPath) { return EnsureExtendedPrefix(path); } else { return path; } } /// <summary> /// Adds the extended path prefix (\\?\) if not relative or already a device path. /// </summary> internal static string EnsureExtendedPrefix(string path) { // Putting the extended prefix on the path changes the processing of the path. It won't get normalized, which // means adding to relative paths will prevent them from getting the appropriate current directory inserted. // If it already has some variant of a device path (\??\, \\?\, \\.\, //./, etc.) we don't need to change it // as it is either correct or we will be changing the behavior. When/if Windows supports long paths implicitly // in the future we wouldn't want normalization to come back and break existing code. // In any case, all internal usages should be hitting normalize path (Path.GetFullPath) before they hit this // shimming method. (Or making a change that doesn't impact normalization, such as adding a filename to a // normalized base path.) if (IsPartiallyQualified(path) || IsDevice(path)) return path; // Given \\server\share in longpath becomes \\?\UNC\server\share if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase)) return path.Insert(2, PathInternal.UncExtendedPrefixToInsert); return PathInternal.ExtendedPathPrefix + path; } /// <summary> /// Returns true if the path uses any of the DOS device path syntaxes. ("\\.\", "\\?\", or "\??\") /// </summary> internal static bool IsDevice(string path) { // If the path begins with any two separators is will be recognized and normalized and prepped with // "\??\" for internal usage correctly. "\??\" is recognized and handled, "/??/" is not. return IsExtended(path) || ( path.Length >= DevicePrefixLength && IsDirectorySeparator(path[0]) && IsDirectorySeparator(path[1]) && (path[2] == '.' || path[2] == '?') && IsDirectorySeparator(path[3]) ); } /// <summary> /// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the /// path matches exactly (cannot use alternate directory separators) Windows will skip normalization /// and path length checks. /// </summary> internal static bool IsExtended(string path) { // While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths. // Skipping of normalization will *only* occur if back slashes ('\') are used. return path.Length >= DevicePrefixLength && path[0] == '\\' && (path[1] == '\\' || path[1] == '?') && path[2] == '?' && path[3] == '\\'; } /// <summary> /// Returns a value indicating if the given path contains invalid characters (", &lt;, &gt;, | /// NUL, or any ASCII char whose integer representation is in the range of 1 through 31). /// Does not check for wild card characters ? and *. /// </summary> internal static bool HasIllegalCharacters(string path) { // This is equivalent to IndexOfAny(InvalidPathChars) >= 0, // except faster since IndexOfAny grows slower as the input // array grows larger. // Since we know that some of the characters we're looking // for are contiguous in the alphabet-- the path cannot contain // characters 0-31-- we can optimize this for our specific use // case and use simple comparison operations. for (int i = 0; i < path.Length; i++) { char c = path[i]; if (c <= '\u001f' || c == '|') { return true; } } return false; } /// <summary> /// Check for known wildcard characters. '*' and '?' are the most common ones. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe bool HasWildCardCharacters(string path) { // Question mark is part of dos device syntax so we have to skip if we are int startIndex = PathInternal.IsDevice(path) ? ExtendedPathPrefix.Length : 0; return path.IndexOfAny(s_wildcardChars, startIndex) >= 0; } /// <summary> /// Gets the length of the root of the path (drive, share, etc.). /// </summary> internal static unsafe int GetRootLength(string path) { fixed(char* value = path) { return (int)GetRootLength(value, (uint)path.Length); } } private static unsafe uint GetRootLength(char* path, uint pathLength) { uint i = 0; uint volumeSeparatorLength = 2; // Length to the colon "C:" uint uncRootLength = 2; // Length to the start of the server name "\\" bool extendedSyntax = StartsWithOrdinal(path, pathLength, ExtendedPathPrefix); bool extendedUncSyntax = StartsWithOrdinal(path, pathLength, UncExtendedPathPrefix); if (extendedSyntax) { // Shift the position we look for the root from to account for the extended prefix if (extendedUncSyntax) { // "\\" -> "\\?\UNC\" uncRootLength = (uint)UncExtendedPathPrefix.Length; } else { // "C:" -> "\\?\C:" volumeSeparatorLength += (uint)ExtendedPathPrefix.Length; } } if ((!extendedSyntax || extendedUncSyntax) && pathLength > 0 && IsDirectorySeparator(path[0])) { // UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo") i = 1; // Drive rooted (\foo) is one character if (extendedUncSyntax || (pathLength > 1 && IsDirectorySeparator(path[1]))) { // UNC (\\?\UNC\ or \\), scan past the next two directory separators at most // (e.g. to \\?\UNC\Server\Share or \\Server\Share\) i = uncRootLength; int n = 2; // Maximum separators to skip while (i < pathLength && (!IsDirectorySeparator(path[i]) || --n > 0)) i++; } } else if (pathLength >= volumeSeparatorLength && path[volumeSeparatorLength - 1] == Path.VolumeSeparatorChar) { // Path is at least longer than where we expect a colon, and has a colon (\\?\A:, A:) // If the colon is followed by a directory separator, move past it i = volumeSeparatorLength; if (pathLength >= volumeSeparatorLength + 1 && IsDirectorySeparator(path[volumeSeparatorLength])) i++; } return i; } private static unsafe bool StartsWithOrdinal(char* source, uint sourceLength, string value) { if (sourceLength < (uint)value.Length) return false; for (int i = 0; i < value.Length; i++) { if (value[i] != source[i]) return false; } return true; } /// <summary> /// Returns true if the path specified is relative to the current drive or working directory. /// Returns false if the path is fixed to a specific drive or UNC path. This method does no /// validation of the path (URIs will be returned as relative as a result). /// </summary> /// <remarks> /// Handles paths that use the alternate directory separator. It is a frequent mistake to /// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case. /// "C:a" is drive relative- meaning that it will be resolved against the current directory /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory /// will not be used to modify the path). /// </remarks> internal static bool IsPartiallyQualified(string path) { if (path.Length < 2) { // It isn't fixed, it must be relative. There is no way to specify a fixed // path with one character (or less). return true; } if (IsDirectorySeparator(path[0])) { // There is no valid way to specify a relative path with two initial slashes or // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\ return !(path[1] == '?' || IsDirectorySeparator(path[1])); } // The only way to specify a fixed path that doesn't begin with two slashes // is the drive, colon, slash format- i.e. C:\ return !((path.Length >= 3) && (path[1] == Path.VolumeSeparatorChar) && IsDirectorySeparator(path[2]) // To match old behavior we'll check the drive character for validity as the path is technically // not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream. && IsValidDriveChar(path[0])); } /// <summary> /// Returns the characters to skip at the start of the path if it starts with space(s) and a drive or directory separator. /// (examples are " C:", " \") /// This is a legacy behavior of Path.GetFullPath(). /// </summary> /// <remarks> /// Note that this conflicts with IsPathRooted() which doesn't (and never did) such a skip. /// </remarks> internal static int PathStartSkip(string path) { int startIndex = 0; while (startIndex < path.Length && path[startIndex] == ' ') startIndex++; if (startIndex > 0 && (startIndex < path.Length && PathInternal.IsDirectorySeparator(path[startIndex])) || (startIndex + 1 < path.Length && path[startIndex + 1] == ':' && PathInternal.IsValidDriveChar(path[startIndex]))) { // Go ahead and skip spaces as we're either " C:" or " \" return startIndex; } return 0; } /// <summary> /// True if the given character is a directory separator. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsDirectorySeparator(char c) { return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar; } /// <summary> /// Normalize separators in the given path. Converts forward slashes into back slashes and compresses slash runs, keeping initial 2 if present. /// Also trims initial whitespace in front of "rooted" paths (see PathStartSkip). /// /// This effectively replicates the behavior of the legacy NormalizePath when it was called with fullCheck=false and expandShortpaths=false. /// The current NormalizePath gets directory separator normalization from Win32's GetFullPathName(), which will resolve relative paths and as /// such can't be used here (and is overkill for our uses). /// /// Like the current NormalizePath this will not try and analyze periods/spaces within directory segments. /// </summary> /// <remarks> /// The only callers that used to use Path.Normalize(fullCheck=false) were Path.GetDirectoryName() and Path.GetPathRoot(). Both usages do /// not need trimming of trailing whitespace here. /// /// GetPathRoot() could technically skip normalizing separators after the second segment- consider as a future optimization. /// /// For legacy desktop behavior with ExpandShortPaths: /// - It has no impact on GetPathRoot() so doesn't need consideration. /// - It could impact GetDirectoryName(), but only if the path isn't relative (C:\ or \\Server\Share). /// /// In the case of GetDirectoryName() the ExpandShortPaths behavior was undocumented and provided inconsistent results if the path was /// fixed/relative. For example: "C:\PROGRA~1\A.TXT" would return "C:\Program Files" while ".\PROGRA~1\A.TXT" would return ".\PROGRA~1". If you /// ultimately call GetFullPath() this doesn't matter, but if you don't or have any intermediate string handling could easily be tripped up by /// this undocumented behavior. /// /// We won't match this old behavior because: /// /// 1. It was undocumented /// 2. It was costly (extremely so if it actually contained '~') /// 3. Doesn't play nice with string logic /// 4. Isn't a cross-plat friendly concept/behavior /// </remarks> internal static string NormalizeDirectorySeparators(string path) { if (string.IsNullOrEmpty(path)) return path; char current; int start = PathStartSkip(path); if (start == 0) { // Make a pass to see if we need to normalize so we can potentially skip allocating bool normalized = true; for (int i = 0; i < path.Length; i++) { current = path[i]; if (IsDirectorySeparator(current) && (current != Path.DirectorySeparatorChar // Check for sequential separators past the first position (we need to keep initial two for UNC/extended) || (i > 0 && i + 1 < path.Length && IsDirectorySeparator(path[i + 1])))) { normalized = false; break; } } if (normalized) return path; } StringBuilder builder = new StringBuilder(path.Length); if (IsDirectorySeparator(path[start])) { start++; builder.Append(Path.DirectorySeparatorChar); } for (int i = start; i < path.Length; i++) { current = path[i]; // If we have a separator if (IsDirectorySeparator(current)) { // If the next is a separator, skip adding this if (i + 1 < path.Length && IsDirectorySeparator(path[i + 1])) { continue; } // Ensure it is the primary separator current = Path.DirectorySeparatorChar; } builder.Append(current); } return builder.ToString(); } /// <summary> /// Returns true if the character is a directory or volume separator. /// </summary> /// <param name="ch">The character to test.</param> internal static bool IsDirectoryOrVolumeSeparator(char ch) { return PathInternal.IsDirectorySeparator(ch) || Path.VolumeSeparatorChar == ch; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security; using System.Security.Cryptography; using System.Text; using SQLCover.Objects; using SQLCover.Parsers; namespace SQLCover { public class CoverageResult : CoverageSummary { private readonly IEnumerable<Batch> _batches; private readonly List<string> _sqlExceptions; private readonly string _commandDetail; public string DatabaseName { get; } public string DataSource { get; } public List<string> SqlExceptions { get { return _sqlExceptions; } } private readonly StatementChecker _statementChecker = new StatementChecker(); public CoverageResult(IEnumerable<Batch> batches, List<string> xml, string database, string dataSource, List<string> sqlExceptions, string commandDetail) { _batches = batches; _sqlExceptions = sqlExceptions; _commandDetail = $"{commandDetail} at {DateTime.Now}"; DatabaseName = database; DataSource = dataSource; var parser = new EventsParser(xml); var statement = parser.GetNextStatement(); while (statement != null) { var batch = _batches.FirstOrDefault(p => p.ObjectId == statement.ObjectId); if (batch != null) { var item = batch.Statements.FirstOrDefault(p => _statementChecker.Overlaps(p, statement)); if (item != null) { item.HitCount++; } } statement = parser.GetNextStatement(); } foreach (var batch in _batches) { batch.CoveredStatementCount = batch.Statements.Count(p => p.HitCount > 0); batch.HitCount = batch.Statements.Sum(p => p.HitCount); } CoveredStatementCount = _batches.Sum(p => p.CoveredStatementCount); StatementCount = _batches.Sum(p => p.StatementCount); HitCount = _batches.Sum(p => p.HitCount); } public string RawXml() { var statements = _batches.Sum(p => p.StatementCount); var coveredStatements = _batches.Sum(p => p.CoveredStatementCount); var builder = new StringBuilder(); builder.AppendFormat("<CodeCoverage StatementCount=\"{0}\" CoveredStatementCount=\"{1}\">\r\n", statements, coveredStatements); foreach (var batch in _batches) { builder.AppendFormat("<Batch Object=\"{0}\" StatementCount=\"{1}\" CoveredStatementCount=\"{2}\">", SecurityElement.Escape(batch.ObjectName), batch.StatementCount, batch.CoveredStatementCount); builder.AppendFormat("<Text>\r\n![CDATA[{0}]]</Text>", XmlTextEncoder.Encode(batch.Text)); foreach (var statement in batch.Statements) { builder.AppendFormat( "\t<Statement HitCount=\"{0}\" Offset=\"{1}\" Length=\"{2}\" CanBeCovered=\"{3}\"></Statement>", statement.HitCount, statement.Offset, statement.Length, statement.IsCoverable); } builder.Append("</Batch>"); } if (_sqlExceptions.Count > 0) { builder.Append("<SqlExceptions>"); foreach (var e in _sqlExceptions) { builder.AppendFormat("\t<SqlException>{0}</SqlException>", XmlTextEncoder.Encode(e)); } builder.Append("</SqlExceptions>"); } builder.Append("\r\n</CodeCoverage>"); var s = builder.ToString(); return s; } public string Html() { var statements = _batches.Sum(p => p.StatementCount); var coveredStatements = _batches.Sum(p => p.CoveredStatementCount); var builder = new StringBuilder(); builder.Append(@"<html> <head> <title>SQLCover Code Coverage Results</title> <style> html{ font-family: ""Roboto"",""Helvetica Neue"",Arial,Sans-serif; font-size: 100%; line-height: 26px; word-break: break-word; } i{ border: solid black; border-width: 0 3px 3px 0; display: inline-block; padding: 3px; } .up { transform: rotate(-135deg); -webkit-transform: rotate(-135deg); } </style> </head> <body id=""top"">"); builder.Append( "<table><thead><td>object name</td><td>statement count</td><td>covered statement count</td><td>coverage %</td></thead>"); builder.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3:0.00}</td></tr>", "<b>Total</b>", statements, coveredStatements, (float)coveredStatements / (float)statements * 100.0); foreach ( var batch in _batches.Where(p => !p.ObjectName.Contains("tSQLt")) .OrderByDescending(p => (float)p.CoveredStatementCount / (float)p.StatementCount)) { builder.AppendFormat( "<tr><td><a href=\"#{0}\">{0}</a></td><td>{1}</td><td>{2}</td><td>{3:0.00}</td></tr>", batch.ObjectName, batch.StatementCount, batch.CoveredStatementCount, (float)batch.CoveredStatementCount / (float)batch.StatementCount * 100.0); } builder.Append("</table>"); foreach (var b in _batches) { builder.AppendFormat("<pre><a name=\"{0}\"><div class=\"batch\">", b.ObjectName); var tempBuffer = b.Text; foreach (var statement in b.Statements.OrderByDescending(p => p.Offset)) { if (statement.HitCount > 0) { var start = tempBuffer.Substring(0, statement.Offset + statement.Length); var end = tempBuffer.Substring(statement.Offset + statement.Length); tempBuffer = start + "</span>" + end; start = tempBuffer.Substring(0, statement.Offset); end = tempBuffer.Substring(statement.Offset); tempBuffer = start + "<span style=\"background-color: greenyellow\">" + end; } } builder.Append(tempBuffer + "</div></a></pre><a href=\"#top\"><i class=\"up\"></i></a>"); } builder.AppendFormat("</body></html>"); return builder.ToString(); } public string Html2() { var statements = _batches.Sum(p => p.StatementCount); var coveredStatements = _batches.Sum(p => p.CoveredStatementCount); var builder = new StringBuilder(); builder.Append(@"<html> <head> <title>SQLCover Code Coverage Results</title> <style> html{ font-family: ""Roboto"",""Helvetica Neue"",Arial,Sans-serif; font-size: 100%; line-height: 26px; word-break: break-word; } i{ border: solid black; border-width: 0 3px 3px 0; display: inline-block; padding: 3px; } .up { transform: rotate(-135deg); -webkit-transform: rotate(-135deg); } .covered-statement{ background-color: greenyellow; } </style> <link media=""all"" rel=""stylesheet"" type=""text/css"" href=""sqlcover.css"" /> </ head> <body id=""top"">"); builder.Append($"<h2 class=\"header\">{_commandDetail}</h2>"); builder.Append( "<table><thead><td>object name</td><td>statement count</td><td>covered statement count</td><td>coverage %</td></thead>"); builder.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3:0.00}</td></tr>", "<b>Total</b>", statements, coveredStatements, (float)coveredStatements / (float)statements * 100.0); foreach ( var batch in _batches.Where(p => !p.ObjectName.Contains("tSQLt")) .OrderByDescending(p => (float)p.CoveredStatementCount / (float)p.StatementCount)) { builder.AppendFormat( "<tr><td><a href=\"#{0}\">{0}</a></td><td>{1}</td><td>{2}</td><td>{3:0.00}</td></tr>", batch.ObjectName, batch.StatementCount, batch.CoveredStatementCount, (float)batch.CoveredStatementCount / (float)batch.StatementCount * 100.0); } builder.Append("</table>"); if (_sqlExceptions.Count > 0) { builder.Append("<div class=\"sql-exceptions\">There were sql exceptions running the batch, see <a href=\"#sql-exceptions\">here</a></div>"); } foreach (var b in _batches) { builder.AppendFormat("<a name=\"{0}\"><div class=\"batch\">", b.ObjectName); builder.AppendFormat("<div><p class=\"batch-summary\">'{3}' summary: statement count: {0}, covered statement count: {1}, coverage %: {2}</p></div>", b.StatementCount, b.CoveredStatementCount, (float) b.CoveredStatementCount / (float) b.StatementCount, b.ObjectName); builder.Append("<pre>"); var tempBuffer = b.Text; foreach (var statement in b.Statements.OrderByDescending(p => p.Offset)) { if (statement.HitCount > 0) { var start = tempBuffer.Substring(0, statement.Offset + statement.Length); var end = tempBuffer.Substring(statement.Offset + statement.Length); tempBuffer = start + "</span>" + end; start = tempBuffer.Substring(0, statement.Offset); end = tempBuffer.Substring(statement.Offset); tempBuffer = start + "<span class=\"covered-statement\">" + end; } } builder.Append(tempBuffer + "</div></a></pre><a href=\"#top\"><i class=\"up\"></i></a>"); } if (_sqlExceptions.Count > 0) { builder.Append("<a name=\"sql-exceptions\"><div class=\"sql-exceptions\">"); foreach (var e in _sqlExceptions) { builder.AppendFormat("\t<pre class=\"sql-exception\">{0}</pre>", e); } builder.Append("</div></a><a href=\"#top\"><i class=\"up sql-exceptions\"></i></a>"); } builder.AppendFormat("</body></html>"); return builder.ToString(); } public void SaveResult(string path, string resultString) { File.WriteAllText(path, resultString); } public void SaveSourceFiles(string path) { foreach (var batch in _batches) { File.WriteAllText(Path.Combine(path, batch.ObjectName), batch.Text); } } /// <summary> /// https://raw.githubusercontent.com/jenkinsci/cobertura-plugin/master/src/test/resources/hudson/plugins/cobertura/coverage-with-data.xml /// http://cobertura.sourceforge.net/xml/coverage-03.dtd /// </summary> /// <returns></returns> public string Cobertura(string packageName = "sql", Action<CustomCoverageUpdateParameter> customCoverageUpdater = null) { var statements = _batches.Sum(p => p.StatementCount); var coveredStatements = _batches.Sum(p => p.CoveredStatementCount); // gen coverage header var builder = new StringBuilder(); builder.AppendLine(Unquote($@"<?xml version='1.0'?> <!--DOCTYPE coverage SYSTEM 'http://cobertura.sourceforge.net/xml/coverage-03.dtd'--> <coverage lines-valid='{statements}' lines-covered='{coveredStatements}' line-rate='{coveredStatements / (float)statements}' version='1.9' timestamp='{(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds}'> <packages> <package name='{packageName}'> <classes>")); var fileMap = _batches.GroupBy(b => b.ObjectName, StringComparer.OrdinalIgnoreCase); foreach (var file in fileMap) { var lines = file.Sum(b => b.StatementCount); var coveredLines = file.Sum(b => b.CoveredStatementCount); var anyBatch = file.First(); var coverageUpdateParam = new CustomCoverageUpdateParameter() { Batch = anyBatch }; customCoverageUpdater?.Invoke(coverageUpdateParam); var objectName = anyBatch.ObjectName; var filename = anyBatch.FileName; // gen file header builder.AppendLine(Unquote($" <class name='{objectName}' filename='{filename}' lines-valid='{lines}' lines-covered='{coveredLines}' line-rate='{coveredLines / (float)lines}' >")); builder.AppendLine(" <methods/>"); builder.AppendLine(" <lines>"); // gen lines info foreach (var line in file.SelectMany(batch => batch.Statements)) { var offsetInfo = GetOffsets(line.Offset + coverageUpdateParam.OffsetCorrection, line.Length, anyBatch.Text, lineStart: 1 + coverageUpdateParam.LineCorrection); int lNum = offsetInfo.StartLine; while (lNum <= offsetInfo.EndLine) builder.AppendLine(Unquote($" <line number='{lNum++}' hits='{line.HitCount}' branch='false' />")); } // gen file footer builder.AppendLine(" </lines>"); builder.AppendLine(" </class>"); } // gen coverage footer builder.AppendLine(@" </classes> </package> </packages> </coverage>"); return builder.ToString(); } private static string Unquote(string quotedStr) => quotedStr.Replace("'", "\""); public string OpenCoverXml() { var statements = _batches.Sum(p => p.StatementCount); var coveredStatements = _batches.Sum(p => p.CoveredStatementCount); var builder = new StringBuilder(); builder.AppendFormat( "<CoverageSession xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + "<Summary numSequencePoints=\"{0}\" visitedSequencePoints=\"{1}\" numBranchPoints=\"0\" visitedBranchPoints=\"0\" sequenceCoverage=\"{2}\" branchCoverage=\"0.0\" maxCyclomaticComplexity=\"0\" minCyclomaticComplexity=\"0\" /><Modules>\r\n" , statements, coveredStatements, coveredStatements / (float)statements * 100.0); builder.Append("<Module hash=\"ED-DE-ED-DE-ED-DE-ED-DE-ED-DE-ED-DE-ED-DE-ED-DE-ED-DE-ED-DE\">"); builder.AppendFormat("<FullName>{0}</FullName>", DatabaseName); builder.AppendFormat("<ModuleName>{0}</ModuleName>", DatabaseName); var fileMap = new Dictionary<string, int>(); var i = 1; foreach (var batch in _batches) { fileMap[batch.ObjectName] = i++; } builder.Append("<Files>\r\n"); foreach (var pair in fileMap) { builder.AppendFormat("\t<File uid=\"{0}\" fullPath=\"{1}\" />\r\n", pair.Value, pair.Key); } builder.Append("</Files>\r\n<Classes>\r\n"); i = 1; foreach (var batch in _batches) { builder.AppendFormat( "<Class><Summary numSequencePoints=\"{0}\" visitedSequencePoints=\"{1}\" numBranchPoints=\"0\" visitedBranchPoints=\"0\" sequenceCoverage=\"{2}\" branchCoverage=\"0\" maxCyclomaticComplexity=\"0\" minCyclomaticComplexity=\"0\" /><FullName>{3}</FullName><Methods>" , batch.Statements.Count, batch.CoveredStatementCount, (float)batch.CoveredStatementCount / (float)batch.StatementCount * 100.0 , batch.ObjectName); builder.AppendFormat( "\t\t<Method visited=\"{0}\" cyclomaticComplexity=\"0\" sequenceCoverage=\"{1}\" branchCoverage=\"0\" isConstructor=\"false\" isStatic=\"false\" isGetter=\"true\" isSetter=\"false\">\r\n", batch.CoveredStatementCount > 0 ? "true" : "false", batch.CoveredStatementCount / (float)batch.StatementCount * 100.0); builder.AppendFormat( "\t\t<Summary numSequencePoints=\"{1}\" visitedSequencePoints=\"0\" numBranchPoints=\"0\" visitedBranchPoints=\"0\" sequenceCoverage=\"{2}\" branchCoverage=\"0\" maxCyclomaticComplexity=\"0\" minCyclomaticComplexity=\"0\" />\r\n", batch.StatementCount, batch.CoveredStatementCount, batch.CoveredStatementCount / (float)batch.StatementCount * 100.0); builder.AppendFormat( "\t\t<MetadataToken>01041980</MetadataToken><Name>{0}</Name><FileRef uid=\"{1}\" />\r\n", batch.ObjectName, fileMap[batch.ObjectName]); builder.Append("\t\t<SequencePoints>\r\n"); var j = 1; foreach (var statement in batch.Statements) { // if (statement.HitCount > 0) // { var offsets = GetOffsets(statement, batch.Text); builder.AppendFormat( "\t\t\t<SequencePoint vc=\"{0}\" uspid=\"{1}\" ordinal=\"{2}\" offset=\"{3}\" sl=\"{4}\" sc=\"{5}\" el=\"{6}\" ec=\"{7}\" />\r\n", statement.HitCount , i++ , j++ , statement.Offset , offsets.StartLine, offsets.StartColumn, offsets.EndLine, offsets.EndColumn); // } } builder.Append("\t\t</SequencePoints>\r\n"); builder.Append("\t\t</Method>\r\n"); builder.Append("</Methods>\r\n"); builder.Append("</Class>\r\n"); } builder.Append("</Classes></Module>\r\n"); builder.Append("</Modules>\r\n"); builder.Append("</CoverageSession>"); var s = builder.ToString(); return s; } private OpenCoverOffsets GetOffsets(Statement statement, string text) => GetOffsets(statement.Offset, statement.Length, text); private OpenCoverOffsets GetOffsets(int offset, int length, string text, int lineStart = 1) { var offsets = new OpenCoverOffsets(); var column = 1; var line = lineStart; var index = 0; while (index < text.Length) { switch (text[index]) { case '\n': line++; column = 0; break; default: if (index == offset) { offsets.StartLine = line; offsets.StartColumn = column; } if (index == offset + length) { offsets.EndLine = line; offsets.EndColumn = column; return offsets; } column++; break; } index++; } return offsets; } public string NCoverXml() { return ""; } } struct OpenCoverOffsets { public int StartLine; public int EndLine; public int StartColumn; public int EndColumn; } public class CustomCoverageUpdateParameter { public Batch Batch { get; internal set; } public int LineCorrection { get; set; } = 0; public int OffsetCorrection { get; set; } = 0; } }
#region License /* * AuthenticationResponse.cs * * ParseBasicCredentials is derived from System.Net.HttpListenerContext.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2013-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections.Specialized; using System.Security.Cryptography; using System.Security.Principal; using System.Text; namespace WebSocketSharp.Net { internal class AuthenticationResponse : AuthenticationBase { #region Private Fields private uint _nonceCount; #endregion #region Private Constructors private AuthenticationResponse (AuthenticationSchemes scheme, NameValueCollection parameters) : base (scheme, parameters) { } #endregion #region Internal Constructors internal AuthenticationResponse (NetworkCredential credentials) : this (AuthenticationSchemes.Basic, new NameValueCollection (), credentials, 0) { } internal AuthenticationResponse ( AuthenticationChallenge challenge, NetworkCredential credentials, uint nonceCount) : this (challenge.Scheme, challenge.Parameters, credentials, nonceCount) { } internal AuthenticationResponse ( AuthenticationSchemes scheme, NameValueCollection parameters, NetworkCredential credentials, uint nonceCount) : base (scheme, parameters) { Parameters["username"] = credentials.UserName; Parameters["password"] = credentials.Password; Parameters["uri"] = credentials.Domain; _nonceCount = nonceCount; if (scheme == AuthenticationSchemes.Digest) initAsDigest (); } #endregion #region Internal Properties internal uint NonceCount { get { return _nonceCount < UInt32.MaxValue ? _nonceCount : 0; } } #endregion #region Public Properties public string Cnonce { get { return Parameters["cnonce"]; } } public string Nc { get { return Parameters["nc"]; } } public string Password { get { return Parameters["password"]; } } public string Response { get { return Parameters["response"]; } } public string Uri { get { return Parameters["uri"]; } } public string UserName { get { return Parameters["username"]; } } #endregion #region Private Methods private static string createA1 (string username, string password, string realm) { return String.Format ("{0}:{1}:{2}", username, realm, password); } private static string createA1 ( string username, string password, string realm, string nonce, string cnonce) { return String.Format ( "{0}:{1}:{2}", hash (createA1 (username, password, realm)), nonce, cnonce); } private static string createA2 (string method, string uri) { return String.Format ("{0}:{1}", method, uri); } private static string createA2 (string method, string uri, string entity) { return String.Format ("{0}:{1}:{2}", method, uri, hash (entity)); } private static string hash (string value) { var src = Encoding.UTF8.GetBytes (value); var md5 = MD5.Create (); var hashed = md5.ComputeHash (src); var res = new StringBuilder (64); foreach (var b in hashed) res.Append (b.ToString ("x2")); return res.ToString (); } private void initAsDigest () { var qops = Parameters["qop"]; if (qops != null) { if (qops.Split (',').Contains (qop => qop.Trim ().ToLower () == "auth")) { Parameters["qop"] = "auth"; Parameters["cnonce"] = CreateNonceValue (); Parameters["nc"] = String.Format ("{0:x8}", ++_nonceCount); } else { Parameters["qop"] = null; } } Parameters["method"] = "GET"; Parameters["response"] = CreateRequestDigest (Parameters); } #endregion #region Internal Methods internal static string CreateRequestDigest (NameValueCollection parameters) { var user = parameters["username"]; var pass = parameters["password"]; var realm = parameters["realm"]; var nonce = parameters["nonce"]; var uri = parameters["uri"]; var algo = parameters["algorithm"]; var qop = parameters["qop"]; var cnonce = parameters["cnonce"]; var nc = parameters["nc"]; var method = parameters["method"]; var a1 = algo != null && algo.ToLower () == "md5-sess" ? createA1 (user, pass, realm, nonce, cnonce) : createA1 (user, pass, realm); var a2 = qop != null && qop.ToLower () == "auth-int" ? createA2 (method, uri, parameters["entity"]) : createA2 (method, uri); var secret = hash (a1); var data = qop != null ? String.Format ("{0}:{1}:{2}:{3}:{4}", nonce, nc, cnonce, qop, hash (a2)) : String.Format ("{0}:{1}", nonce, hash (a2)); return hash (String.Format ("{0}:{1}", secret, data)); } internal static AuthenticationResponse Parse (string value) { try { var cred = value.Split (new[] { ' ' }, 2); if (cred.Length != 2) return null; var schm = cred[0].ToLower (); return schm == "basic" ? new AuthenticationResponse ( AuthenticationSchemes.Basic, ParseBasicCredentials (cred[1])) : schm == "digest" ? new AuthenticationResponse ( AuthenticationSchemes.Digest, ParseParameters (cred[1])) : null; } catch { } return null; } internal static NameValueCollection ParseBasicCredentials (string value) { // Decode the basic-credentials (a Base64 encoded string). var userPass = Encoding.Default.GetString (Convert.FromBase64String (value)); // The format is [<domain>\]<username>:<password>. var i = userPass.IndexOf (':'); var user = userPass.Substring (0, i); var pass = i < userPass.Length - 1 ? userPass.Substring (i + 1) : String.Empty; // Check if 'domain' exists. i = user.IndexOf ('\\'); if (i > -1) user = user.Substring (i + 1); var res = new NameValueCollection (); res["username"] = user; res["password"] = pass; return res; } internal override string ToBasicString () { var userPass = String.Format ("{0}:{1}", Parameters["username"], Parameters["password"]); var cred = Convert.ToBase64String (Encoding.UTF8.GetBytes (userPass)); return "Basic " + cred; } internal override string ToDigestString () { var output = new StringBuilder (256); output.AppendFormat ( "Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", response=\"{4}\"", Parameters["username"], Parameters["realm"], Parameters["nonce"], Parameters["uri"], Parameters["response"]); var opaque = Parameters["opaque"]; if (opaque != null) output.AppendFormat (", opaque=\"{0}\"", opaque); var algo = Parameters["algorithm"]; if (algo != null) output.AppendFormat (", algorithm={0}", algo); var qop = Parameters["qop"]; if (qop != null) output.AppendFormat ( ", qop={0}, cnonce=\"{1}\", nc={2}", qop, Parameters["cnonce"], Parameters["nc"]); return output.ToString (); } #endregion #region Public Methods public IIdentity ToIdentity () { var schm = Scheme; return schm == AuthenticationSchemes.Basic ? new HttpBasicIdentity (Parameters["username"], Parameters["password"]) as IIdentity : schm == AuthenticationSchemes.Digest ? new HttpDigestIdentity (Parameters) : null; } #endregion } }
// Release.cs // // Copyright (c) 2008 Scott Peterson <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Xml; namespace MusicBrainz { public sealed class Release : MusicBrainzItem { #region Private const string EXTENSION = "release"; ReleaseType? type; ReleaseStatus? status; string language; string script; string asin; ReadOnlyCollection<Disc> discs; ReadOnlyCollection<Event> events; ReadOnlyCollection<Track> tracks; int? track_number; #endregion #region Constructors Release (string id) : base (id) { } internal Release (XmlReader reader) : base (reader, null, false) { } #endregion #region Protected internal override string UrlExtension { get { return EXTENSION; } } static readonly string [] track_params = new string [] { "tracks", "track-level-rels", "artist", "isrcs" }; internal override void CreateIncCore (StringBuilder builder) { AppendIncParameters (builder, "release-events", "labels"); if (discs == null) AppendIncParameters (builder, "discs"); if (tracks == null) { AppendIncParameters (builder, track_params); AllRelsLoaded = false; } base.CreateIncCore (builder); } internal override void LoadMissingDataCore () { Release release = new Release (Id); type = release.GetReleaseType (); status = release.GetReleaseStatus (); language = release.GetLanguage (); script = release.GetScript (); asin = release.GetAsin (); events = release.GetEvents (); if (discs == null) discs = release.GetDiscs (); if (tracks == null) tracks = release.GetTracks (); base.LoadMissingDataCore (release); } internal override void ProcessAttributes (XmlReader reader) { // How sure am I about getting the type and status in the "Type Status" format? // MB really ought to specify these two things seperatly. string type_string = reader ["type"]; if (type_string != null) { foreach (string token in type_string.Split (' ')) { if (type == null) { type = Utils.StringToEnumOrNull<ReleaseType> (token); if (type != null) continue; } this.status = Utils.StringToEnumOrNull<ReleaseStatus> (token); } } } internal override void ProcessXmlCore (XmlReader reader) { switch (reader.Name) { case "text-representation": language = reader["language"]; script = reader["script"]; break; case "asin": asin = reader.ReadString (); break; case "disc-list": if (reader.ReadToDescendant ("disc")) { List<Disc> discs = new List<Disc> (); do discs.Add (new Disc (reader.ReadSubtree ())); while (reader.ReadToNextSibling ("disc")); this.discs = discs.AsReadOnly (); } break; case "release-event-list": if (!AllDataLoaded) { reader.Skip (); // FIXME this is a workaround for Mono bug 334752 return; } if (reader.ReadToDescendant ("event")) { List<Event> events = new List<Event> (); do events.Add (new Event (reader.ReadSubtree ())); while (reader.ReadToNextSibling ("event")); this.events = events.AsReadOnly (); } break; case "track-list": string offset = reader["offset"]; if (offset != null) track_number = int.Parse (offset) + 1; if (reader.ReadToDescendant ("track")) { List<Track> tracks = new List<Track> (); do tracks.Add (new Track (reader.ReadSubtree (), GetArtist (), AllDataLoaded)); while (reader.ReadToNextSibling ("track")); this.tracks = tracks.AsReadOnly (); } break; default: base.ProcessXmlCore (reader); break; } } #endregion #region Public [Queryable ("reid")] public override string Id { get { return base.Id; } } [Queryable ("release")] public override string GetTitle () { return base.GetTitle (); } [Queryable ("type")] public ReleaseType GetReleaseType () { return GetPropertyOrDefault (ref type, ReleaseType.None); } [Queryable ("status")] public ReleaseStatus GetReleaseStatus () { return GetPropertyOrDefault (ref status, ReleaseStatus.None); } public string GetLanguage () { return GetPropertyOrNull (ref language); } [Queryable ("script")] public string GetScript () { return GetPropertyOrNull (ref script); } [Queryable ("asin")] public string GetAsin () { return GetPropertyOrNull (ref asin); } [QueryableMember("Count", "discids")] public ReadOnlyCollection<Disc> GetDiscs () { return GetPropertyOrNew (ref discs); } public ReadOnlyCollection<Event> GetEvents () { return GetPropertyOrNew (ref events); } [QueryableMember ("Count", "tracks")] public ReadOnlyCollection<Track> GetTracks () { return GetPropertyOrNew (ref tracks); } internal int TrackNumber { get { return track_number ?? -1; } } #endregion #region Static public static Release Get (string id) { if (id == null) throw new ArgumentNullException ("id"); return new Release (id); } public static Query<Release> Query (string title) { if (title == null) throw new ArgumentNullException ("title"); ReleaseQueryParameters parameters = new ReleaseQueryParameters (); parameters.Title = title; return Query (parameters); } public static Query<Release> Query (string title, string artist) { if (title == null) throw new ArgumentNullException ("title"); if (artist == null) throw new ArgumentNullException ("artist"); ReleaseQueryParameters parameters = new ReleaseQueryParameters (); parameters.Title = title; parameters.Artist = artist; return Query (parameters); } public static Query<Release> Query (Disc disc) { if (disc == null) throw new ArgumentNullException ("disc"); ReleaseQueryParameters parameters = new ReleaseQueryParameters (); parameters.DiscId = disc.Id; return Query (parameters); } public static Query<Release> Query (ReleaseQueryParameters parameters) { if (parameters == null) throw new ArgumentNullException ("parameters"); return new Query<Release> (EXTENSION, parameters.ToString ()); } public static Query<Release> QueryFromDevice(string device) { if (device == null) throw new ArgumentNullException ("device"); ReleaseQueryParameters parameters = new ReleaseQueryParameters (); parameters.DiscId = LocalDisc.GetFromDevice (device).Id; return Query (parameters); } public static Query<Release> QueryLucene (string luceneQuery) { if (luceneQuery == null) throw new ArgumentNullException ("luceneQuery"); return new Query<Release> (EXTENSION, CreateLuceneParameter (luceneQuery)); } public static implicit operator string (Release release) { return release.ToString (); } #endregion } #region Ancillary Types public enum ReleaseType { None, Album, Single, EP, Compilation, Soundtrack, Spokenword, Interview, Audiobook, Live, Remix, Other } public enum ReleaseStatus { None, Official, Promotion, Bootleg, PsudoRelease } public enum ReleaseFormat { None, Cartridge, Cassette, CD, DAT, Digital, DualDisc, DVD, LaserDisc, MiniDisc, Other, ReelToReel, SACD, Vinyl } public sealed class ReleaseQueryParameters : ItemQueryParameters { string disc_id; public string DiscId { get { return disc_id; } set { disc_id = value; } } string date; public string Date { get { return date; } set { date = value; } } string asin; public string Asin { get { return asin; } set { asin = value; } } string language; public string Language { get { return language; } set { language = value; } } string script; public string Script { get { return script; } set { script = value; } } internal override void ToStringCore (StringBuilder builder) { if (disc_id != null) { builder.Append ("&discid="); builder.Append (disc_id); } if (date != null) { builder.Append ("&date="); Utils.PercentEncode (builder, date); } if (asin != null) { builder.Append ("&asin="); builder.Append (asin); } if (language != null) { builder.Append ("&lang="); builder.Append (language); } if (script != null) { builder.Append ("&script="); builder.Append (script); } } } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.CalendarTests { // GregorianCalendar.GetDaysInMonth(Int32, Int32) public class GregorianCalendarGetDaysInMonth { private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private static readonly int[] s_daysInMonth365 = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private static readonly int[] s_daysInMonth366 = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; #region Positive tests // PosTest1: leap year, any month other than February [Fact] public void PosTest1() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; int expectedDays, actualDays; year = GetALeapYear(myCalendar); //Get a random value beween 1 and 12 not including 2. do { month = _generator.GetInt32(-55) % 12 + 1; } while (2 == month); expectedDays = s_daysInMonth366[month]; actualDays = myCalendar.GetDaysInMonth(year, month); Assert.Equal(expectedDays, actualDays); } // PosTest2: leap year, February [Fact] public void PosTest2() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; int expectedDays, actualDays; year = GetALeapYear(myCalendar); month = 2; expectedDays = s_daysInMonth366[month]; actualDays = myCalendar.GetDaysInMonth(year, month); Assert.Equal(expectedDays, actualDays); } // PosTest3: common year, February [Fact] public void PosTest3() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; int expectedDays, actualDays; year = GetACommonYear(myCalendar); month = 2; expectedDays = s_daysInMonth365[month]; actualDays = myCalendar.GetDaysInMonth(year, month); Assert.Equal(expectedDays, actualDays); } // PosTest4: common year, any month other than February [Fact] public void PosTest4() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; int expectedDays, actualDays; year = GetACommonYear(myCalendar); //Get a random value beween 1 and 12 not including 2. do { month = _generator.GetInt32(-55) % 12 + 1; } while (2 == month); expectedDays = s_daysInMonth365[month]; actualDays = myCalendar.GetDaysInMonth(year, month); Assert.Equal(expectedDays, actualDays); } // PosTest5: Maximum supported year, any month [Fact] public void PosTest5() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; int expectedDays, actualDays; year = myCalendar.MaxSupportedDateTime.Year; //Get a random month whose value is beween 1 and 12 month = _generator.GetInt32(-55) % 12 + 1; expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month]; actualDays = myCalendar.GetDaysInMonth(year, month); Assert.Equal(expectedDays, actualDays); } // PosTest6: Minimum supported year, any month [Fact] public void PosTest6() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; int expectedDays, actualDays; year = myCalendar.MaxSupportedDateTime.Year; //Get a random month whose value is beween 1 and 12 month = _generator.GetInt32(-55) % 12 + 1; expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month]; actualDays = myCalendar.GetDaysInMonth(year, month); Assert.Equal(expectedDays, actualDays); } // PosTest7: Any year, any month [Fact] public void PosTest7() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; int expectedDays, actualDays; year = GetAYear(myCalendar); //Get a random month whose value is beween 1 and 12 month = _generator.GetInt32(-55) % 12 + 1; expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month]; actualDays = myCalendar.GetDaysInMonth(year, month); Assert.Equal(expectedDays, actualDays); } // PosTest8: Any year, the minimum month [Fact] public void PosTest8() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; int expectedDays, actualDays; year = myCalendar.MaxSupportedDateTime.Year; month = 1; expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month]; actualDays = myCalendar.GetDaysInMonth(year, month); Assert.Equal(expectedDays, actualDays); } // PosTest9: Any year, the maximum month [Fact] public void PosTest9() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; int expectedDays, actualDays; year = myCalendar.MaxSupportedDateTime.Year; month = 12; expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month]; actualDays = myCalendar.GetDaysInMonth(year, month); Assert.Equal(expectedDays, actualDays); } #endregion #region Negative Tests // NegTest1: year is greater than maximum supported value [Fact] public void NegTest1() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; year = myCalendar.MaxSupportedDateTime.Year + 100; month = _generator.GetInt32(-55) % 12 + 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.GetDaysInMonth(year, month); }); } // NegTest2: year is less than maximum supported value [Fact] public void NegTest2() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; year = myCalendar.MinSupportedDateTime.Year - 100; month = _generator.GetInt32(-55) % 12 + 1; Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.GetDaysInMonth(year, month); }); } // NegTest3: month is greater than maximum supported value [Fact] public void NegTest3() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; year = GetAYear(myCalendar); month = 13 + _generator.GetInt32(-55) % (int.MaxValue - 12); Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.GetDaysInMonth(year, month); }); } // NegTest4: month is less than maximum supported value [Fact] public void NegTest4() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; year = myCalendar.MinSupportedDateTime.Year - 100; month = -1 * _generator.GetInt32(-55); Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.GetDaysInMonth(year, month); }); } #endregion #region Helper methods for all the tests //Indicate whether the specified year is leap year or not private bool IsLeapYear(int year) { if (0 == year % 400 || (0 != year % 100 && 0 == (year & 0x3))) { return true; } return false; } //Get a random year beween minmum supported year and maximum supported year of the specified calendar private int GetAYear(Calendar calendar) { int retVal; int maxYear, minYear; maxYear = calendar.MaxSupportedDateTime.Year; minYear = calendar.MinSupportedDateTime.Year; retVal = minYear + _generator.GetInt32(-55) % (maxYear + 1 - minYear); return retVal; } //Get a leap year of the specified calendar private int GetALeapYear(Calendar calendar) { int retVal; // A leap year is any year divisible by 4 except for centennial years(those ending in 00) // which are only leap years if they are divisible by 400. retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0 retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400 // if retVal was 100, 200, or 300 the above logic will result in 0 if (0 == retVal) { retVal = 400; } return retVal; } //Get a common year of the specified calendar private int GetACommonYear(Calendar calendar) { int retVal; do { retVal = GetAYear(calendar); } while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400); return retVal; } //Get text represntation of the input parmeters private string GetParamsInfo(int year, int month) { string str; str = string.Format("\nThe specified month is in {0}-{1}(year-month).", year, month); return str; } #endregion } }
// // ColumnCellStatusIndicator.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Cairo; using Mono.Unix; using Hyena.Gui; using Hyena.Data.Gui; using Hyena.Data.Gui.Accessibility; using Banshee.Gui; using Banshee.Streaming; using Banshee.MediaEngine; using Banshee.ServiceStack; namespace Banshee.Collection.Gui { class ColumnCellStatusIndicatorAccessible : ColumnCellAccessible, Atk.ImageImplementor { private string image_description; public ColumnCellStatusIndicatorAccessible (object bound_object, ColumnCellStatusIndicator cell, ICellAccessibleParent parent) : base (bound_object, cell as ColumnCell, parent) { image_description = cell.GetTextAlternative (bound_object); } public override void Redrawn () { string new_image_description = cell.GetTextAlternative (bound_object); #if ENABLE_ATK if (image_description != new_image_description) GLib.Signal.Emit (this, "visible-data-changed"); #endif image_description = new_image_description; } public string ImageLocale { get { return null; } } public bool SetImageDescription (string description) { return false; } public void GetImageSize (out int width, out int height) { if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object))) width = height = 16; else width = height = Int32.MinValue; } public string ImageDescription { get { return image_description; } } public void GetImagePosition (out int x, out int y, Atk.CoordType coordType) { if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object))) { GetPosition (out x, out y, coordType); x += 4; y += 4; } else { x = y = Int32.MinValue; } } } public class ColumnCellStatusIndicator : ColumnCell, ISizeRequestCell, ITooltipCell { const int padding = 2; protected enum Icon : int { Playing, Paused, Error, Protected, External } private string [] status_names; protected string [] StatusNames { get { return status_names; } } private int pixbuf_size = 16; protected virtual int PixbufSize { get { return pixbuf_size; } set { pixbuf_size = value; } } private int pixbuf_spacing = 4; protected virtual int PixbufSpacing { get { return pixbuf_spacing; } set { pixbuf_spacing = value; } } private Gdk.Pixbuf [] pixbufs; protected Gdk.Pixbuf [] Pixbufs { get { return pixbufs; } } public ColumnCellStatusIndicator (string property) : this (property, true) { } public ColumnCellStatusIndicator (string property, bool expand) : base (property, expand) { LoadPixbufs (); RestrictSize = true; } public bool RestrictSize { get; set; } public void GetWidthRange (Pango.Layout layout, out int min_width, out int max_width) { min_width = max_width = pixbuf_size + 2 * padding; } public override Atk.Object GetAccessible (ICellAccessibleParent parent) { return new ColumnCellStatusIndicatorAccessible (BoundObject, this, parent); } public override string GetTextAlternative (object obj) { var track = obj as TrackInfo; if (track == null) return ""; int icon_index = GetIconIndex (track); if ((icon_index < 0) || (icon_index >= status_names.Length)) { return ""; } else if (icon_index == (int)Icon.Error) { return track.GetPlaybackErrorMessage () ?? ""; } else { return status_names[icon_index]; } } protected virtual int PixbufCount { get { return 5; } } protected virtual int GetIconIndex (TrackInfo track) { int icon_index = -1; if (track.PlaybackError != StreamPlaybackError.None) { icon_index = (int)(track.PlaybackError == StreamPlaybackError.Drm ? Icon.Protected : Icon.Error); } else if (track.IsPlaying) { icon_index = (int)(ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused ? Icon.Paused : Icon.Playing); } else if ((track.MediaAttributes & TrackMediaAttributes.ExternalResource) != 0) { icon_index = (int)Icon.External; } else { icon_index = -1; } return icon_index; } protected virtual void LoadPixbufs () { if (pixbufs != null && pixbufs.Length > 0) { for (int i = 0; i < pixbufs.Length; i++) { if (pixbufs[i] != null) { pixbufs[i].Dispose (); pixbufs[i] = null; } } } if (pixbufs == null) { pixbufs = new Gdk.Pixbuf[PixbufCount]; } pixbufs[(int)Icon.Playing] = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-start"); pixbufs[(int)Icon.Paused] = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-pause"); pixbufs[(int)Icon.Error] = IconThemeUtils.LoadIcon (PixbufSize, "emblem-unreadable", "dialog-error"); pixbufs[(int)Icon.Protected] = IconThemeUtils.LoadIcon (PixbufSize, "emblem-readonly", "dialog-error"); pixbufs[(int)Icon.External] = IconThemeUtils.LoadIcon (PixbufSize, "x-office-document"); if (status_names == null) { status_names = new string[PixbufCount]; for (int i=0; i<PixbufCount; i++) status_names[i] = ""; } status_names[(int)Icon.Playing] = Catalog.GetString ("Playing"); status_names[(int)Icon.Paused] = Catalog.GetString ("Paused"); status_names[(int)Icon.Error] = Catalog.GetString ("Error"); status_names[(int)Icon.Protected] = Catalog.GetString ("Protected"); status_names[(int)Icon.External] = Catalog.GetString ("External Document"); } public override void NotifyThemeChange () { LoadPixbufs (); } public override void Render (CellContext context, StateType state, double cellWidth, double cellHeight) { TrackInfo track = BoundTrack; if (track == null) { return; } int icon_index = GetIconIndex (track); if (icon_index < 0 || pixbufs == null || pixbufs[icon_index] == null) { return; } context.Context.Translate (0, 0.5); Gdk.Pixbuf render_pixbuf = pixbufs[icon_index]; Cairo.Rectangle pixbuf_area = new Cairo.Rectangle ((cellWidth - render_pixbuf.Width) / 2, (cellHeight - render_pixbuf.Height) / 2, render_pixbuf.Width, render_pixbuf.Height); if (!context.Opaque) { context.Context.Save (); } Gdk.CairoHelper.SetSourcePixbuf (context.Context, render_pixbuf, pixbuf_area.X, pixbuf_area.Y); context.Context.Rectangle (pixbuf_area); if (!context.Opaque) { context.Context.Clip (); context.Context.PaintWithAlpha (0.5); context.Context.Restore (); } else { context.Context.Fill (); } } public string GetTooltipMarkup (CellContext cellContext, double columnWidth) { return GetTextAlternative (BoundObject); } protected TrackInfo BoundTrack { get { return BoundObject as TrackInfo; } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Dispatcher { using System.Collections.Generic; using System.Runtime; internal enum RelationOperator { None, Eq, Ne, Gt, Ge, Lt, Le } /// <summary> /// General relation opcode: compares any two values on the value stack /// </summary> internal class RelationOpcode : Opcode { protected RelationOperator op; internal RelationOpcode(RelationOperator op) : this(OpcodeID.Relation, op) { } protected RelationOpcode(OpcodeID id, RelationOperator op) : base(id) { this.op = op; } internal override bool Equals(Opcode op) { if (base.Equals(op)) { return (this.op == ((RelationOpcode)op).op); } return false; } internal override Opcode Eval(ProcessingContext context) { StackFrame argX = context.TopArg; StackFrame argY = context.SecondArg; Fx.Assert(argX.Count == argY.Count, ""); Value[] values = context.Values; while (argX.basePtr <= argX.endPtr) { values[argY.basePtr].Update(context, values[argY.basePtr].CompareTo(ref values[argX.basePtr], op)); argX.basePtr++; argY.basePtr++; } context.PopFrame(); return this.next; } #if DEBUG_FILTER public override string ToString() { return string.Format("{0} {1}", base.ToString(), this.op.ToString()); } #endif } internal abstract class LiteralRelationOpcode : Opcode { internal LiteralRelationOpcode(OpcodeID id) : base(id) { this.flags |= OpcodeFlags.Literal; } #if NO internal abstract ValueDataType DataType { get; } #endif internal abstract object Literal { get; } #if DEBUG_FILTER public override string ToString() { return string.Format("{0} '{1}'", base.ToString(), this.Literal); } #endif } internal class StringEqualsOpcode : LiteralRelationOpcode { string literal; internal StringEqualsOpcode(string literal) : base(OpcodeID.StringEquals) { Fx.Assert(null != literal, ""); this.literal = literal; } #if NO internal override ValueDataType DataType { get { return ValueDataType.String; } } #endif internal override object Literal { get { return this.literal; } } internal override void Add(Opcode op) { StringEqualsOpcode strEqOp = op as StringEqualsOpcode; if (null == strEqOp) { base.Add(op); return; } Fx.Assert(null != this.prev, ""); StringEqualsBranchOpcode branch = new StringEqualsBranchOpcode(); this.prev.Replace(this, branch); branch.Add(this); branch.Add(strEqOp); } internal override bool Equals(Opcode op) { if (base.Equals(op)) { StringEqualsOpcode strEqOp = (StringEqualsOpcode)op; return (strEqOp.literal == this.literal); } return false; } internal override Opcode Eval(ProcessingContext context) { Value[] values = context.Values; StackFrame arg = context.TopArg; if (1 == arg.Count) { values[arg.basePtr].Update(context, values[arg.basePtr].Equals(this.literal)); } else { for (int i = arg.basePtr; i <= arg.endPtr; ++i) { values[i].Update(context, values[i].Equals(this.literal)); } } return this.next; } } internal class NumberEqualsOpcode : LiteralRelationOpcode { double literal; internal NumberEqualsOpcode(double literal) : base(OpcodeID.NumberEquals) { this.literal = literal; } #if NO internal override ValueDataType DataType { get { return ValueDataType.Double; } } #endif internal override object Literal { get { return this.literal; } } internal override void Add(Opcode op) { NumberEqualsOpcode numEqOp = op as NumberEqualsOpcode; if (null == numEqOp) { base.Add(op); return; } Fx.Assert(null != this.prev, ""); NumberEqualsBranchOpcode branch = new NumberEqualsBranchOpcode(); this.prev.Replace(this, branch); branch.Add(this); branch.Add(numEqOp); } internal override bool Equals(Opcode op) { if (base.Equals(op)) { NumberEqualsOpcode numEqOp = (NumberEqualsOpcode)op; return (numEqOp.literal == this.literal); } return false; } internal override Opcode Eval(ProcessingContext context) { Value[] values = context.Values; StackFrame arg = context.TopArg; if (1 == arg.Count) { values[arg.basePtr].Update(context, values[arg.basePtr].Equals(this.literal)); } else { for (int i = arg.basePtr; i <= arg.endPtr; ++i) { values[i].Update(context, values[i].Equals(this.literal)); } } return this.next; } } internal abstract class HashBranchIndex : QueryBranchIndex { Dictionary<object, QueryBranch> literals; internal HashBranchIndex() { this.literals = new Dictionary<object, QueryBranch>(); } internal override int Count { get { return this.literals.Count; } } internal override QueryBranch this[object literal] { get { QueryBranch result; if (this.literals.TryGetValue(literal, out result)) { return result; } return null; } set { this.literals[literal] = value; } } internal override void CollectXPathFilters(ICollection<MessageFilter> filters) { foreach (QueryBranch branch in this.literals.Values) { branch.Branch.CollectXPathFilters(filters); } } #if NO internal override IEnumerator GetEnumerator() { return this.literals.GetEnumerator(); } #endif internal override void Remove(object key) { this.literals.Remove(key); } internal override void Trim() { // Can't compact Hashtable } } internal class StringBranchIndex : HashBranchIndex { internal override void Match(int valIndex, ref Value val, QueryBranchResultSet results) { QueryBranch branch = null; if (ValueDataType.Sequence == val.Type) { NodeSequence sequence = val.Sequence; for (int i = 0; i < sequence.Count; ++i) { branch = this[sequence.Items[i].StringValue()]; if (null != branch) { results.Add(branch, valIndex); } } } else { Fx.Assert(val.Type == ValueDataType.String, ""); branch = this[val.String]; if (null != branch) { results.Add(branch, valIndex); } } } } internal class StringEqualsBranchOpcode : QueryConditionalBranchOpcode { internal StringEqualsBranchOpcode() : base(OpcodeID.StringEqualsBranch, new StringBranchIndex()) { } internal override LiteralRelationOpcode ValidateOpcode(Opcode opcode) { StringEqualsOpcode numOp = opcode as StringEqualsOpcode; if (null != numOp) { return numOp; } return null; } } internal class NumberBranchIndex : HashBranchIndex { internal override void Match(int valIndex, ref Value val, QueryBranchResultSet results) { QueryBranch branch = null; if (ValueDataType.Sequence == val.Type) { NodeSequence sequence = val.Sequence; for (int i = 0; i < sequence.Count; ++i) { branch = this[sequence.Items[i].NumberValue()]; if (null != branch) { results.Add(branch, valIndex); } } } else { branch = this[val.ToDouble()]; if (null != branch) { results.Add(branch, valIndex); } } } } internal class NumberEqualsBranchOpcode : QueryConditionalBranchOpcode { internal NumberEqualsBranchOpcode() : base(OpcodeID.NumberEqualsBranch, new NumberBranchIndex()) { } internal override LiteralRelationOpcode ValidateOpcode(Opcode opcode) { NumberEqualsOpcode numOp = opcode as NumberEqualsOpcode; if (null != numOp) { return numOp; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Reflection.Tests { // MemberInfo.MemberType Property // When overridden in a derived class, gets a MemberTypes value indicating // the type of the member method, constructor, event, and so on. public class ReflectionMemberInfoMemberType { // PosTest1: get accessor of public static property [Fact] public void PosTest1() { bool expectedValue = true; bool actualValue = false; MethodInfo methodInfo; MemberInfo memberInfo; methodInfo = typeof(TestClass1).GetProperty("InstanceCount").GetGetMethod(); memberInfo = methodInfo as MemberInfo; actualValue = memberInfo.Name.Equals("get_InstanceCount"); Assert.Equal(expectedValue, actualValue); } // PosTest2: set accessor of public instance property [Fact] public void PosTest2() { bool expectedValue = true; bool actualValue = false; MethodInfo methodInfo; MemberInfo memberInfo; methodInfo = typeof(TestClass1).GetProperty("Data1").GetSetMethod(); memberInfo = methodInfo as MemberInfo; actualValue = memberInfo.Name.Equals("set_Data1"); Assert.Equal(expectedValue, actualValue); } // PosTest3: public static property [Fact] public void PosTest3() { bool expectedValue = true; bool actualValue = false; PropertyInfo propertyInfo; MemberInfo memberInfo; propertyInfo = typeof(TestClass1).GetProperty("InstanceCount"); memberInfo = propertyInfo as MemberInfo; actualValue = memberInfo.Name.Equals("InstanceCount"); Assert.Equal(expectedValue, actualValue); } // PosTest4: public instance property [Fact] public void PosTest4() { bool expectedValue = true; bool actualValue = false; PropertyInfo propertyInfo; MemberInfo memberInfo; propertyInfo = typeof(TestClass1).GetProperty("Data1"); memberInfo = propertyInfo as MemberInfo; actualValue = memberInfo.Name.Equals("Data1"); Assert.Equal(expectedValue, actualValue); } // PosTest5: public constructor [Fact] public void PosTest5() { bool expectedValue = true; bool actualValue = false; ConstructorInfo constructorInfo; MemberInfo memberInfo; Type[] parameterTypes = { typeof(int) }; constructorInfo = typeof(TestClass1).GetConstructor(parameterTypes); memberInfo = constructorInfo as MemberInfo; actualValue = memberInfo.Name.Equals(".ctor"); ; Assert.Equal(expectedValue, actualValue); } // PosTest6: private instance field [Fact] public void PosTest6() { bool expectedValue = true; bool actualValue = false; Type testType; FieldInfo fieldInfo; MemberInfo memberInfo; testType = typeof(TestClass1); fieldInfo = testType.GetField("_data1", BindingFlags.NonPublic | BindingFlags.Instance); memberInfo = fieldInfo as MemberInfo; actualValue = memberInfo.Name.Equals("_data1"); Assert.Equal(expectedValue, actualValue); } // PosTest7: private static field [Fact] public void PosTest7() { bool expectedValue = true; bool actualValue = false; Type testType; FieldInfo fieldInfo; MemberInfo memberInfo; testType = typeof(TestClass1); fieldInfo = testType.GetField("s_count", BindingFlags.NonPublic | BindingFlags.Static); memberInfo = fieldInfo as MemberInfo; actualValue = memberInfo.Name.Equals("s_count"); ; Assert.Equal(expectedValue, actualValue); } // PosTest8: private instance event [Fact] public void PosTest8() { bool expectedValue = true; bool actualValue = false; Type testType; EventInfo eventInfo; MemberInfo memberInfo; testType = typeof(TestButton); eventInfo = testType.GetEvent("Click"); memberInfo = eventInfo as MemberInfo; actualValue = memberInfo.Name.Equals("Click"); ; Assert.Equal(expectedValue, actualValue); } // PosTest9: nested type [Fact] public void PosTest9() { bool expectedValue = true; bool actualValue = false; Type testType; Type nestedType; testType = typeof(ReflectionMemberInfoMemberType); nestedType = testType.GetNestedType("TestClass1", BindingFlags.NonPublic); actualValue = nestedType.IsNested; Assert.Equal(expectedValue, actualValue); } // PosTest10: unnested type [Fact] public void PosTest10() { bool expectedValue = true; bool actualValue = false; Type testType; testType = typeof(ReflectionMemberInfoMemberType); actualValue = testType.Name.Equals("ReflectionMemberInfoMemberType"); Assert.Equal(expectedValue, actualValue); } private class TestClass1 { private static int s_count = 0; //Default constructor public TestClass1() { ++s_count; } public TestClass1(int data1) { ++s_count; _data1 = data1; } public static int InstanceCount { get { return s_count; } } public int Data1 { get { return _data1; } set { _data1 = value; } } private int _data1; public void Do() { } } private class TestButton { public event EventHandler Click; protected void OnClick(EventArgs e) { if (null != Click) { Click(this, e); } } } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class FileExists : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); File.Create(file1Name).Close(); File.Create(IOTests.Volume.RootDirectory + "\\" + file2Name).Close(); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "File1.tmp"; private const string file2Name = "File2.txt"; private const string testDir = "ExistsDir"; #endregion Local vars #region Helper methods private bool TestExists(string path, bool exists) { Log.Comment("Checking for " + path); if (File.Exists(path) != exists) { Log.Exception("Expeceted " + exists + " but got " + !exists); return false; } return true; } #endregion Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { bool file; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Null"); file = File.Exists(null); /// MSDN: No exception thrown. } catch (ArgumentNullException) { return MFTestResults.Fail; } try { Log.Comment("String.Empty"); file = File.Exists(String.Empty); } catch (ArgumentNullException) { return MFTestResults.Fail; } try { Log.Comment("White Space"); file = File.Exists(" "); } catch (ArgumentNullException) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { Log.Comment("relative to current"); if (!TestExists(file1Name, true)) return MFTestResults.Fail; Log.Comment(". current directory"); if (!TestExists(@".\" + file1Name, true)) return MFTestResults.Fail; Log.Comment(".. parent directory"); if (!TestExists(@"..\" + file2Name, true)) return MFTestResults.Fail; Log.Comment("absolute path"); if (!TestExists(Directory.GetCurrentDirectory() + "\\" + file1Name, true)) return MFTestResults.Fail; Log.Comment("current directory name"); if (!TestExists(Directory.GetCurrentDirectory(), false)) return MFTestResults.Fail; Log.Comment("Set to root"); Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); Log.Comment(". current directory"); if (!TestExists(@".\" + file2Name, true)) return MFTestResults.Fail; Log.Comment("relative child"); if (!TestExists(testDir + "\\" + file1Name, true)) return MFTestResults.Fail; Log.Comment("child directory name"); if (!TestExists(testDir, false)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults NonExistentFiles() { MFTestResults result = MFTestResults.Pass; try { Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); Log.Comment("Current directory: " + Directory.GetCurrentDirectory()); Log.Comment("Non-exist at root"); if (!TestExists(@"..\" + file1Name, false)) return MFTestResults.Fail; Log.Comment("Dot - ."); if (!TestExists("." + file1Name, false)) return MFTestResults.Fail; Log.Comment("Double dot - .."); if (!TestExists(".." + file1Name, false)) return MFTestResults.Fail; Log.Comment("Non-exist relative"); if (!TestExists(file1Name, false)) return MFTestResults.Fail; Log.Comment("Non-exist in child dir"); if (!TestExists(testDir + "\\" + file2Name, false)) return MFTestResults.Fail; Log.Comment("Non-exist absolute"); if (!TestExists(IOTests.Volume.RootDirectory + "\\" + testDir + "\\" + file2Name, false)) return MFTestResults.Fail; Log.Comment("Non-exist directory absolute"); if (!TestExists(IOTests.Volume.RootDirectory + "\\" + testDir + "\\non-existent\\" + file2Name, false)) return MFTestResults.Fail; Log.Comment("Wild card - *" + file1Name); if (!TestExists("*" + file1Name, false)) return MFTestResults.Fail; Log.Comment("Wild card - *"); if (!TestExists("*", false)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults PathTooLong() { MFTestResults result = MFTestResults.Pass; try { string path = new string('x', 500); bool exists = File.Exists(path); } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults CaseInsensitive() { Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory + "\\" + testDir); Log.Comment("Current directory: " + Directory.GetCurrentDirectory()); MFTestResults result = MFTestResults.Pass; try { if (!TestExists(file1Name.ToLower(), true)) return MFTestResults.Fail; if (!TestExists(file1Name.ToUpper(), true)) return MFTestResults.Fail; if (!TestExists(IOTests.Volume.RootDirectory + "\\" + testDir.ToLower() + "\\" + file1Name.ToLower(), true)) return MFTestResults.Fail; if (!TestExists(IOTests.Volume.RootDirectory + "\\" + testDir.ToUpper() + "\\" + file1Name.ToUpper(), true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults MultiSpaceExists() { MFTestResults result = MFTestResults.Pass; try { string dir = Directory.GetCurrentDirectory() + @"\Microsoft Visual Studio .NET\Frame work\V1.0.0.0000"; Directory.CreateDirectory(dir); string fileName = dir + "\\test file with spaces.txt"; File.Create(fileName).Close(); if (!TestExists(fileName, true)) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( NonExistentFiles, "NonExistentFiles" ), new MFTestMethod( PathTooLong, "PathTooLong" ), new MFTestMethod( CaseInsensitive, "CaseInsensitive" ), new MFTestMethod( MultiSpaceExists, "MultiSpaceExists" ), }; } } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. #endregion using System; using System.Text; using NUnit.Framework; using System.IO; #if !NET35 using System.Threading.Tasks; #endif namespace Google.Protobuf { public class ByteStringTest { [Test] public void Equality() { ByteString b1 = ByteString.CopyFrom(1, 2, 3); ByteString b2 = ByteString.CopyFrom(1, 2, 3); ByteString b3 = ByteString.CopyFrom(1, 2, 4); ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4); EqualityTester.AssertEquality(b1, b1); EqualityTester.AssertEquality(b1, b2); EqualityTester.AssertInequality(b1, b3); EqualityTester.AssertInequality(b1, b4); EqualityTester.AssertInequality(b1, null); #pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1) Assert.IsTrue(b1 == b1); Assert.IsTrue(b1 == b2); Assert.IsFalse(b1 == b3); Assert.IsFalse(b1 == b4); Assert.IsFalse(b1 == null); Assert.IsTrue((ByteString) null == null); Assert.IsFalse(b1 != b1); Assert.IsFalse(b1 != b2); #pragma warning disable 1718 Assert.IsTrue(b1 != b3); Assert.IsTrue(b1 != b4); Assert.IsTrue(b1 != null); Assert.IsFalse((ByteString) null != null); } [Test] public void EmptyByteStringHasZeroSize() { Assert.AreEqual(0, ByteString.Empty.Length); } [Test] public void CopyFromStringWithExplicitEncoding() { ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode); Assert.AreEqual(4, bs.Length); Assert.AreEqual(65, bs[0]); Assert.AreEqual(0, bs[1]); Assert.AreEqual(66, bs[2]); Assert.AreEqual(0, bs[3]); } [Test] public void IsEmptyWhenEmpty() { Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty); } [Test] public void IsEmptyWhenNotEmpty() { Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty); } [Test] public void CopyFromByteArrayCopiesContents() { byte[] data = new byte[1]; data[0] = 10; ByteString bs = ByteString.CopyFrom(data); Assert.AreEqual(10, bs[0]); data[0] = 5; Assert.AreEqual(10, bs[0]); } [Test] public void ToByteArrayCopiesContents() { ByteString bs = ByteString.CopyFromUtf8("Hello"); byte[] data = bs.ToByteArray(); Assert.AreEqual((byte)'H', data[0]); Assert.AreEqual((byte)'H', bs[0]); data[0] = 0; Assert.AreEqual(0, data[0]); Assert.AreEqual((byte)'H', bs[0]); } [Test] public void CopyFromUtf8UsesUtf8() { ByteString bs = ByteString.CopyFromUtf8("\u20ac"); Assert.AreEqual(3, bs.Length); Assert.AreEqual(0xe2, bs[0]); Assert.AreEqual(0x82, bs[1]); Assert.AreEqual(0xac, bs[2]); } [Test] public void CopyFromPortion() { byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; ByteString bs = ByteString.CopyFrom(data, 2, 3); Assert.AreEqual(3, bs.Length); Assert.AreEqual(2, bs[0]); Assert.AreEqual(3, bs[1]); } [Test] public void ToStringUtf8() { ByteString bs = ByteString.CopyFromUtf8("\u20ac"); Assert.AreEqual("\u20ac", bs.ToStringUtf8()); } [Test] public void ToStringWithExplicitEncoding() { ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode); Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode)); } [Test] public void FromBase64_WithText() { byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; string base64 = Convert.ToBase64String(data); ByteString bs = ByteString.FromBase64(base64); Assert.AreEqual(data, bs.ToByteArray()); } [Test] public void FromBase64_Empty() { // Optimization which also fixes issue 61. Assert.AreSame(ByteString.Empty, ByteString.FromBase64("")); } [Test] public void FromStream_Seekable() { var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); // Consume the first byte, just to test that it's "from current position" stream.ReadByte(); var actual = ByteString.FromStream(stream); ByteString expected = ByteString.CopyFrom(2, 3, 4, 5); Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); } [Test] public void FromStream_NotSeekable() { var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); // Consume the first byte, just to test that it's "from current position" stream.ReadByte(); // Wrap the original stream in LimitedInputStream, which has CanSeek=false var limitedStream = new LimitedInputStream(stream, 3); var actual = ByteString.FromStream(limitedStream); ByteString expected = ByteString.CopyFrom(2, 3, 4); Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); } #if !NET35 [Test] public async Task FromStreamAsync_Seekable() { var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); // Consume the first byte, just to test that it's "from current position" stream.ReadByte(); var actual = await ByteString.FromStreamAsync(stream); ByteString expected = ByteString.CopyFrom(2, 3, 4, 5); Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); } [Test] public async Task FromStreamAsync_NotSeekable() { var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); // Consume the first byte, just to test that it's "from current position" stream.ReadByte(); // Wrap the original stream in LimitedInputStream, which has CanSeek=false var limitedStream = new LimitedInputStream(stream, 3); var actual = await ByteString.FromStreamAsync(limitedStream); ByteString expected = ByteString.CopyFrom(2, 3, 4); Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); } #endif [Test] public void GetHashCode_Regression() { // We used to have an awful hash algorithm where only the last four // bytes were relevant. This is a regression test for // https://github.com/protocolbuffers/protobuf/issues/2511 ByteString b1 = ByteString.CopyFrom(100, 1, 2, 3, 4); ByteString b2 = ByteString.CopyFrom(200, 1, 2, 3, 4); Assert.AreNotEqual(b1.GetHashCode(), b2.GetHashCode()); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Report email templates Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SPEMAILDataSet : EduHubDataSet<SPEMAIL> { /// <inheritdoc /> public override string Name { get { return "SPEMAIL"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SPEMAILDataSet(EduHubContext Context) : base(Context) { Index_REPORT = new Lazy<NullDictionary<string, IReadOnlyList<SPEMAIL>>>(() => this.ToGroupedNullDictionary(i => i.REPORT)); Index_SPEMAILKEY = new Lazy<Dictionary<string, SPEMAIL>>(() => this.ToDictionary(i => i.SPEMAILKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SPEMAIL" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SPEMAIL" /> fields for each CSV column header</returns> internal override Action<SPEMAIL, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SPEMAIL, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "SPEMAILKEY": mapper[i] = (e, v) => e.SPEMAILKEY = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "REPORT": mapper[i] = (e, v) => e.REPORT = v; break; case "PRINT_PATH": mapper[i] = (e, v) => e.PRINT_PATH = v; break; case "IMPORTANCE": mapper[i] = (e, v) => e.IMPORTANCE = v; break; case "SEND_OPTION": mapper[i] = (e, v) => e.SEND_OPTION = v; break; case "EMAIL_SUBJECT": mapper[i] = (e, v) => e.EMAIL_SUBJECT = v; break; case "EMAIL_MESSAGE": mapper[i] = (e, v) => e.EMAIL_MESSAGE = v; break; case "EMAIL_HTML": mapper[i] = (e, v) => e.EMAIL_HTML = v; break; case "HTML_MESSAGE": mapper[i] = (e, v) => e.HTML_MESSAGE = v; break; case "FROM_ADDRESS": mapper[i] = (e, v) => e.FROM_ADDRESS = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SPEMAIL" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SPEMAIL" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SPEMAIL" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SPEMAIL}"/> of entities</returns> internal override IEnumerable<SPEMAIL> ApplyDeltaEntities(IEnumerable<SPEMAIL> Entities, List<SPEMAIL> DeltaEntities) { HashSet<string> Index_SPEMAILKEY = new HashSet<string>(DeltaEntities.Select(i => i.SPEMAILKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.SPEMAILKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_SPEMAILKEY.Remove(entity.SPEMAILKEY); if (entity.SPEMAILKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<SPEMAIL>>> Index_REPORT; private Lazy<Dictionary<string, SPEMAIL>> Index_SPEMAILKEY; #endregion #region Index Methods /// <summary> /// Find SPEMAIL by REPORT field /// </summary> /// <param name="REPORT">REPORT value used to find SPEMAIL</param> /// <returns>List of related SPEMAIL entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SPEMAIL> FindByREPORT(string REPORT) { return Index_REPORT.Value[REPORT]; } /// <summary> /// Attempt to find SPEMAIL by REPORT field /// </summary> /// <param name="REPORT">REPORT value used to find SPEMAIL</param> /// <param name="Value">List of related SPEMAIL entities</param> /// <returns>True if the list of related SPEMAIL entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByREPORT(string REPORT, out IReadOnlyList<SPEMAIL> Value) { return Index_REPORT.Value.TryGetValue(REPORT, out Value); } /// <summary> /// Attempt to find SPEMAIL by REPORT field /// </summary> /// <param name="REPORT">REPORT value used to find SPEMAIL</param> /// <returns>List of related SPEMAIL entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SPEMAIL> TryFindByREPORT(string REPORT) { IReadOnlyList<SPEMAIL> value; if (Index_REPORT.Value.TryGetValue(REPORT, out value)) { return value; } else { return null; } } /// <summary> /// Find SPEMAIL by SPEMAILKEY field /// </summary> /// <param name="SPEMAILKEY">SPEMAILKEY value used to find SPEMAIL</param> /// <returns>Related SPEMAIL entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SPEMAIL FindBySPEMAILKEY(string SPEMAILKEY) { return Index_SPEMAILKEY.Value[SPEMAILKEY]; } /// <summary> /// Attempt to find SPEMAIL by SPEMAILKEY field /// </summary> /// <param name="SPEMAILKEY">SPEMAILKEY value used to find SPEMAIL</param> /// <param name="Value">Related SPEMAIL entity</param> /// <returns>True if the related SPEMAIL entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySPEMAILKEY(string SPEMAILKEY, out SPEMAIL Value) { return Index_SPEMAILKEY.Value.TryGetValue(SPEMAILKEY, out Value); } /// <summary> /// Attempt to find SPEMAIL by SPEMAILKEY field /// </summary> /// <param name="SPEMAILKEY">SPEMAILKEY value used to find SPEMAIL</param> /// <returns>Related SPEMAIL entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SPEMAIL TryFindBySPEMAILKEY(string SPEMAILKEY) { SPEMAIL value; if (Index_SPEMAILKEY.Value.TryGetValue(SPEMAILKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SPEMAIL table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SPEMAIL]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SPEMAIL]( [SPEMAILKEY] varchar(15) NOT NULL, [DESCRIPTION] varchar(50) NULL, [REPORT] varchar(10) NULL, [PRINT_PATH] varchar(128) NULL, [IMPORTANCE] varchar(6) NULL, [SEND_OPTION] varchar(15) NULL, [EMAIL_SUBJECT] varchar(70) NULL, [EMAIL_MESSAGE] varchar(MAX) NULL, [EMAIL_HTML] varchar(128) NULL, [HTML_MESSAGE] varchar(1) NULL, [FROM_ADDRESS] varchar(128) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SPEMAIL_Index_SPEMAILKEY] PRIMARY KEY CLUSTERED ( [SPEMAILKEY] ASC ) ); CREATE NONCLUSTERED INDEX [SPEMAIL_Index_REPORT] ON [dbo].[SPEMAIL] ( [REPORT] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SPEMAIL]') AND name = N'SPEMAIL_Index_REPORT') ALTER INDEX [SPEMAIL_Index_REPORT] ON [dbo].[SPEMAIL] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SPEMAIL]') AND name = N'SPEMAIL_Index_REPORT') ALTER INDEX [SPEMAIL_Index_REPORT] ON [dbo].[SPEMAIL] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SPEMAIL"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SPEMAIL"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SPEMAIL> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_SPEMAILKEY = new List<string>(); foreach (var entity in Entities) { Index_SPEMAILKEY.Add(entity.SPEMAILKEY); } builder.AppendLine("DELETE [dbo].[SPEMAIL] WHERE"); // Index_SPEMAILKEY builder.Append("[SPEMAILKEY] IN ("); for (int index = 0; index < Index_SPEMAILKEY.Count; index++) { if (index != 0) builder.Append(", "); // SPEMAILKEY var parameterSPEMAILKEY = $"@p{parameterIndex++}"; builder.Append(parameterSPEMAILKEY); command.Parameters.Add(parameterSPEMAILKEY, SqlDbType.VarChar, 15).Value = Index_SPEMAILKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SPEMAIL data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SPEMAIL data set</returns> public override EduHubDataSetDataReader<SPEMAIL> GetDataSetDataReader() { return new SPEMAILDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SPEMAIL data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SPEMAIL data set</returns> public override EduHubDataSetDataReader<SPEMAIL> GetDataSetDataReader(List<SPEMAIL> Entities) { return new SPEMAILDataReader(new EduHubDataSetLoadedReader<SPEMAIL>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SPEMAILDataReader : EduHubDataSetDataReader<SPEMAIL> { public SPEMAILDataReader(IEduHubDataSetReader<SPEMAIL> Reader) : base (Reader) { } public override int FieldCount { get { return 14; } } public override object GetValue(int i) { switch (i) { case 0: // SPEMAILKEY return Current.SPEMAILKEY; case 1: // DESCRIPTION return Current.DESCRIPTION; case 2: // REPORT return Current.REPORT; case 3: // PRINT_PATH return Current.PRINT_PATH; case 4: // IMPORTANCE return Current.IMPORTANCE; case 5: // SEND_OPTION return Current.SEND_OPTION; case 6: // EMAIL_SUBJECT return Current.EMAIL_SUBJECT; case 7: // EMAIL_MESSAGE return Current.EMAIL_MESSAGE; case 8: // EMAIL_HTML return Current.EMAIL_HTML; case 9: // HTML_MESSAGE return Current.HTML_MESSAGE; case 10: // FROM_ADDRESS return Current.FROM_ADDRESS; case 11: // LW_DATE return Current.LW_DATE; case 12: // LW_TIME return Current.LW_TIME; case 13: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DESCRIPTION return Current.DESCRIPTION == null; case 2: // REPORT return Current.REPORT == null; case 3: // PRINT_PATH return Current.PRINT_PATH == null; case 4: // IMPORTANCE return Current.IMPORTANCE == null; case 5: // SEND_OPTION return Current.SEND_OPTION == null; case 6: // EMAIL_SUBJECT return Current.EMAIL_SUBJECT == null; case 7: // EMAIL_MESSAGE return Current.EMAIL_MESSAGE == null; case 8: // EMAIL_HTML return Current.EMAIL_HTML == null; case 9: // HTML_MESSAGE return Current.HTML_MESSAGE == null; case 10: // FROM_ADDRESS return Current.FROM_ADDRESS == null; case 11: // LW_DATE return Current.LW_DATE == null; case 12: // LW_TIME return Current.LW_TIME == null; case 13: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // SPEMAILKEY return "SPEMAILKEY"; case 1: // DESCRIPTION return "DESCRIPTION"; case 2: // REPORT return "REPORT"; case 3: // PRINT_PATH return "PRINT_PATH"; case 4: // IMPORTANCE return "IMPORTANCE"; case 5: // SEND_OPTION return "SEND_OPTION"; case 6: // EMAIL_SUBJECT return "EMAIL_SUBJECT"; case 7: // EMAIL_MESSAGE return "EMAIL_MESSAGE"; case 8: // EMAIL_HTML return "EMAIL_HTML"; case 9: // HTML_MESSAGE return "HTML_MESSAGE"; case 10: // FROM_ADDRESS return "FROM_ADDRESS"; case 11: // LW_DATE return "LW_DATE"; case 12: // LW_TIME return "LW_TIME"; case 13: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "SPEMAILKEY": return 0; case "DESCRIPTION": return 1; case "REPORT": return 2; case "PRINT_PATH": return 3; case "IMPORTANCE": return 4; case "SEND_OPTION": return 5; case "EMAIL_SUBJECT": return 6; case "EMAIL_MESSAGE": return 7; case "EMAIL_HTML": return 8; case "HTML_MESSAGE": return 9; case "FROM_ADDRESS": return 10; case "LW_DATE": return 11; case "LW_TIME": return 12; case "LW_USER": return 13; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
/* * @(#)Function1Arg.cs 4.1.0 2017-04-18 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``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 <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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * [email protected] * http://mathparser.org * http://mathspace.pl * http://janetsudoku.mariuszgromada.org * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser * http://mxparser.sourceforge.net * http://bitbucket.org/mariuszgromada/mxparser * http://mxparser.codeplex.com * http://github.com/mariuszgromada/Janet-Sudoku * http://janetsudoku.codeplex.com * http://sourceforge.net/projects/janetsudoku * http://bitbucket.org/mariuszgromada/janet-sudoku * http://github.com/mariuszgromada/MathParser.org-mXparser * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ using System; namespace org.mariuszgromada.math.mxparser.parsertokens { /** * Unary functions (1 argument) - mXparser tokens definition. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:[email protected]">[email protected]</a><br> * <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br> * <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br> * <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br> * <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br> * <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br> * <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br> * * @version 3.1.0 */ [CLSCompliant(true)] public sealed class Function1Arg { /* * UnaryFunction - token type id. */ public const int TYPE_ID = 4; public const String TYPE_DESC = "Unary Function"; /* * UnaryFunction - tokens id. */ public const int SIN_ID = 1; public const int COS_ID = 2; public const int TAN_ID = 3; public const int CTAN_ID = 4; public const int SEC_ID = 5; public const int COSEC_ID = 6; public const int ASIN_ID = 7; public const int ACOS_ID = 8; public const int ATAN_ID = 9; public const int ACTAN_ID = 10; public const int LN_ID = 11; public const int LOG2_ID = 12; public const int LOG10_ID = 13; public const int RAD_ID = 14; public const int EXP_ID = 15; public const int SQRT_ID = 16; public const int SINH_ID = 17; public const int COSH_ID = 18; public const int TANH_ID = 19; public const int COTH_ID = 20; public const int SECH_ID = 21; public const int CSCH_ID = 22; public const int DEG_ID = 23; public const int ABS_ID = 24; public const int SGN_ID = 25; public const int FLOOR_ID = 26; public const int CEIL_ID = 27; public const int NOT_ID = 29; public const int ARSINH_ID = 30; public const int ARCOSH_ID = 31; public const int ARTANH_ID = 32; public const int ARCOTH_ID = 33; public const int ARSECH_ID = 34; public const int ARCSCH_ID = 35; public const int SA_ID = 36; public const int SINC_ID = 37; public const int BELL_NUMBER_ID = 38; public const int LUCAS_NUMBER_ID = 39; public const int FIBONACCI_NUMBER_ID = 40; public const int HARMONIC_NUMBER_ID = 41; public const int IS_PRIME_ID = 42; public const int PRIME_COUNT_ID = 43; public const int EXP_INT_ID = 44; public const int LOG_INT_ID = 45; public const int OFF_LOG_INT_ID = 46; public const int GAUSS_ERF_ID = 47; public const int GAUSS_ERFC_ID = 48; public const int GAUSS_ERF_INV_ID = 49; public const int GAUSS_ERFC_INV_ID = 50; public const int ULP_ID = 51; public const int ISNAN_ID = 52; /* * UnaryFunction - tokens key words. */ public const String SIN_STR = "sin"; public const String COS_STR = "cos"; public const String TAN_STR = "tan"; public const String TG_STR = "tg"; public const String CTAN_STR = "ctan"; public const String CTG_STR = "ctg"; public const String COT_STR = "cot"; public const String SEC_STR = "sec"; public const String COSEC_STR = "cosec"; public const String CSC_STR = "csc"; public const String ASIN_STR = "asin"; public const String ARSIN_STR = "arsin"; public const String ARCSIN_STR = "arcsin"; public const String ACOS_STR = "acos"; public const String ARCOS_STR = "arcos"; public const String ARCCOS_STR = "arccos"; public const String ATAN_STR = "atan"; public const String ARCTAN_STR = "arctan"; public const String ATG_STR = "atg"; public const String ARCTG_STR = "arctg"; public const String ACTAN_STR = "actan"; public const String ARCCTAN_STR = "arcctan"; public const String ACTG_STR = "actg"; public const String ARCCTG_STR = "arcctg"; public const String ACOT_STR = "acot"; public const String ARCCOT_STR = "arccot"; public const String LN_STR = "ln"; public const String LOG2_STR = "log2"; public const String LOG10_STR = "log10"; public const String RAD_STR = "rad"; public const String EXP_STR = "exp"; public const String SQRT_STR = "sqrt"; public const String SINH_STR = "sinh"; public const String COSH_STR = "cosh"; public const String TANH_STR = "tanh"; public const String TGH_STR = "tgh"; public const String CTANH_STR = "ctanh"; public const String COTH_STR = "coth"; public const String CTGH_STR = "ctgh"; public const String SECH_STR = "sech"; public const String CSCH_STR = "csch"; public const String COSECH_STR = "cosech"; public const String DEG_STR = "deg"; public const String ABS_STR = "abs"; public const String SGN_STR = "sgn"; public const String FLOOR_STR = "floor"; public const String CEIL_STR = "ceil"; public const String NOT_STR = "not"; public const String ASINH_STR = "asinh"; public const String ARSINH_STR = "arsinh"; public const String ARCSINH_STR = "arcsinh"; public const String ACOSH_STR = "acosh"; public const String ARCOSH_STR = "arcosh"; public const String ARCCOSH_STR = "arccosh"; public const String ATANH_STR = "atanh"; public const String ARCTANH_STR = "arctanh"; public const String ATGH_STR = "atgh"; public const String ARCTGH_STR = "arctgh"; public const String ACTANH_STR = "actanh"; public const String ARCCTANH_STR = "arcctanh"; public const String ACOTH_STR = "acoth"; public const String ARCOTH_STR = "arcoth"; public const String ARCCOTH_STR = "arccoth"; public const String ACTGH_STR = "actgh"; public const String ARCCTGH_STR = "arcctgh"; public const String ASECH_STR = "asech"; public const String ARSECH_STR = "arsech"; public const String ARCSECH_STR = "arcsech"; public const String ACSCH_STR = "acsch"; public const String ARCSCH_STR = "arcsch"; public const String ARCCSCH_STR = "arccsch"; public const String ACOSECH_STR = "acosech"; public const String ARCOSECH_STR = "arcosech"; public const String ARCCOSECH_STR = "arccosech"; public const String SA_STR = "sinc"; public const String SA1_STR = "Sa"; public const String SINC_STR = "Sinc"; public const String BELL_NUMBER_STR = "Bell"; public const String LUCAS_NUMBER_STR = "Luc"; public const String FIBONACCI_NUMBER_STR = "Fib"; public const String HARMONIC_NUMBER_STR = "harm"; public const String IS_PRIME_STR = "ispr"; public const String PRIME_COUNT_STR = "Pi"; public const String EXP_INT_STR = "Ei"; public const String LOG_INT_STR = "li"; public const String OFF_LOG_INT_STR = "Li"; public const String GAUSS_ERF_STR = "erf"; public const String GAUSS_ERFC_STR = "erfc"; public const String GAUSS_ERF_INV_STR = "erfInv"; public const String GAUSS_ERFC_INV_STR = "erfcInv"; public const String ULP_STR = "ulp"; public const String ISNAN_STR = "isNaN"; /* * UnaryFunction - tokens description. */ public const String SIN_DESC = "trigonometric sine function"; public const String COS_DESC = "trigonometric cosine function"; public const String TAN_DESC = "trigonometric tangent function"; public const String CTAN_DESC = "trigonometric cotangent function"; public const String SEC_DESC = "trigonometric secant function"; public const String COSEC_DESC = "trigonometric cosecant function"; public const String ASIN_DESC = "inverse trigonometric sine function"; public const String ACOS_DESC = "inverse trigonometric cosine function"; public const String ATAN_DESC = "inverse trigonometric tangent function"; public const String ACTAN_DESC = "inverse trigonometric cotangent function"; public const String LN_DESC = "natural logarithm function (base e)"; public const String LOG2_DESC = "binary logarithm function (base 2)"; public const String LOG10_DESC = "common logarithm function (base 10)"; public const String RAD_DESC = "degrees to radians function"; public const String EXP_DESC = "exponential function"; public const String SQRT_DESC = "squre root function"; public const String SINH_DESC = "hyperbolic sine function"; public const String COSH_DESC = "hyperbolic cosine function"; public const String TANH_DESC = "hyperbolic tangent function"; public const String COTH_DESC = "hyperbolic cotangent function"; public const String SECH_DESC = "hyperbolic secant function"; public const String CSCH_DESC = "hyperbolic cosecant function"; public const String DEG_DESC = "radians to degrees function"; public const String ABS_DESC = "absolut value function"; public const String SGN_DESC = "signum function"; public const String FLOOR_DESC = "floor function"; public const String CEIL_DESC = "ceiling function"; public const String NOT_DESC = "negation function"; public const String ARSINH_DESC = "inverse hyperbolic sine function"; public const String ARCOSH_DESC = "inverse hyperbolic cosine function"; public const String ARTANH_DESC = "inverse hyperbolic tangent function"; public const String ARCOTH_DESC = "inverse hyperbolic cotangent function"; public const String ARSECH_DESC = "inverse hyperbolic secant function"; public const String ARCSCH_DESC = "inverse hyperbolic cosecant function"; public const String SA_DESC = "sinc function (normalized)"; public const String SINC_DESC = "sinc function (unnormalized)"; public const String BELL_NUMBER_DESC = "Bell number"; public const String LUCAS_NUMBER_DESC = "Lucas number"; public const String FIBONACCI_NUMBER_DESC = "Fibonacci number"; public const String HARMONIC_NUMBER_DESC = "Harmonic number"; public const String IS_PRIME_DESC = "(2.3) Prime number test (is number a prime?)"; public const String PRIME_COUNT_DESC = "(2.3) Prime-counting function - Pi(x)"; public const String EXP_INT_DESC = "(2.3) Exponential integral function (non-elementary special function) - usage example: Ei(x)"; public const String LOG_INT_DESC = "(2.3) Logarithmic integral function (non-elementary special function) - usage example: li(x)"; public const String OFF_LOG_INT_DESC = "(2.3) Offset logarithmic integral function (non-elementary special function) - usage example: Li(x)"; public const String GAUSS_ERF_DESC = "(3.0) Gauss error function (non-elementary special function) - usage example: 2 + erf(x)"; public const String GAUSS_ERFC_DESC = "(3.0) Gauss complementary error function (non-elementary special function) - usage example: 1 - erfc(x)"; public const String GAUSS_ERF_INV_DESC = "(3.0) Inverse Gauss error function (non-elementary special function) - usage example: erfInv(x)"; public const String GAUSS_ERFC_INV_DESC = "(3.0) Inverse Gauss complementary error function (non-elementary special function) - usage example: erfcInv(x)"; public const String ULP_DESC = "(3.0) Unit in The Last Place - ulp(0.1)"; public const String ISNAN_DESC = "(4.1) Returns true = 1 if value is a Not-a-Number (NaN), false = 0 otherwise - usage example: isNaN(x)"; } }
/* * NetworkStream.cs - Implementation of the * "System.Net.Sockets.NetworkStream" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Net.Sockets { using System; using System.IO; using System.Threading; public class NetworkStream : Stream { // Internal state. private Socket socket; private FileAccess access; private bool ownsSocket; private Object readLock; // Constructors. public NetworkStream(Socket socket) : this(socket, FileAccess.ReadWrite, false) { // Nothing to do here. } public NetworkStream(Socket socket, bool ownsSocket) : this(socket, FileAccess.ReadWrite, ownsSocket) { // Nothing to do here. } public NetworkStream(Socket socket, FileAccess access) : this(socket, access, false) { // Nothing to do here. } public NetworkStream(Socket socket, FileAccess access, bool ownsSocket) { // Validate the parameters. if(socket == null) { throw new ArgumentNullException("socket"); } if(!(socket.Blocking)) { throw new IOException(S._("IO_SocketNotBlocking")); } if(!(socket.Connected)) { throw new IOException(S._("IO_SocketNotConnected")); } if(socket.SocketType != SocketType.Stream) { throw new IOException(S._("IO_SocketIncorrectType")); } // Initialize the internal state. this.socket = socket; this.access = access; this.ownsSocket = ownsSocket; this.readLock = new Object(); } // Destructor. ~NetworkStream() { Dispose(false); } // Handle asynchronous operations by passing them back to the base class. // Note: we deliberately don't use the "BeginReceive" and "BeginSend" // methods on "Socket", because those methods will bypass the locking and // integrity checks that "NetworkStream" imposes. public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { return base.BeginRead(buffer, offset, count, callback, state); } public override int EndRead(IAsyncResult asyncResult) { return base.EndRead(asyncResult); } public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { return base.BeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { base.EndWrite(asyncResult); } // Close this stream. public override void Close() { Dispose(true); GC.SuppressFinalize(this); } // Dispose of this stream. protected virtual void Dispose(bool disposing) { lock(this) { if(socket != null) { if(ownsSocket) { socket.Close(); } socket = null; } } } // Flush this stream. public override void Flush() { // Nothing to do here. } // Read data from this stream. public override int Read(byte[] buffer, int offset, int count) { lock(readLock) { // Validate the stream state first. if(socket == null) { throw new ObjectDisposedException (S._("Exception_Disposed")); } else if((access & FileAccess.Read) == 0) { throw new NotSupportedException (S._("IO_NotSupp_Read")); } // Read directly from the socket. return socket.Receive (buffer, offset, count, SocketFlags.None); } } // Seek to a new location in the stream. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(S._("IO_NotSupp_Seek")); } // Set the length of this stream. public override void SetLength(long length) { throw new NotSupportedException(S._("IO_NotSupp_SetLength")); } // Write data to this stream. public override void Write(byte[] buffer, int offset, int count) { lock(this) { // Validate the stream state first. if(socket == null) { throw new ObjectDisposedException (S._("Exception_Disposed")); } else if((access & FileAccess.Write) == 0) { throw new NotSupportedException (S._("IO_NotSupp_Write")); } // Write directly to the socket. socket.Send(buffer, offset, count, SocketFlags.None); } } // Determine if we can read from this stream. public override bool CanRead { get { return ((access & FileAccess.Read) != 0); } } // Determine if we can seek within this stream. public override bool CanSeek { get { return false; } } // Determine if we can write to this stream. public override bool CanWrite { get { return ((access & FileAccess.Write) != 0); } } #if !ECMA_COMPAT // Get or set the readable state for this stream. protected bool Readable { get { return ((access & FileAccess.Read) != 0); } set { if(value) { access |= FileAccess.Read; } else { access &= ~(FileAccess.Read); } } } // Get or set the writable state for this stream. protected bool Writeable { get { return ((access & FileAccess.Write) != 0); } set { if(value) { access |= FileAccess.Write; } else { access &= ~(FileAccess.Write); } } } // Get the underlying socket. protected Socket Socket { get { return socket; } } #endif // !ECMA_COMPAT // Determine if the underlying socket has data available. public virtual bool DataAvailable { get { lock(readLock) { if(socket == null) { throw new ObjectDisposedException (S._("Exception_Disposed")); } else { return (socket.Available > 0); } } } } // Get the length of this stream. public override long Length { get { throw new NotSupportedException(S._("IO_NotSupp_Seek")); } } // Get or set the position within this stream. public override long Position { get { throw new NotSupportedException(S._("IO_NotSupp_Seek")); } set { throw new NotSupportedException(S._("IO_NotSupp_Seek")); } } }; // class NetworkStream }; // namespace System.Net.Sockets
// 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.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Internal; namespace System.Reflection.Metadata.Ecma335 { partial class MetadataBuilder { private const byte MetadataFormatMajorVersion = 2; private const byte MetadataFormatMinorVersion = 0; // type system table rows: private struct AssemblyRefTableRow { public Version Version; public BlobHandle PublicKeyToken; public StringHandle Name; public StringHandle Culture; public uint Flags; public BlobHandle HashValue; } private struct ModuleRow { public ushort Generation; public StringHandle Name; public GuidHandle ModuleVersionId; public GuidHandle EncId; public GuidHandle EncBaseId; } private struct AssemblyRow { public uint HashAlgorithm; public Version Version; public ushort Flags; public BlobHandle AssemblyKey; public StringHandle AssemblyName; public StringHandle AssemblyCulture; } private struct ClassLayoutRow { public ushort PackingSize; public uint ClassSize; public uint Parent; } private struct ConstantRow { public byte Type; public uint Parent; public BlobHandle Value; } private struct CustomAttributeRow { public uint Parent; public uint Type; public BlobHandle Value; } private struct DeclSecurityRow { public ushort Action; public uint Parent; public BlobHandle PermissionSet; } private struct EncLogRow { public uint Token; public byte FuncCode; } private struct EncMapRow { public uint Token; } private struct EventRow { public ushort EventFlags; public StringHandle Name; public uint EventType; } private struct EventMapRow { public uint Parent; public uint EventList; } private struct ExportedTypeRow { public uint Flags; public uint TypeDefId; public StringHandle TypeName; public StringHandle TypeNamespace; public uint Implementation; } private struct FieldLayoutRow { public uint Offset; public uint Field; } private struct FieldMarshalRow { public uint Parent; public BlobHandle NativeType; } private struct FieldRvaRow { public uint Offset; public uint Field; } private struct FieldDefRow { public ushort Flags; public StringHandle Name; public BlobHandle Signature; } private struct FileTableRow { public uint Flags; public StringHandle FileName; public BlobHandle HashValue; } private struct GenericParamConstraintRow { public uint Owner; public uint Constraint; } private struct GenericParamRow { public ushort Number; public ushort Flags; public uint Owner; public StringHandle Name; } private struct ImplMapRow { public ushort MappingFlags; public uint MemberForwarded; public StringHandle ImportName; public uint ImportScope; } private struct InterfaceImplRow { public uint Class; public uint Interface; } private struct ManifestResourceRow { public uint Offset; public uint Flags; public StringHandle Name; public uint Implementation; } private struct MemberRefRow { public uint Class; public StringHandle Name; public BlobHandle Signature; } private struct MethodImplRow { public uint Class; public uint MethodBody; public uint MethodDecl; } private struct MethodSemanticsRow { public ushort Semantic; public uint Method; public uint Association; } private struct MethodSpecRow { public uint Method; public BlobHandle Instantiation; } private struct MethodRow { public int BodyOffset; public ushort ImplFlags; public ushort Flags; public StringHandle Name; public BlobHandle Signature; public uint ParamList; } private struct ModuleRefRow { public StringHandle Name; } private struct NestedClassRow { public uint NestedClass; public uint EnclosingClass; } private struct ParamRow { public ushort Flags; public ushort Sequence; public StringHandle Name; } private struct PropertyMapRow { public uint Parent; public uint PropertyList; } private struct PropertyRow { public ushort PropFlags; public StringHandle Name; public BlobHandle Type; } private struct TypeDefRow { public uint Flags; public StringHandle Name; public StringHandle Namespace; public uint Extends; public uint FieldList; public uint MethodList; } private struct TypeRefRow { public uint ResolutionScope; public StringHandle Name; public StringHandle Namespace; } private struct TypeSpecRow { public BlobHandle Signature; } private struct StandaloneSigRow { public BlobHandle Signature; } // debug table rows: private struct DocumentRow { public BlobHandle Name; public GuidHandle HashAlgorithm; public BlobHandle Hash; public GuidHandle Language; } private struct MethodDebugInformationRow { public uint Document; public BlobHandle SequencePoints; } private struct LocalScopeRow { public uint Method; public uint ImportScope; public uint VariableList; public uint ConstantList; public uint StartOffset; public uint Length; } private struct LocalVariableRow { public ushort Attributes; public ushort Index; public StringHandle Name; } private struct LocalConstantRow { public StringHandle Name; public BlobHandle Signature; } private struct ImportScopeRow { public uint Parent; public BlobHandle Imports; } private struct StateMachineMethodRow { public uint MoveNextMethod; public uint KickoffMethod; } private struct CustomDebugInformationRow { public uint Parent; public GuidHandle Kind; public BlobHandle Value; } // type system tables: private readonly List<ModuleRow> _moduleTable = new List<ModuleRow>(1); private readonly List<AssemblyRow> _assemblyTable = new List<AssemblyRow>(1); private readonly List<ClassLayoutRow> _classLayoutTable = new List<ClassLayoutRow>(); private readonly List<ConstantRow> _constantTable = new List<ConstantRow>(); private uint _constantTableLastParent; private bool _constantTableNeedsSorting; private readonly List<CustomAttributeRow> _customAttributeTable = new List<CustomAttributeRow>(); private uint _customAttributeTableLastParent; private bool _customAttributeTableNeedsSorting; private readonly List<DeclSecurityRow> _declSecurityTable = new List<DeclSecurityRow>(); private uint _declSecurityTableLastParent; private bool _declSecurityTableNeedsSorting; private readonly List<EncLogRow> _encLogTable = new List<EncLogRow>(); private readonly List<EncMapRow> _encMapTable = new List<EncMapRow>(); private readonly List<EventRow> _eventTable = new List<EventRow>(); private readonly List<EventMapRow> _eventMapTable = new List<EventMapRow>(); private readonly List<ExportedTypeRow> _exportedTypeTable = new List<ExportedTypeRow>(); private readonly List<FieldLayoutRow> _fieldLayoutTable = new List<FieldLayoutRow>(); private readonly List<FieldMarshalRow> _fieldMarshalTable = new List<FieldMarshalRow>(); private uint _fieldMarshalTableLastParent; private bool _fieldMarshalTableNeedsSorting; private readonly List<FieldRvaRow> _fieldRvaTable = new List<FieldRvaRow>(); private readonly List<FieldDefRow> _fieldTable = new List<FieldDefRow>(); private readonly List<FileTableRow> _fileTable = new List<FileTableRow>(); private readonly List<GenericParamConstraintRow> _genericParamConstraintTable = new List<GenericParamConstraintRow>(); private readonly List<GenericParamRow> _genericParamTable = new List<GenericParamRow>(); private readonly List<ImplMapRow> _implMapTable = new List<ImplMapRow>(); private readonly List<InterfaceImplRow> _interfaceImplTable = new List<InterfaceImplRow>(); private readonly List<ManifestResourceRow> _manifestResourceTable = new List<ManifestResourceRow>(); private readonly List<MemberRefRow> _memberRefTable = new List<MemberRefRow>(); private readonly List<MethodImplRow> _methodImplTable = new List<MethodImplRow>(); private readonly List<MethodSemanticsRow> _methodSemanticsTable = new List<MethodSemanticsRow>(); private uint _methodSemanticsTableLastAssociation; private bool _methodSemanticsTableNeedsSorting; private readonly List<MethodSpecRow> _methodSpecTable = new List<MethodSpecRow>(); private readonly List<MethodRow> _methodDefTable = new List<MethodRow>(); private readonly List<ModuleRefRow> _moduleRefTable = new List<ModuleRefRow>(); private readonly List<NestedClassRow> _nestedClassTable = new List<NestedClassRow>(); private readonly List<ParamRow> _paramTable = new List<ParamRow>(); private readonly List<PropertyMapRow> _propertyMapTable = new List<PropertyMapRow>(); private readonly List<PropertyRow> _propertyTable = new List<PropertyRow>(); private readonly List<TypeDefRow> _typeDefTable = new List<TypeDefRow>(); private readonly List<TypeRefRow> _typeRefTable = new List<TypeRefRow>(); private readonly List<TypeSpecRow> _typeSpecTable = new List<TypeSpecRow>(); private readonly List<AssemblyRefTableRow> _assemblyRefTable = new List<AssemblyRefTableRow>(); private readonly List<StandaloneSigRow> _standAloneSigTable = new List<StandaloneSigRow>(); // debug tables: private readonly List<DocumentRow> _documentTable = new List<DocumentRow>(); private readonly List<MethodDebugInformationRow> _methodDebugInformationTable = new List<MethodDebugInformationRow>(); private readonly List<LocalScopeRow> _localScopeTable = new List<LocalScopeRow>(); private readonly List<LocalVariableRow> _localVariableTable = new List<LocalVariableRow>(); private readonly List<LocalConstantRow> _localConstantTable = new List<LocalConstantRow>(); private readonly List<ImportScopeRow> _importScopeTable = new List<ImportScopeRow>(); private readonly List<StateMachineMethodRow> _stateMachineMethodTable = new List<StateMachineMethodRow>(); private readonly List<CustomDebugInformationRow> _customDebugInformationTable = new List<CustomDebugInformationRow>(); public void SetCapacity(TableIndex table, int capacity) { switch (table) { case TableIndex.Module: _moduleTable.Capacity = capacity; break; case TableIndex.TypeRef: _typeRefTable.Capacity = capacity; break; case TableIndex.TypeDef: _typeDefTable.Capacity = capacity; break; case TableIndex.Field: _fieldTable.Capacity = capacity; break; case TableIndex.MethodDef: _methodDefTable.Capacity = capacity; break; case TableIndex.Param: _paramTable.Capacity = capacity; break; case TableIndex.InterfaceImpl: _interfaceImplTable.Capacity = capacity; break; case TableIndex.MemberRef: _memberRefTable.Capacity = capacity; break; case TableIndex.Constant: _constantTable.Capacity = capacity; break; case TableIndex.CustomAttribute: _customAttributeTable.Capacity = capacity; break; case TableIndex.FieldMarshal: _fieldMarshalTable.Capacity = capacity; break; case TableIndex.DeclSecurity: _declSecurityTable.Capacity = capacity; break; case TableIndex.ClassLayout: _classLayoutTable.Capacity = capacity; break; case TableIndex.FieldLayout: _fieldLayoutTable.Capacity = capacity; break; case TableIndex.StandAloneSig: _standAloneSigTable.Capacity = capacity; break; case TableIndex.EventMap: _eventMapTable.Capacity = capacity; break; case TableIndex.Event: _eventTable.Capacity = capacity; break; case TableIndex.PropertyMap: _propertyMapTable.Capacity = capacity; break; case TableIndex.Property: _propertyTable.Capacity = capacity; break; case TableIndex.MethodSemantics: _methodSemanticsTable.Capacity = capacity; break; case TableIndex.MethodImpl: _methodImplTable.Capacity = capacity; break; case TableIndex.ModuleRef: _moduleRefTable.Capacity = capacity; break; case TableIndex.TypeSpec: _typeSpecTable.Capacity = capacity; break; case TableIndex.ImplMap: _implMapTable.Capacity = capacity; break; case TableIndex.FieldRva: _fieldRvaTable.Capacity = capacity; break; case TableIndex.EncLog: _encLogTable.Capacity = capacity; break; case TableIndex.EncMap: _encMapTable.Capacity = capacity; break; case TableIndex.Assembly: _assemblyTable.Capacity = capacity; break; case TableIndex.AssemblyRef: _assemblyRefTable.Capacity = capacity; break; case TableIndex.File: _fileTable.Capacity = capacity; break; case TableIndex.ExportedType: _exportedTypeTable.Capacity = capacity; break; case TableIndex.ManifestResource: _manifestResourceTable.Capacity = capacity; break; case TableIndex.NestedClass: _nestedClassTable.Capacity = capacity; break; case TableIndex.GenericParam: _genericParamTable.Capacity = capacity; break; case TableIndex.MethodSpec: _methodSpecTable.Capacity = capacity; break; case TableIndex.GenericParamConstraint: _genericParamConstraintTable.Capacity = capacity; break; case TableIndex.Document: _documentTable.Capacity = capacity; break; case TableIndex.MethodDebugInformation: _methodDebugInformationTable.Capacity = capacity; break; case TableIndex.LocalScope: _localScopeTable.Capacity = capacity; break; case TableIndex.LocalVariable: _localVariableTable.Capacity = capacity; break; case TableIndex.LocalConstant: _localConstantTable.Capacity = capacity; break; case TableIndex.ImportScope: _importScopeTable.Capacity = capacity; break; case TableIndex.StateMachineMethod: _stateMachineMethodTable.Capacity = capacity; break; case TableIndex.CustomDebugInformation: _customDebugInformationTable.Capacity = capacity; break; case TableIndex.AssemblyOS: case TableIndex.AssemblyProcessor: case TableIndex.AssemblyRefOS: case TableIndex.AssemblyRefProcessor: case TableIndex.EventPtr: case TableIndex.FieldPtr: case TableIndex.MethodPtr: case TableIndex.ParamPtr: case TableIndex.PropertyPtr: throw new NotSupportedException(); default: throw new ArgumentOutOfRangeException(nameof(table)); } } #region Building public ModuleDefinitionHandle AddModule( int generation, StringHandle moduleName, GuidHandle mvid, GuidHandle encId, GuidHandle encBaseId) { _moduleTable.Add(new ModuleRow { Generation = (ushort)generation, Name = moduleName, ModuleVersionId = mvid, EncId = encId, EncBaseId = encBaseId, }); return EntityHandle.ModuleDefinition; } public AssemblyDefinitionHandle AddAssembly( StringHandle name, Version version, StringHandle culture, BlobHandle publicKey, AssemblyFlags flags, AssemblyHashAlgorithm hashAlgorithm) { _assemblyTable.Add(new AssemblyRow { Flags = (ushort)flags, HashAlgorithm = (uint)hashAlgorithm, Version = version, AssemblyKey = publicKey, AssemblyName = name, AssemblyCulture = culture }); return EntityHandle.AssemblyDefinition; } public AssemblyReferenceHandle AddAssemblyReference( StringHandle name, Version version, StringHandle culture, BlobHandle publicKeyOrToken, AssemblyFlags flags, BlobHandle hashValue) { _assemblyRefTable.Add(new AssemblyRefTableRow { Name = name, Version = version, Culture = culture, PublicKeyToken = publicKeyOrToken, Flags = (uint)flags, HashValue = hashValue }); return MetadataTokens.AssemblyReferenceHandle(_assemblyRefTable.Count); } public TypeDefinitionHandle AddTypeDefinition( TypeAttributes attributes, StringHandle @namespace, StringHandle name, EntityHandle baseType, FieldDefinitionHandle fieldList, MethodDefinitionHandle methodList) { Debug.Assert(@namespace != null); Debug.Assert(name != null); _typeDefTable.Add(new TypeDefRow { Flags = (uint)attributes, Name = name, Namespace = @namespace, Extends = baseType.IsNil ? 0 : (uint)CodedIndex.ToTypeDefOrRefOrSpec(baseType), FieldList = (uint)MetadataTokens.GetRowNumber(fieldList), MethodList = (uint)MetadataTokens.GetRowNumber(methodList) }); return MetadataTokens.TypeDefinitionHandle(_typeDefTable.Count); } public void AddTypeLayout( TypeDefinitionHandle type, ushort packingSize, uint size) { _classLayoutTable.Add(new ClassLayoutRow { Parent = (uint)MetadataTokens.GetRowNumber(type), PackingSize = packingSize, ClassSize = size }); } public InterfaceImplementationHandle AddInterfaceImplementation( TypeDefinitionHandle type, EntityHandle implementedInterface) { _interfaceImplTable.Add(new InterfaceImplRow { Class = (uint)MetadataTokens.GetRowNumber(type), Interface = (uint)CodedIndex.ToTypeDefOrRefOrSpec(implementedInterface) }); // TODO: return (InterfaceImplementationHandle)MetadataTokens.Handle(TableIndex.InterfaceImpl, _interfaceImplTable.Count); } public void AddNestedType( TypeDefinitionHandle type, TypeDefinitionHandle enclosingType) { _nestedClassTable.Add(new NestedClassRow { NestedClass = (uint)MetadataTokens.GetRowNumber(type), EnclosingClass = (uint)MetadataTokens.GetRowNumber(enclosingType) }); } public TypeReferenceHandle AddTypeReference( EntityHandle resolutionScope, StringHandle @namespace, StringHandle name) { Debug.Assert(@namespace != null); Debug.Assert(name != null); _typeRefTable.Add(new TypeRefRow { ResolutionScope = (uint)CodedIndex.ToResolutionScope(resolutionScope), Name = name, Namespace = @namespace }); return MetadataTokens.TypeReferenceHandle(_typeRefTable.Count); } public TypeSpecificationHandle AddTypeSpecification(BlobHandle signature) { _typeSpecTable.Add(new TypeSpecRow { Signature = signature }); return MetadataTokens.TypeSpecificationHandle(_typeSpecTable.Count); } public StandaloneSignatureHandle AddStandaloneSignature(BlobHandle signature) { _standAloneSigTable.Add(new StandaloneSigRow { Signature = signature }); return MetadataTokens.StandaloneSignatureHandle(_standAloneSigTable.Count); } public PropertyDefinitionHandle AddProperty(PropertyAttributes attributes, StringHandle name, BlobHandle signature) { _propertyTable.Add(new PropertyRow { PropFlags = (ushort)attributes, Name = name, Type = signature }); return MetadataTokens.PropertyDefinitionHandle(_propertyTable.Count); } public void AddPropertyMap(TypeDefinitionHandle declaringType, PropertyDefinitionHandle propertyList) { _propertyMapTable.Add(new PropertyMapRow { Parent = (uint)MetadataTokens.GetRowNumber(declaringType), PropertyList = (uint)MetadataTokens.GetRowNumber(propertyList) }); } public EventDefinitionHandle AddEvent(EventAttributes attributes, StringHandle name, EntityHandle type) { _eventTable.Add(new EventRow { EventFlags = (ushort)attributes, Name = name, EventType = (uint)CodedIndex.ToTypeDefOrRefOrSpec(type) }); return MetadataTokens.EventDefinitionHandle(_eventTable.Count); } public void AddEventMap(TypeDefinitionHandle declaringType, EventDefinitionHandle eventList) { _eventMapTable.Add(new EventMapRow { Parent = (uint)MetadataTokens.GetRowNumber(declaringType), EventList = (uint)MetadataTokens.GetRowNumber(eventList) }); } public ConstantHandle AddConstant(EntityHandle parent, object value) { uint parentCodedIndex = (uint)CodedIndex.ToHasConstant(parent); // the table is required to be sorted by Parent: _constantTableNeedsSorting |= parentCodedIndex < _constantTableLastParent; _constantTableLastParent = parentCodedIndex; _constantTable.Add(new ConstantRow { Type = (byte)MetadataWriterUtilities.GetConstantTypeCode(value), Parent = parentCodedIndex, Value = GetOrAddConstantBlob(value) }); return MetadataTokens.ConstantHandle(_constantTable.Count); } public void AddMethodSemantics(EntityHandle association, ushort semantics, MethodDefinitionHandle methodDefinition) { uint associationCodedIndex = (uint)CodedIndex.ToHasSemantics(association); // the table is required to be sorted by Association: _methodSemanticsTableNeedsSorting |= associationCodedIndex < _methodSemanticsTableLastAssociation; _methodSemanticsTableLastAssociation = associationCodedIndex; _methodSemanticsTable.Add(new MethodSemanticsRow { Association = associationCodedIndex, Method = (uint)MetadataTokens.GetRowNumber(methodDefinition), Semantic = semantics }); } public CustomAttributeHandle AddCustomAttribute(EntityHandle parent, EntityHandle constructor, BlobHandle value) { uint parentCodedIndex = (uint)CodedIndex.ToHasCustomAttribute(parent); // the table is required to be sorted by Parent: _customAttributeTableNeedsSorting |= parentCodedIndex < _customAttributeTableLastParent; _customAttributeTableLastParent = parentCodedIndex; _customAttributeTable.Add(new CustomAttributeRow { Parent = parentCodedIndex, Type = (uint)CodedIndex.ToCustomAttributeType(constructor), Value = value }); return MetadataTokens.CustomAttributeHandle(_customAttributeTable.Count); } public MethodSpecificationHandle AddMethodSpecification(EntityHandle method, BlobHandle instantiation) { _methodSpecTable.Add(new MethodSpecRow { Method = (uint)CodedIndex.ToMethodDefOrRef(method), Instantiation = instantiation }); return MetadataTokens.MethodSpecificationHandle(_methodSpecTable.Count); } public ModuleReferenceHandle AddModuleReference(StringHandle moduleName) { _moduleRefTable.Add(new ModuleRefRow { Name = moduleName }); return MetadataTokens.ModuleReferenceHandle(_moduleRefTable.Count); } public ParameterHandle AddParameter(ParameterAttributes attributes, StringHandle name, int sequenceNumber) { _paramTable.Add(new ParamRow { Flags = (ushort)attributes, Name = name, Sequence = (ushort)sequenceNumber }); return MetadataTokens.ParameterHandle(_paramTable.Count); } public GenericParameterHandle AddGenericParameter( EntityHandle parent, GenericParameterAttributes attributes, StringHandle name, int index) { _genericParamTable.Add(new GenericParamRow { Flags = (ushort)attributes, Name = name, Number = (ushort)index, Owner = (uint)CodedIndex.ToTypeOrMethodDef(parent) }); return MetadataTokens.GenericParameterHandle(_genericParamTable.Count); } public GenericParameterConstraintHandle AddGenericParameterConstraint( GenericParameterHandle genericParameter, EntityHandle constraint) { _genericParamConstraintTable.Add(new GenericParamConstraintRow { Owner = (uint)MetadataTokens.GetRowNumber(genericParameter), Constraint = (uint)CodedIndex.ToTypeDefOrRefOrSpec(constraint), }); return MetadataTokens.GenericParameterConstraintHandle(_genericParamConstraintTable.Count); } public FieldDefinitionHandle AddFieldDefinition( FieldAttributes attributes, StringHandle name, BlobHandle signature) { _fieldTable.Add(new FieldDefRow { Flags = (ushort)attributes, Name = name, Signature = signature }); return MetadataTokens.FieldDefinitionHandle(_fieldTable.Count); } public void AddFieldLayout( FieldDefinitionHandle field, int offset) { _fieldLayoutTable.Add(new FieldLayoutRow { Field = (uint)MetadataTokens.GetRowNumber(field), Offset = (uint)offset }); } public void AddMarshallingDescriptor( EntityHandle parent, BlobHandle descriptor) { uint codedIndex = (uint)CodedIndex.ToHasFieldMarshal(parent); // the table is required to be sorted by Parent: _fieldMarshalTableNeedsSorting |= codedIndex < _fieldMarshalTableLastParent; _fieldMarshalTableLastParent = codedIndex; _fieldMarshalTable.Add(new FieldMarshalRow { Parent = codedIndex, NativeType = descriptor }); } public void AddFieldRelativeVirtualAddress( FieldDefinitionHandle field, int relativeVirtualAddress) { _fieldRvaTable.Add(new FieldRvaRow { Field = (uint)MetadataTokens.GetRowNumber(field), Offset = (uint)relativeVirtualAddress }); } public MethodDefinitionHandle AddMethodDefinition( MethodAttributes attributes, MethodImplAttributes implAttributes, StringHandle name, BlobHandle signature, int bodyOffset, ParameterHandle paramList) { _methodDefTable.Add(new MethodRow { Flags = (ushort)attributes, ImplFlags = (ushort)implAttributes, Name = name, Signature = signature, BodyOffset = bodyOffset, ParamList = (uint)MetadataTokens.GetRowNumber(paramList) }); return MetadataTokens.MethodDefinitionHandle(_methodDefTable.Count); } public void AddMethodImport( EntityHandle member, MethodImportAttributes attributes, StringHandle name, ModuleReferenceHandle module) { _implMapTable.Add(new ImplMapRow { MemberForwarded = (uint)CodedIndex.ToMemberForwarded(member), ImportName = name, ImportScope = (uint)MetadataTokens.GetRowNumber(module), MappingFlags = (ushort)attributes, }); } public MethodImplementationHandle AddMethodImplementation( TypeDefinitionHandle type, EntityHandle methodBody, EntityHandle methodDeclaration) { _methodImplTable.Add(new MethodImplRow { Class = (uint)MetadataTokens.GetRowNumber(type), MethodBody = (uint)CodedIndex.ToMethodDefOrRef(methodBody), MethodDecl = (uint)CodedIndex.ToMethodDefOrRef(methodDeclaration) }); return MetadataTokens.MethodImplementationHandle(_methodImplTable.Count); } public MemberReferenceHandle AddMemberReference( EntityHandle parent, StringHandle name, BlobHandle signature) { _memberRefTable.Add(new MemberRefRow { Class = (uint)CodedIndex.ToMemberRefParent(parent), Name = name, Signature = signature }); return MetadataTokens.MemberReferenceHandle(_memberRefTable.Count); } public ManifestResourceHandle AddManifestResource( ManifestResourceAttributes attributes, StringHandle name, EntityHandle implementation, long offset) { _manifestResourceTable.Add(new ManifestResourceRow { Flags = (uint)attributes, Name = name, Implementation = implementation.IsNil ? 0 : (uint)CodedIndex.ToImplementation(implementation), Offset = (uint)offset }); return MetadataTokens.ManifestResourceHandle(_manifestResourceTable.Count); } public AssemblyFileHandle AddAssemblyFile( StringHandle name, BlobHandle hashValue, bool containsMetadata) { _fileTable.Add(new FileTableRow { FileName = name, Flags = containsMetadata ? 0u : 1u, HashValue = hashValue }); return MetadataTokens.AssemblyFileHandle(_fileTable.Count); } public ExportedTypeHandle AddExportedType( TypeAttributes attributes, StringHandle @namespace, StringHandle name, EntityHandle implementation, int typeDefinitionId) { _exportedTypeTable.Add(new ExportedTypeRow { Flags = (uint)attributes, Implementation = (uint)CodedIndex.ToImplementation(implementation), TypeNamespace = @namespace, TypeName = name, TypeDefId = (uint)typeDefinitionId }); return MetadataTokens.ExportedTypeHandle(_exportedTypeTable.Count); } // TODO: remove public uint GetExportedTypeFlags(int rowId) { return _exportedTypeTable[rowId].Flags; } public DeclarativeSecurityAttributeHandle AddDeclarativeSecurityAttribute( EntityHandle parent, DeclarativeSecurityAction action, BlobHandle permissionSet) { uint parentCodedIndex = (uint)CodedIndex.ToHasDeclSecurity(parent); // the table is required to be sorted by Parent: _declSecurityTableNeedsSorting |= parentCodedIndex < _declSecurityTableLastParent; _declSecurityTableLastParent = parentCodedIndex; _declSecurityTable.Add(new DeclSecurityRow { Parent = parentCodedIndex, Action = (ushort)action, PermissionSet = permissionSet }); return MetadataTokens.DeclarativeSecurityAttributeHandle(_declSecurityTable.Count); } public void AddEncLogEntry(EntityHandle entity, EditAndContinueOperation code) { _encLogTable.Add(new EncLogRow { Token = (uint)MetadataTokens.GetToken(entity), FuncCode = (byte)code }); } public void AddEncMapEntry(EntityHandle entity) { _encMapTable.Add(new EncMapRow { Token = (uint)MetadataTokens.GetToken(entity) }); } public DocumentHandle AddDocument(BlobHandle name, GuidHandle hashAlgorithm, BlobHandle hash, GuidHandle language) { _documentTable.Add(new DocumentRow { Name = name, HashAlgorithm = hashAlgorithm, Hash = hash, Language = language }); return MetadataTokens.DocumentHandle(_documentTable.Count); } public MethodDebugInformationHandle AddMethodDebugInformation(DocumentHandle document, BlobHandle sequencePoints) { _methodDebugInformationTable.Add(new MethodDebugInformationRow { Document = (uint)MetadataTokens.GetRowNumber(document), SequencePoints = sequencePoints }); // TODO: return (MethodDebugInformationHandle)MetadataTokens.Handle(TableIndex.MethodDebugInformation, _methodDebugInformationTable.Count); } public LocalScopeHandle AddLocalScope(MethodDefinitionHandle method, ImportScopeHandle importScope, LocalVariableHandle variableList, LocalConstantHandle constantList, int startOffset, int length) { _localScopeTable.Add(new LocalScopeRow { Method = (uint)MetadataTokens.GetRowNumber(method), ImportScope = (uint)MetadataTokens.GetRowNumber(importScope), VariableList = (uint)MetadataTokens.GetRowNumber(variableList), ConstantList = (uint)MetadataTokens.GetRowNumber(constantList), StartOffset = (uint)startOffset, Length = (uint)length }); return MetadataTokens.LocalScopeHandle(_localScopeTable.Count); } public LocalVariableHandle AddLocalVariable(LocalVariableAttributes attributes, int index, StringHandle name) { _localVariableTable.Add(new LocalVariableRow { Attributes = (ushort)attributes, Index = (ushort)index, Name = name }); return MetadataTokens.LocalVariableHandle(_localVariableTable.Count); } public LocalConstantHandle AddLocalConstant(StringHandle name, BlobHandle signature) { _localConstantTable.Add(new LocalConstantRow { Name = name, Signature = signature }); return MetadataTokens.LocalConstantHandle(_localConstantTable.Count); } public ImportScopeHandle AddImportScope(ImportScopeHandle parentScope, BlobHandle imports) { _importScopeTable.Add(new ImportScopeRow { Parent = (uint)MetadataTokens.GetRowNumber(parentScope), Imports = imports }); return MetadataTokens.ImportScopeHandle(_importScopeTable.Count); } public void AddStateMachineMethod(MethodDefinitionHandle moveNextMethod, MethodDefinitionHandle kickoffMethod) { _stateMachineMethodTable.Add(new StateMachineMethodRow { MoveNextMethod = (uint)MetadataTokens.GetRowNumber(moveNextMethod), KickoffMethod = (uint)MetadataTokens.GetRowNumber(kickoffMethod) }); } public CustomDebugInformationHandle AddCustomDebugInformation(EntityHandle parent, GuidHandle kind, BlobHandle value) { _customDebugInformationTable.Add(new CustomDebugInformationRow { Parent = (uint)CodedIndex.ToHasCustomDebugInformation(parent), Kind = kind, Value = value }); return MetadataTokens.CustomDebugInformationHandle(_customDebugInformationTable.Count); } #endregion public ImmutableArray<int> GetRowCounts() { var rowCounts = new int[MetadataTokens.TableCount]; rowCounts[(int)TableIndex.Assembly] = _assemblyTable.Count; rowCounts[(int)TableIndex.AssemblyRef] = _assemblyRefTable.Count; rowCounts[(int)TableIndex.ClassLayout] = _classLayoutTable.Count; rowCounts[(int)TableIndex.Constant] = _constantTable.Count; rowCounts[(int)TableIndex.CustomAttribute] = _customAttributeTable.Count; rowCounts[(int)TableIndex.DeclSecurity] = _declSecurityTable.Count; rowCounts[(int)TableIndex.EncLog] = _encLogTable.Count; rowCounts[(int)TableIndex.EncMap] = _encMapTable.Count; rowCounts[(int)TableIndex.EventMap] = _eventMapTable.Count; rowCounts[(int)TableIndex.Event] = _eventTable.Count; rowCounts[(int)TableIndex.ExportedType] = _exportedTypeTable.Count; rowCounts[(int)TableIndex.FieldLayout] = _fieldLayoutTable.Count; rowCounts[(int)TableIndex.FieldMarshal] = _fieldMarshalTable.Count; rowCounts[(int)TableIndex.FieldRva] = _fieldRvaTable.Count; rowCounts[(int)TableIndex.Field] = _fieldTable.Count; rowCounts[(int)TableIndex.File] = _fileTable.Count; rowCounts[(int)TableIndex.GenericParamConstraint] = _genericParamConstraintTable.Count; rowCounts[(int)TableIndex.GenericParam] = _genericParamTable.Count; rowCounts[(int)TableIndex.ImplMap] = _implMapTable.Count; rowCounts[(int)TableIndex.InterfaceImpl] = _interfaceImplTable.Count; rowCounts[(int)TableIndex.ManifestResource] = _manifestResourceTable.Count; rowCounts[(int)TableIndex.MemberRef] = _memberRefTable.Count; rowCounts[(int)TableIndex.MethodImpl] = _methodImplTable.Count; rowCounts[(int)TableIndex.MethodSemantics] = _methodSemanticsTable.Count; rowCounts[(int)TableIndex.MethodSpec] = _methodSpecTable.Count; rowCounts[(int)TableIndex.MethodDef] = _methodDefTable.Count; rowCounts[(int)TableIndex.ModuleRef] = _moduleRefTable.Count; rowCounts[(int)TableIndex.Module] = _moduleTable.Count; rowCounts[(int)TableIndex.NestedClass] = _nestedClassTable.Count; rowCounts[(int)TableIndex.Param] = _paramTable.Count; rowCounts[(int)TableIndex.PropertyMap] = _propertyMapTable.Count; rowCounts[(int)TableIndex.Property] = _propertyTable.Count; rowCounts[(int)TableIndex.StandAloneSig] = _standAloneSigTable.Count; rowCounts[(int)TableIndex.TypeDef] = _typeDefTable.Count; rowCounts[(int)TableIndex.TypeRef] = _typeRefTable.Count; rowCounts[(int)TableIndex.TypeSpec] = _typeSpecTable.Count; rowCounts[(int)TableIndex.Document] = _documentTable.Count; rowCounts[(int)TableIndex.MethodDebugInformation] = _methodDebugInformationTable.Count; rowCounts[(int)TableIndex.LocalScope] = _localScopeTable.Count; rowCounts[(int)TableIndex.LocalVariable] = _localVariableTable.Count; rowCounts[(int)TableIndex.LocalConstant] = _localConstantTable.Count; rowCounts[(int)TableIndex.StateMachineMethod] = _stateMachineMethodTable.Count; rowCounts[(int)TableIndex.ImportScope] = _importScopeTable.Count; rowCounts[(int)TableIndex.CustomDebugInformation] = _customDebugInformationTable.Count; return ImmutableArray.CreateRange(rowCounts); } #region Serialization internal void SerializeMetadataTables( BlobBuilder writer, MetadataSizes metadataSizes, int methodBodyStreamRva, int mappedFieldDataStreamRva) { int startPosition = writer.Count; this.SerializeTablesHeader(writer, metadataSizes); if (metadataSizes.IsPresent(TableIndex.Module)) { SerializeModuleTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.TypeRef)) { this.SerializeTypeRefTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.TypeDef)) { this.SerializeTypeDefTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.Field)) { this.SerializeFieldTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.MethodDef)) { this.SerializeMethodDefTable(writer, metadataSizes, methodBodyStreamRva); } if (metadataSizes.IsPresent(TableIndex.Param)) { this.SerializeParamTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.InterfaceImpl)) { this.SerializeInterfaceImplTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.MemberRef)) { this.SerializeMemberRefTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.Constant)) { this.SerializeConstantTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.CustomAttribute)) { this.SerializeCustomAttributeTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.FieldMarshal)) { this.SerializeFieldMarshalTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.DeclSecurity)) { this.SerializeDeclSecurityTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.ClassLayout)) { this.SerializeClassLayoutTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.FieldLayout)) { this.SerializeFieldLayoutTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.StandAloneSig)) { this.SerializeStandAloneSigTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.EventMap)) { this.SerializeEventMapTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.Event)) { this.SerializeEventTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.PropertyMap)) { this.SerializePropertyMapTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.Property)) { this.SerializePropertyTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.MethodSemantics)) { this.SerializeMethodSemanticsTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.MethodImpl)) { this.SerializeMethodImplTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.ModuleRef)) { this.SerializeModuleRefTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.TypeSpec)) { this.SerializeTypeSpecTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.ImplMap)) { this.SerializeImplMapTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.FieldRva)) { this.SerializeFieldRvaTable(writer, metadataSizes, mappedFieldDataStreamRva); } if (metadataSizes.IsPresent(TableIndex.EncLog)) { this.SerializeEncLogTable(writer); } if (metadataSizes.IsPresent(TableIndex.EncMap)) { this.SerializeEncMapTable(writer); } if (metadataSizes.IsPresent(TableIndex.Assembly)) { this.SerializeAssemblyTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.AssemblyRef)) { this.SerializeAssemblyRefTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.File)) { this.SerializeFileTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.ExportedType)) { this.SerializeExportedTypeTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.ManifestResource)) { this.SerializeManifestResourceTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.NestedClass)) { this.SerializeNestedClassTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.GenericParam)) { this.SerializeGenericParamTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.MethodSpec)) { this.SerializeMethodSpecTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.GenericParamConstraint)) { this.SerializeGenericParamConstraintTable(writer, metadataSizes); } // debug tables if (metadataSizes.IsPresent(TableIndex.Document)) { this.SerializeDocumentTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.MethodDebugInformation)) { this.SerializeMethodDebugInformationTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.LocalScope)) { this.SerializeLocalScopeTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.LocalVariable)) { this.SerializeLocalVariableTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.LocalConstant)) { this.SerializeLocalConstantTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.ImportScope)) { this.SerializeImportScopeTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.StateMachineMethod)) { this.SerializeStateMachineMethodTable(writer, metadataSizes); } if (metadataSizes.IsPresent(TableIndex.CustomDebugInformation)) { this.SerializeCustomDebugInformationTable(writer, metadataSizes); } writer.WriteByte(0); writer.Align(4); int endPosition = writer.Count; Debug.Assert(metadataSizes.MetadataTableStreamSize == endPosition - startPosition); } private void SerializeTablesHeader(BlobBuilder writer, MetadataSizes metadataSizes) { int startPosition = writer.Count; HeapSizeFlag heapSizes = 0; if (metadataSizes.StringIndexSize > 2) { heapSizes |= HeapSizeFlag.StringHeapLarge; } if (metadataSizes.GuidIndexSize > 2) { heapSizes |= HeapSizeFlag.GuidHeapLarge; } if (metadataSizes.BlobIndexSize > 2) { heapSizes |= HeapSizeFlag.BlobHeapLarge; } if (metadataSizes.IsMinimalDelta) { heapSizes |= (HeapSizeFlag.EnCDeltas | HeapSizeFlag.DeletedMarks); } ulong sortedDebugTables = metadataSizes.PresentTablesMask & MetadataSizes.SortedDebugTables; // Consider filtering out type system tables that are not present: ulong sortedTables = sortedDebugTables | (metadataSizes.IsStandaloneDebugMetadata ? 0UL : 0x16003301fa00); writer.WriteUInt32(0); // reserved writer.WriteByte(MetadataFormatMajorVersion); writer.WriteByte(MetadataFormatMinorVersion); writer.WriteByte((byte)heapSizes); writer.WriteByte(1); // reserved writer.WriteUInt64(metadataSizes.PresentTablesMask); writer.WriteUInt64(sortedTables); MetadataWriterUtilities.SerializeRowCounts(writer, metadataSizes.RowCounts); int endPosition = writer.Count; Debug.Assert(metadataSizes.CalculateTableStreamHeaderSize() == endPosition - startPosition); } private void SerializeModuleTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (var moduleRow in _moduleTable) { writer.WriteUInt16(moduleRow.Generation); writer.WriteReference((uint)GetHeapOffset(moduleRow.Name), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(moduleRow.ModuleVersionId), metadataSizes.GuidIndexSize); writer.WriteReference((uint)GetHeapOffset(moduleRow.EncId), metadataSizes.GuidIndexSize); writer.WriteReference((uint)GetHeapOffset(moduleRow.EncBaseId), metadataSizes.GuidIndexSize); } } private void SerializeEncLogTable(BlobBuilder writer) { foreach (EncLogRow encLog in _encLogTable) { writer.WriteUInt32(encLog.Token); writer.WriteUInt32(encLog.FuncCode); } } private void SerializeEncMapTable(BlobBuilder writer) { foreach (EncMapRow encMap in _encMapTable) { writer.WriteUInt32(encMap.Token); } } private void SerializeTypeRefTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (TypeRefRow typeRef in _typeRefTable) { writer.WriteReference(typeRef.ResolutionScope, metadataSizes.ResolutionScopeCodedIndexSize); writer.WriteReference((uint)GetHeapOffset(typeRef.Name), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(typeRef.Namespace), metadataSizes.StringIndexSize); } } private void SerializeTypeDefTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (TypeDefRow typeDef in _typeDefTable) { writer.WriteUInt32(typeDef.Flags); writer.WriteReference((uint)GetHeapOffset(typeDef.Name), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(typeDef.Namespace), metadataSizes.StringIndexSize); writer.WriteReference(typeDef.Extends, metadataSizes.TypeDefOrRefCodedIndexSize); writer.WriteReference(typeDef.FieldList, metadataSizes.FieldDefIndexSize); writer.WriteReference(typeDef.MethodList, metadataSizes.MethodDefIndexSize); } } private void SerializeFieldTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (FieldDefRow fieldDef in _fieldTable) { writer.WriteUInt16(fieldDef.Flags); writer.WriteReference((uint)GetHeapOffset(fieldDef.Name), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(fieldDef.Signature), metadataSizes.BlobIndexSize); } } private void SerializeMethodDefTable(BlobBuilder writer, MetadataSizes metadataSizes, int methodBodyStreamRva) { foreach (MethodRow method in _methodDefTable) { if (method.BodyOffset == -1) { writer.WriteUInt32(0); } else { writer.WriteUInt32((uint)(methodBodyStreamRva + method.BodyOffset)); } writer.WriteUInt16(method.ImplFlags); writer.WriteUInt16(method.Flags); writer.WriteReference((uint)GetHeapOffset(method.Name), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(method.Signature), metadataSizes.BlobIndexSize); writer.WriteReference(method.ParamList, metadataSizes.ParameterIndexSize); } } private void SerializeParamTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (ParamRow param in _paramTable) { writer.WriteUInt16(param.Flags); writer.WriteUInt16(param.Sequence); writer.WriteReference((uint)GetHeapOffset(param.Name), metadataSizes.StringIndexSize); } } private void SerializeInterfaceImplTable(BlobBuilder writer, MetadataSizes metadataSizes) { // TODO (bug https://github.com/dotnet/roslyn/issues/3905): // We should sort the table by Class and then by Interface. foreach (InterfaceImplRow interfaceImpl in _interfaceImplTable) { writer.WriteReference(interfaceImpl.Class, metadataSizes.TypeDefIndexSize); writer.WriteReference(interfaceImpl.Interface, metadataSizes.TypeDefOrRefCodedIndexSize); } } private void SerializeMemberRefTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (MemberRefRow memberRef in _memberRefTable) { writer.WriteReference(memberRef.Class, metadataSizes.MemberRefParentCodedIndexSize); writer.WriteReference((uint)GetHeapOffset(memberRef.Name), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(memberRef.Signature), metadataSizes.BlobIndexSize); } } private void SerializeConstantTable(BlobBuilder writer, MetadataSizes metadataSizes) { // Note: we can sort the table at this point since no other table can reference its rows via RowId or CodedIndex (which would need updating otherwise). var ordered = _constantTableNeedsSorting ? (IEnumerable<ConstantRow>)_constantTable.OrderBy((x, y) => (int)x.Parent - (int)y.Parent) : _constantTable; foreach (ConstantRow constant in ordered) { writer.WriteByte(constant.Type); writer.WriteByte(0); writer.WriteReference(constant.Parent, metadataSizes.HasConstantCodedIndexSize); writer.WriteReference((uint)GetHeapOffset(constant.Value), metadataSizes.BlobIndexSize); } } private void SerializeCustomAttributeTable(BlobBuilder writer, MetadataSizes metadataSizes) { // Note: we can sort the table at this point since no other table can reference its rows via RowId or CodedIndex (which would need updating otherwise). // OrderBy performs a stable sort, so multiple attributes with the same parent will be sorted in the order they were added to the table. var ordered = _customAttributeTableNeedsSorting ? (IEnumerable<CustomAttributeRow>)_customAttributeTable.OrderBy((x, y) => (int)x.Parent - (int)y.Parent) : _customAttributeTable; foreach (CustomAttributeRow customAttribute in ordered) { writer.WriteReference(customAttribute.Parent, metadataSizes.HasCustomAttributeCodedIndexSize); writer.WriteReference(customAttribute.Type, metadataSizes.CustomAttributeTypeCodedIndexSize); writer.WriteReference((uint)GetHeapOffset(customAttribute.Value), metadataSizes.BlobIndexSize); } } private void SerializeFieldMarshalTable(BlobBuilder writer, MetadataSizes metadataSizes) { // Note: we can sort the table at this point since no other table can reference its rows via RowId or CodedIndex (which would need updating otherwise). var ordered = _fieldMarshalTableNeedsSorting ? (IEnumerable<FieldMarshalRow>)_fieldMarshalTable.OrderBy((x, y) => (int)x.Parent - (int)y.Parent) : _fieldMarshalTable; foreach (FieldMarshalRow fieldMarshal in ordered) { writer.WriteReference(fieldMarshal.Parent, metadataSizes.HasFieldMarshalCodedIndexSize); writer.WriteReference((uint)GetHeapOffset(fieldMarshal.NativeType), metadataSizes.BlobIndexSize); } } private void SerializeDeclSecurityTable(BlobBuilder writer, MetadataSizes metadataSizes) { // Note: we can sort the table at this point since no other table can reference its rows via RowId or CodedIndex (which would need updating otherwise). // OrderBy performs a stable sort, so multiple attributes with the same parent will be sorted in the order they were added to the table. var ordered = _declSecurityTableNeedsSorting ? (IEnumerable<DeclSecurityRow>)_declSecurityTable.OrderBy((x, y) => (int)x.Parent - (int)y.Parent) : _declSecurityTable; foreach (DeclSecurityRow declSecurity in ordered) { writer.WriteUInt16(declSecurity.Action); writer.WriteReference(declSecurity.Parent, metadataSizes.DeclSecurityCodedIndexSize); writer.WriteReference((uint)GetHeapOffset(declSecurity.PermissionSet), metadataSizes.BlobIndexSize); } } private void SerializeClassLayoutTable(BlobBuilder writer, MetadataSizes metadataSizes) { #if DEBUG for (int i = 1; i < _classLayoutTable.Count; i++) { Debug.Assert(_classLayoutTable[i - 1].Parent < _classLayoutTable[i].Parent); } #endif foreach (ClassLayoutRow classLayout in _classLayoutTable) { writer.WriteUInt16(classLayout.PackingSize); writer.WriteUInt32(classLayout.ClassSize); writer.WriteReference(classLayout.Parent, metadataSizes.TypeDefIndexSize); } } private void SerializeFieldLayoutTable(BlobBuilder writer, MetadataSizes metadataSizes) { #if DEBUG for (int i = 1; i < _fieldLayoutTable.Count; i++) { Debug.Assert(_fieldLayoutTable[i - 1].Field < _fieldLayoutTable[i].Field); } #endif foreach (FieldLayoutRow fieldLayout in _fieldLayoutTable) { writer.WriteUInt32(fieldLayout.Offset); writer.WriteReference(fieldLayout.Field, metadataSizes.FieldDefIndexSize); } } private void SerializeStandAloneSigTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (StandaloneSigRow row in _standAloneSigTable) { writer.WriteReference((uint)GetHeapOffset(row.Signature), metadataSizes.BlobIndexSize); } } private void SerializeEventMapTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (EventMapRow eventMap in _eventMapTable) { writer.WriteReference(eventMap.Parent, metadataSizes.TypeDefIndexSize); writer.WriteReference(eventMap.EventList, metadataSizes.EventDefIndexSize); } } private void SerializeEventTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (EventRow eventRow in _eventTable) { writer.WriteUInt16(eventRow.EventFlags); writer.WriteReference((uint)GetHeapOffset(eventRow.Name), metadataSizes.StringIndexSize); writer.WriteReference(eventRow.EventType, metadataSizes.TypeDefOrRefCodedIndexSize); } } private void SerializePropertyMapTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (PropertyMapRow propertyMap in _propertyMapTable) { writer.WriteReference(propertyMap.Parent, metadataSizes.TypeDefIndexSize); writer.WriteReference(propertyMap.PropertyList, metadataSizes.PropertyDefIndexSize); } } private void SerializePropertyTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (PropertyRow property in _propertyTable) { writer.WriteUInt16(property.PropFlags); writer.WriteReference((uint)GetHeapOffset(property.Name), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(property.Type), metadataSizes.BlobIndexSize); } } private void SerializeMethodSemanticsTable(BlobBuilder writer, MetadataSizes metadataSizes) { // Note: we can sort the table at this point since no other table can reference its rows via RowId or CodedIndex (which would need updating otherwise). // OrderBy performs a stable sort, so multiple attributes with the same parent will be sorted in the order they were added to the table. var ordered = _methodSemanticsTableNeedsSorting ? (IEnumerable<MethodSemanticsRow>)_methodSemanticsTable.OrderBy((x, y) => (int)x.Association - (int)y.Association) : _methodSemanticsTable; foreach (MethodSemanticsRow methodSemantic in ordered) { writer.WriteUInt16(methodSemantic.Semantic); writer.WriteReference(methodSemantic.Method, metadataSizes.MethodDefIndexSize); writer.WriteReference(methodSemantic.Association, metadataSizes.HasSemanticsCodedIndexSize); } } private void SerializeMethodImplTable(BlobBuilder writer, MetadataSizes metadataSizes) { #if DEBUG for (int i = 1; i < _methodImplTable.Count; i++) { Debug.Assert(_methodImplTable[i - 1].Class <= _methodImplTable[i].Class); } #endif foreach (MethodImplRow methodImpl in _methodImplTable) { writer.WriteReference(methodImpl.Class, metadataSizes.TypeDefIndexSize); writer.WriteReference(methodImpl.MethodBody, metadataSizes.MethodDefOrRefCodedIndexSize); writer.WriteReference(methodImpl.MethodDecl, metadataSizes.MethodDefOrRefCodedIndexSize); } } private void SerializeModuleRefTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (ModuleRefRow moduleRef in _moduleRefTable) { writer.WriteReference((uint)GetHeapOffset(moduleRef.Name), metadataSizes.StringIndexSize); } } private void SerializeTypeSpecTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (TypeSpecRow typeSpec in _typeSpecTable) { writer.WriteReference((uint)GetHeapOffset(typeSpec.Signature), metadataSizes.BlobIndexSize); } } private void SerializeImplMapTable(BlobBuilder writer, MetadataSizes metadataSizes) { #if DEBUG for (int i = 1; i < _implMapTable.Count; i++) { Debug.Assert(_implMapTable[i - 1].MemberForwarded < _implMapTable[i].MemberForwarded); } #endif foreach (ImplMapRow implMap in _implMapTable) { writer.WriteUInt16(implMap.MappingFlags); writer.WriteReference(implMap.MemberForwarded, metadataSizes.MemberForwardedCodedIndexSize); writer.WriteReference((uint)GetHeapOffset(implMap.ImportName), metadataSizes.StringIndexSize); writer.WriteReference(implMap.ImportScope, metadataSizes.ModuleRefIndexSize); } } private void SerializeFieldRvaTable(BlobBuilder writer, MetadataSizes metadataSizes, int mappedFieldDataStreamRva) { #if DEBUG for (int i = 1; i < _fieldRvaTable.Count; i++) { Debug.Assert(_fieldRvaTable[i - 1].Field < _fieldRvaTable[i].Field); } #endif foreach (FieldRvaRow fieldRva in _fieldRvaTable) { writer.WriteUInt32((uint)mappedFieldDataStreamRva + fieldRva.Offset); writer.WriteReference(fieldRva.Field, metadataSizes.FieldDefIndexSize); } } private void SerializeAssemblyTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (AssemblyRow row in _assemblyTable) { writer.WriteUInt32(row.HashAlgorithm); writer.WriteUInt16((ushort)row.Version.Major); writer.WriteUInt16((ushort)row.Version.Minor); writer.WriteUInt16((ushort)row.Version.Build); writer.WriteUInt16((ushort)row.Version.Revision); writer.WriteUInt32(row.Flags); writer.WriteReference((uint)GetHeapOffset(row.AssemblyKey), metadataSizes.BlobIndexSize); writer.WriteReference((uint)GetHeapOffset(row.AssemblyName), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(row.AssemblyCulture), metadataSizes.StringIndexSize); } } private void SerializeAssemblyRefTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (AssemblyRefTableRow row in _assemblyRefTable) { writer.WriteUInt16((ushort)row.Version.Major); writer.WriteUInt16((ushort)row.Version.Minor); writer.WriteUInt16((ushort)row.Version.Build); writer.WriteUInt16((ushort)row.Version.Revision); writer.WriteUInt32(row.Flags); writer.WriteReference((uint)GetHeapOffset(row.PublicKeyToken), metadataSizes.BlobIndexSize); writer.WriteReference((uint)GetHeapOffset(row.Name), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(row.Culture), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(row.HashValue), metadataSizes.BlobIndexSize); } } private void SerializeFileTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (FileTableRow fileReference in _fileTable) { writer.WriteUInt32(fileReference.Flags); writer.WriteReference((uint)GetHeapOffset(fileReference.FileName), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(fileReference.HashValue), metadataSizes.BlobIndexSize); } } private void SerializeExportedTypeTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (ExportedTypeRow exportedType in _exportedTypeTable) { writer.WriteUInt32((uint)exportedType.Flags); writer.WriteUInt32(exportedType.TypeDefId); writer.WriteReference((uint)GetHeapOffset(exportedType.TypeName), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(exportedType.TypeNamespace), metadataSizes.StringIndexSize); writer.WriteReference(exportedType.Implementation, metadataSizes.ImplementationCodedIndexSize); } } private void SerializeManifestResourceTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (ManifestResourceRow manifestResource in _manifestResourceTable) { writer.WriteUInt32(manifestResource.Offset); writer.WriteUInt32(manifestResource.Flags); writer.WriteReference((uint)GetHeapOffset(manifestResource.Name), metadataSizes.StringIndexSize); writer.WriteReference(manifestResource.Implementation, metadataSizes.ImplementationCodedIndexSize); } } private void SerializeNestedClassTable(BlobBuilder writer, MetadataSizes metadataSizes) { #if DEBUG for (int i = 1; i < _nestedClassTable.Count; i++) { Debug.Assert(_nestedClassTable[i - 1].NestedClass <= _nestedClassTable[i].NestedClass); } #endif foreach (NestedClassRow nestedClass in _nestedClassTable) { writer.WriteReference(nestedClass.NestedClass, metadataSizes.TypeDefIndexSize); writer.WriteReference(nestedClass.EnclosingClass, metadataSizes.TypeDefIndexSize); } } private void SerializeGenericParamTable(BlobBuilder writer, MetadataSizes metadataSizes) { #if DEBUG for (int i = 1; i < _genericParamTable.Count; i++) { Debug.Assert( _genericParamTable[i - 1].Owner < _genericParamTable[i].Owner || _genericParamTable[i - 1].Owner == _genericParamTable[i].Owner && _genericParamTable[i - 1].Number < _genericParamTable[i].Number); } #endif foreach (GenericParamRow genericParam in _genericParamTable) { writer.WriteUInt16(genericParam.Number); writer.WriteUInt16(genericParam.Flags); writer.WriteReference(genericParam.Owner, metadataSizes.TypeOrMethodDefCodedIndexSize); writer.WriteReference((uint)GetHeapOffset(genericParam.Name), metadataSizes.StringIndexSize); } } private void SerializeGenericParamConstraintTable(BlobBuilder writer, MetadataSizes metadataSizes) { #if DEBUG for (int i = 1; i < _genericParamConstraintTable.Count; i++) { Debug.Assert(_genericParamConstraintTable[i - 1].Owner <= _genericParamConstraintTable[i].Owner); } #endif foreach (GenericParamConstraintRow genericParamConstraint in _genericParamConstraintTable) { writer.WriteReference(genericParamConstraint.Owner, metadataSizes.GenericParamIndexSize); writer.WriteReference(genericParamConstraint.Constraint, metadataSizes.TypeDefOrRefCodedIndexSize); } } private void SerializeMethodSpecTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (MethodSpecRow methodSpec in _methodSpecTable) { writer.WriteReference(methodSpec.Method, metadataSizes.MethodDefOrRefCodedIndexSize); writer.WriteReference((uint)GetHeapOffset(methodSpec.Instantiation), metadataSizes.BlobIndexSize); } } private void SerializeDocumentTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (var row in _documentTable) { writer.WriteReference((uint)GetHeapOffset(row.Name), metadataSizes.BlobIndexSize); writer.WriteReference((uint)GetHeapOffset(row.HashAlgorithm), metadataSizes.GuidIndexSize); writer.WriteReference((uint)GetHeapOffset(row.Hash), metadataSizes.BlobIndexSize); writer.WriteReference((uint)GetHeapOffset(row.Language), metadataSizes.GuidIndexSize); } } private void SerializeMethodDebugInformationTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (var row in _methodDebugInformationTable) { writer.WriteReference(row.Document, metadataSizes.DocumentIndexSize); writer.WriteReference((uint)GetHeapOffset(row.SequencePoints), metadataSizes.BlobIndexSize); } } private void SerializeLocalScopeTable(BlobBuilder writer, MetadataSizes metadataSizes) { #if DEBUG // Spec: The table is required to be sorted first by Method in ascending order, then by StartOffset in ascending order, then by Length in descending order. for (int i = 1; i < _localScopeTable.Count; i++) { Debug.Assert(_localScopeTable[i - 1].Method <= _localScopeTable[i].Method); if (_localScopeTable[i - 1].Method == _localScopeTable[i].Method) { Debug.Assert(_localScopeTable[i - 1].StartOffset <= _localScopeTable[i].StartOffset); if (_localScopeTable[i - 1].StartOffset == _localScopeTable[i].StartOffset) { Debug.Assert(_localScopeTable[i - 1].Length >= _localScopeTable[i].Length); } } } #endif foreach (var row in _localScopeTable) { writer.WriteReference(row.Method, metadataSizes.MethodDefIndexSize); writer.WriteReference(row.ImportScope, metadataSizes.ImportScopeIndexSize); writer.WriteReference(row.VariableList, metadataSizes.LocalVariableIndexSize); writer.WriteReference(row.ConstantList, metadataSizes.LocalConstantIndexSize); writer.WriteUInt32(row.StartOffset); writer.WriteUInt32(row.Length); } } private void SerializeLocalVariableTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (var row in _localVariableTable) { writer.WriteUInt16(row.Attributes); writer.WriteUInt16(row.Index); writer.WriteReference((uint)GetHeapOffset(row.Name), metadataSizes.StringIndexSize); } } private void SerializeLocalConstantTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (var row in _localConstantTable) { writer.WriteReference((uint)GetHeapOffset(row.Name), metadataSizes.StringIndexSize); writer.WriteReference((uint)GetHeapOffset(row.Signature), metadataSizes.BlobIndexSize); } } private void SerializeImportScopeTable(BlobBuilder writer, MetadataSizes metadataSizes) { foreach (var row in _importScopeTable) { writer.WriteReference(row.Parent, metadataSizes.ImportScopeIndexSize); writer.WriteReference((uint)GetHeapOffset(row.Imports), metadataSizes.BlobIndexSize); } } private void SerializeStateMachineMethodTable(BlobBuilder writer, MetadataSizes metadataSizes) { #if DEBUG for (int i = 1; i < _stateMachineMethodTable.Count; i++) { Debug.Assert(_stateMachineMethodTable[i - 1].MoveNextMethod < _stateMachineMethodTable[i].MoveNextMethod); } #endif foreach (var row in _stateMachineMethodTable) { writer.WriteReference(row.MoveNextMethod, metadataSizes.MethodDefIndexSize); writer.WriteReference(row.KickoffMethod, metadataSizes.MethodDefIndexSize); } } private void SerializeCustomDebugInformationTable(BlobBuilder writer, MetadataSizes metadataSizes) { // Note: we can sort the table at this point since no other table can reference its rows via RowId or CodedIndex (which would need updating otherwise). // OrderBy performs a stable sort, so multiple attributes with the same parent and kind will be sorted in the order they were added to the table. foreach (CustomDebugInformationRow row in _customDebugInformationTable.OrderBy((x, y) => { int result = (int)x.Parent - (int)y.Parent; return (result != 0) ? result : MetadataTokens.GetHeapOffset(x.Kind) - MetadataTokens.GetHeapOffset(y.Kind); })) { writer.WriteReference(row.Parent, metadataSizes.HasCustomDebugInformationSize); writer.WriteReference((uint)GetHeapOffset(row.Kind), metadataSizes.GuidIndexSize); writer.WriteReference((uint)GetHeapOffset(row.Value), metadataSizes.BlobIndexSize); } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using CSharpGuidelinesAnalyzer.Rules.Maintainability; using CSharpGuidelinesAnalyzer.Test.TestDataBuilders; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace CSharpGuidelinesAnalyzer.Test.Specs.Maintainability { public sealed class AssignEachVariableInASeparateStatementSpecs : CSharpGuidelinesAnalysisTestFixture { protected override string DiagnosticId => AssignEachVariableInASeparateStatementAnalyzer.DiagnosticId; [Fact] internal void When_two_variables_are_declared_in_separate_statements_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i; int j; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_declared_in_a_single_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; i = 5; j = 8; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; [|i = j = 5;|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_a_single_compound_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i = 5; int j = 8; [|i = j += i;|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_a_single_increment_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j = 5; [|i = j++;|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_separate_statements_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i = 5; int j = 8; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_a_single_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { [|int i = 5, j = 8;|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_a_single_compound_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i = 5; int j = 8; [|int k = j += i;|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'k' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_a_single_decrement_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int j = 5; [|int i = --j;|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_variable_is_declared_and_two_variables_are_assigned_in_a_single_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int j; [|int i = j = 5;|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_multiple_times_in_a_single_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i; int j; [|i = j = j = 5;|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_three_variables_are_assigned_in_a_single_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k; [|i = (true ? (j = 5) : (k = 7));|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i', 'j' and 'k' are assigned in a single statement"); } [Fact] internal void When_multiple_identifiers_are_assigned_in_a_single_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" abstract class C { private int field1; private int Property1 { get; set; } public abstract int this[int index] { get; set; } void M(ref int parameter1) { int local1; [|local1 = field1 = Property1 = this[0] = parameter1 = 5;|] } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'local1', 'C.field1', 'C.Property1', 'C.this[int]' and 'parameter1' are assigned in a single statement"); } [Fact] internal void When_variable_is_declared_and_multiple_identifiers_are_assigned_in_a_single_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" abstract class C { private int field1; private int Property1 { get; set; } public abstract int this[int index] { get; set; } void M(ref int parameter1) { int local1; [|int decl1 = local1 = field1 = Property1 = this[0] = parameter1 = 5;|] } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'decl1', 'local1', 'C.field1', 'C.Property1', 'C.this[int]' and 'parameter1' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_initializer_of_a_for_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k = 8; for ([|i = j = 5|]; (k = 1) > 0; k -= 2) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_sequentially_assigned_in_the_initializer_of_a_for_loop_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k = 8; for (i = 1, j = 5; (k = 1) > 0; k -= 2) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_the_initializer_of_a_for_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int k = 8; for ([|int i = 1, j = 5|]; (k += 1) > 0; k -= 2) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_condition_of_a_for_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k; for (k = 1; [|(i = j = 5) > 0|]; k -= 2) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_post_expression_of_a_for_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k; for (k = 1; (k += 1) > 0; [|i = j = 5|]) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_sequentially_assigned_in_the_post_expression_of_a_for_loop_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k; for (k = 1; (k += 1) > 0; i = 5, j = 8) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_in_the_body_of_a_for_loop_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; for (int index = 0; index < 10; index++) { i = 5; j = 8; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_the_body_of_a_for_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; for (int index = 0; index < 10; index++) { [|i = j = 5;|] } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_collection_of_a_foreach_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k; [|foreach|] (var itr in new int[i = j = 5]) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_in_the_body_of_a_foreach_loop_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; foreach (var item in new int[0]) { i = 5; j = 8; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_the_body_of_a_foreach_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; foreach (var item in new int[0]) { [|i = j = 5;|] } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_condition_of_a_while_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k; [|while|] ((i = j = 5) > 0) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_in_the_body_of_a_while_loop_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; while (true) { i = 5; j = 8; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_the_body_of_a_while_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; while (true) { [|i = j = 5;|] } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_condition_of_a_do_while_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k; do { k = 3; } [|while|] ((i = j = 5) > 0); } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_in_the_body_of_a_do_while_loop_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; do { i = 5; j = 8; } while (true); } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_the_body_of_a_do_while_loop_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; do { [|i = j = 5;|] } while (true); } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_condition_of_an_if_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k; [|if|] ((i = j = 5) > 0) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_in_the_bodies_of_an_if_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, x, y; if (true) { i = 5; j = 8; } else { x = 5; y = 8; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_the_bodies_of_an_if_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, x, y; if (true) { [|i = j = 5;|] } else { [|x = y = 5;|] } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement", "'x' and 'y' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_value_of_a_switch_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, k; [|switch|] (i = j = 5) { case 1: { k = 3; break; } default: { k = 4; break; } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_in_the_clauses_of_a_switch_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; switch (true) { case true: { i = 5; j = 8; break; } default: { i = 5; j = 8; break; } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_the_clauses_of_a_switch_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j, x, y; switch (true) { case true: { [|i = j = 5;|] break; } default: { [|x = y = 5;|] break; } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement", "'x' and 'y' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_a_return_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" int M() { int i, j; [|return|] i = j = 5; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_a_yield_return_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(IEnumerable<>).Namespace) .InDefaultClass(@" IEnumerable<int> M() { int i, j; [|yield return|] i = j = 5; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_expression_of_a_lock_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { object o, p; int k; [|lock|] (o = p = new object()) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'o' and 'p' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_in_the_body_of_a_lock_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; lock (this) { i = 5; j = 8; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_the_body_of_a_lock_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; lock (this) { [|i = j = 5;|] } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_the_expression_of_a_using_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(IDisposable).Namespace) .InDefaultClass(@" void M() { IDisposable i, j; int k; [|using|] (i = j = null) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_variable_is_declared_and_two_variables_are_assigned_in_the_expression_of_a_using_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(IDisposable).Namespace) .InDefaultClass(@" void M() { IDisposable j; int k; [|using|] (IDisposable i = j = null) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_the_expression_of_a_using_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(MemoryStream).Namespace) .InDefaultClass(@" void M() { int k; [|using|] (MemoryStream ms1 = new MemoryStream(), ms2 = new MemoryStream()) { k = 3; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'ms1' and 'ms2' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_in_the_body_of_a_using_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; using (null) { i = 5; j = 8; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_the_body_of_a_using_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { int i, j; using (null) { [|i = j = 5;|] } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_a_throw_statement_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Exception).Namespace) .InDefaultClass(@" int M() { Exception i, j; [|throw|] i = j = new Exception(); } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_separate_statements_in_a_lambda_body_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Action).Namespace) .InDefaultClass(@" void M() { int i, j; Action action = () => { i = 5; j = 8; }; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_a_lambda_body_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Action).Namespace) .InDefaultClass(@" void M() { int i, j; Action action = () => { [|i = j = 5;|] }; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_two_variables_are_assigned_in_a_single_statement_in_a_lambda_expression_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Action).Namespace) .InDefaultClass(@" void M() { int i, j; Action action = () => [|i = j = 5|]; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "'i' and 'j' are assigned in a single statement"); } [Fact] internal void When_a_property_is_declared_and_assigned_in_an_anonymous_type_creation_expression_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { var instance = new { Abc = string.Empty }; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_members_are_assigned_in_an_object_creation_expression_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { var instance = new X { F = 1, P = 2 }; } class X { public int F; public int P { get; set; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_members_are_assigned_in_an_anonymous_object_creation_expression_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { var instance = new { F = 1, P = 2 }; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_members_are_assigned_in_a_type_parameter_object_creation_expression_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M<T>() where T : I, new() { var instance = new T { P1 = 1, P2 = 2 }; } interface I { int P1 { get; set; } int P2 { get; set; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_members_are_assigned_in_a_dynamic_object_creation_expression_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M(dynamic d) { var instance = new X(d) { P = 1 }; } class X { public X(dynamic d) => throw null; public int P { get; set; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_a_declaration_expression_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { bool result = N(out var a, out var b); int x, y; bool z; z = N(out x, out y); } bool N(out int i, out int j) => throw null; ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_a_tuple_declaration_expression_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M() { (int a, int b) = GetTuple(); (var c, var d) = GetTuple(); (int, int) t = GetTuple(); var (x, y) = GetTuple(); var (_, _) = GetTuple(); } (int, int) GetTuple() => throw null; ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_an_is_pattern_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M(object a, object b) { if (a is string s1 && b is string s2) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_two_variables_are_declared_and_assigned_in_a_pattern_matching_statement_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M(object o) { switch (o) { case string s when s.Length > 0: { throw null; } case int i when i > 0: { throw null; } case null: { return; } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } protected override DiagnosticAnalyzer CreateAnalyzer() { return new AssignEachVariableInASeparateStatementAnalyzer(); } } }
using Kazyx.RemoteApi; using Kazyx.RemoteApi.Camera; using Kazyx.WPPMM.CameraManager; using Kazyx.WPPMM.Controls; using Kazyx.WPPMM.DataModel; using Kazyx.WPPMM.Resources; using Kazyx.WPPMM.Utils; using Microsoft.Devices; using Microsoft.Phone.Controls; using Microsoft.Phone.Net.NetworkInformation; using Microsoft.Phone.Reactive; using Microsoft.Phone.Tasks; using NtNfcLib; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Threading; using Windows.Networking.Proximity; namespace Kazyx.WPPMM.Pages { public partial class MainPage : PhoneApplicationPage { private const int PIVOTINDEX_MAIN = 0; private const int PIVOTINDEX_LIVEVIEW = 1; private readonly CameraManager.CameraManager cameraManager = CameraManager.CameraManager.GetInstance(); private bool OnZooming; private const double APPBAR_OPACITY_ENTRANCE = 0.7; private const double APPBAR_OPACITY_LIVEVIEW = 0.0; private double AppBarOpacity = 0.7; private ShootingViewData svd; private readonly PostViewData pvd = new PostViewData(); private AppBarManager abm = new AppBarManager(); private ControlPanelManager cpm; private ProximityDevice ProximitiyDevice; private long SubscriptionIdNdef; private const string AP_NAME_PREFIX = "DIRECT-"; private const bool FilterBySsid = true; private static readonly BitmapImage GeoInfoStatusImage_OK = new BitmapImage(new Uri("/Assets/Screen/GeoInfoStatus_OK.png", UriKind.Relative)); private static readonly BitmapImage GeoInfoStatusImage_NG = new BitmapImage(new Uri("/Assets/Screen/GeoInfoStatus_NG.png", UriKind.Relative)); private static readonly BitmapImage GeoInfoStatusImage_Updating = new BitmapImage(new Uri("/Assets/Screen/GeoInfoStatus_Updating.png", UriKind.Relative)); private const string ViewerPageUri = "/Pages/RemoteViewerPage.xaml"; public MainPage() { InitializeComponent(); MyPivot.SelectionChanged += MyPivot_SelectionChanged; this.InitAppSettingPanel(); abm.SetEvent(Menu.About, (sender, e) => { NavigationService.Navigate(new Uri("/Pages/AboutPage.xaml", UriKind.Relative)); }); #if DEBUG abm.SetEvent(Menu.Log, (sender, e) => { NavigationService.Navigate(new Uri("/Pages/LogViewerPage.xaml", UriKind.Relative)); }); abm.SetEvent(Menu.Contents, (sender, e) => { NavigationService.Navigate(new Uri(ViewerPageUri, UriKind.Relative)); }); #endif abm.SetEvent(IconMenu.WiFi, (sender, e) => { var task = new ConnectionSettingsTask { ConnectionSettingsType = ConnectionSettingsType.WiFi }; task.Show(); }); abm.SetEvent(IconMenu.ControlPanel, (sender, e) => { if (abm != null) { ApplicationBar = abm.Disable(IconMenu.TouchAfCancel).CreateNew(AppBarOpacity); } ApplicationBar.IsVisible = false; if (cameraManager != null) { cameraManager.CancelTouchAF(); cameraManager.CancelHalfPressShutter(); } if (Sliders.Visibility == System.Windows.Visibility.Visible) { CloseSliderPanel(); } cpm.Show(); }); abm.SetEvent(IconMenu.ApplicationSetting, (sender, e) => { this.OpenAppSettingPanel(); }); abm.SetEvent(IconMenu.Ok, (sender, e) => { this.CloseAppSettingPanel(); }); abm.SetEvent(IconMenu.TouchAfCancel, (sender, e) => { if (cameraManager != null) { cameraManager.CancelTouchAF(); } }); abm.SetEvent(IconMenu.CameraRoll, (sender, e) => { if (cameraManager != null) { cameraManager.CancelTouchAF(); cameraManager.CancelHalfPressShutter(); } NavigationService.Navigate(new Uri(ViewerPageUri, UriKind.Relative)); }); abm.SetEvent(IconMenu.Hidden, (sender, e) => { NavigationService.Navigate(new Uri("/Pages/HiddenPage.xaml", UriKind.Relative)); }); cpm = new ControlPanelManager(ControlPanel); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); DebugUtil.Log(e.Uri.OriginalString); progress.IsVisible = false; InitializeApplication(); cameraManager.OnDisconnected += cameraManager_OnDisconnected; cameraManager.WifiInfoUpdated += WifiInfoUpdated; cameraManager.Downloader.QueueStatusUpdated += OnFetchingImages; cameraManager.OnRemoteClientError += cameraManager_OnRemoteClientError; cameraManager.PictureFetchFailed += cameraManager_PictureFetchFailed; cameraManager.PictureFetchStatusUpdated += cameraManager_PictureFetchStatusUpdated; cameraManager.PictureFetchSucceed += cameraManager_PictureFetchSucceed; cameraManager.OnTakePictureSucceed += cameraManager_OnTakePictureSucceed; cameraManager.MethodTypesUpdateNotifer += SupportedApiUpdated; switch (MyPivot.SelectedIndex) { case PIVOTINDEX_MAIN: LiveviewPageUnloaded(); EntrancePageLoaded(); break; case PIVOTINDEX_LIVEVIEW: EntrancePageUnloaded(); LiveviewPageLoaded(); break; } if (!FilterBySsid || GetSSIDName().StartsWith(AP_NAME_PREFIX)) { if (MyPivot.SelectedIndex != PIVOTINDEX_LIVEVIEW) { StartConnectionSequence(true); } } ActivateGeoTagSetting(true); DisplayGridColorSetting(ApplicationSettings.GetInstance().GridType != FramingGridTypes.Off); DisplayFibonacciOriginSetting(ApplicationSettings.GetInstance().GridType == FramingGridTypes.Fibonacci); } void cameraManager_OnTakePictureSucceed() { if (!ApplicationSettings.GetInstance().IsPostviewTransferEnabled || cameraManager.IntervalManager.IsRunning) { ShowToast(AppResources.Message_ImageCapture_Succeed); } } private void cameraManager_PictureFetchSucceed(Windows.Devices.Geolocation.Geoposition pos) { if (ApplicationSettings.GetInstance().GeotagEnabled && pos != null) { ShowToast(AppResources.Message_ImageDL_Succeed_withGeotag); } else if (ApplicationSettings.GetInstance().GeotagEnabled) { MessageBox.Show(AppResources.ErrorMessage_FailedToGetGeoposition); } else { ShowToast(AppResources.Message_ImageDL_Succeed); } } void cameraManager_PictureFetchStatusUpdated(int amount) { if (amount == 0) { AppStatus.GetInstance().IsDownloadingImages = false; } else { AppStatus.GetInstance().IsDownloadingImages = true; } } void cameraManager_PictureFetchFailed(ImageDLError err) { var error = ""; var isOriginal = false; if (cameraManager.Status.PostviewSizeInfo != null && cameraManager.Status.PostviewSizeInfo.Current == "Original") { isOriginal = true; } switch (err) { case ImageDLError.Gone: error = AppResources.ErrorMessage_ImageDL_Gone; break; case ImageDLError.Network: error = AppResources.ErrorMessage_ImageDL_Network; break; case ImageDLError.Saving: case ImageDLError.DeviceInternal: if (isOriginal) { error = AppResources.ErrorMessage_ImageDL_SavingOriginal; } else { error = AppResources.ErrorMessage_ImageDL_Saving; } break; case ImageDLError.GeotagAlreadyExists: error = AppResources.ErrorMessage_ImageDL_DuplicatedGeotag; break; case ImageDLError.GeotagAddition: error = AppResources.ErrorMessage_ImageDL_Geotagging; break; case ImageDLError.Unknown: case ImageDLError.Argument: default: if (isOriginal) { error = AppResources.ErrorMessage_ImageDL_OtherOriginal; } else { error = AppResources.ErrorMessage_ImageDL_Other; } break; } MessageBox.Show(error, AppResources.MessageCaption_error, MessageBoxButton.OK); DebugUtil.Log(error); } void cameraManager_OnRemoteClientError(StatusCode code) { var err = ""; if (cameraManager.IntervalManager.IsRunning) { err = AppResources.ErrorMessage_Interval + System.Environment.NewLine + System.Environment.NewLine + "Error code: " + code; } else { switch (code) { case StatusCode.Any: err = AppResources.ErrorMessage_fatal; break; case StatusCode.Timeout: err = AppResources.ErrorMessage_timeout; break; case StatusCode.ShootingFailure: err = AppResources.ErrorMessage_shootingFailure; break; case StatusCode.CameraNotReady: err = AppResources.ErrorMessage_cameraNotReady; break; case StatusCode.Forbidden: err = AppResources.BuiltInSRNotSupported; break; default: err = AppResources.ErrorMessage_fatal; break; } } err = err + System.Environment.NewLine + System.Environment.NewLine + "Error code: " + code; MessageBox.Show(err, AppResources.MessageCaption_error, MessageBoxButton.OK); } internal void cameraManager_OnDisconnected() { DebugUtil.Log("## Disconnected"); MessageBox.Show(AppResources.ErrorMessage_Dsconnected, AppResources.MessageCaption_error, MessageBoxButton.OK); MyPivot.IsLocked = false; if (cpm != null && cpm.IsShowing()) { cpm.Hide(); } this.GoToMainPage(); this.InitializeApplication(); } internal void InitializeApplication() { cameraManager.Refresh(); UpdateNetworkStatus(); LiveViewInit(); InitializeProximityDevice(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { cameraManager.OnDisconnected -= cameraManager_OnDisconnected; cameraManager.WifiInfoUpdated -= WifiInfoUpdated; cameraManager.Downloader.QueueStatusUpdated -= OnFetchingImages; cameraManager.OnRemoteClientError -= cameraManager_OnRemoteClientError; cameraManager.PictureFetchFailed -= cameraManager_PictureFetchFailed; cameraManager.PictureFetchStatusUpdated -= cameraManager_PictureFetchStatusUpdated; cameraManager.PictureFetchSucceed -= cameraManager_PictureFetchSucceed; cameraManager.OnTakePictureSucceed -= cameraManager_OnTakePictureSucceed; cameraManager.MethodTypesUpdateNotifer -= SupportedApiUpdated; switch (MyPivot.SelectedIndex) { case PIVOTINDEX_LIVEVIEW: LiveviewPageUnloaded(); break; case PIVOTINDEX_MAIN: EntrancePageUnloaded(); break; } cameraManager.RequestCloseLiveView(); } private void StartConnectionSequence(bool connect) { progress.Text = AppResources.ProgressMessageDetectingDevice; progress.IsVisible = true; CameraManager.CameraManager.GetInstance().RequestSearchDevices(() => { DebugUtil.Log("DeviceFound -> GoToShootingPage if required."); progress.IsVisible = false; if (connect) GoToShootingPage(); }, () => { DebugUtil.Log("Discovery timeout."); progress.IsVisible = false; }); } private void HandleError(int code) { DebugUtil.Log("Error: " + code); } private void UpdateNetworkStatus() { var ssid = GetSSIDName(); DebugUtil.Log("SSID: " + ssid); if (ssid != null && ssid.StartsWith(AP_NAME_PREFIX)) { NetworkStatus.Text = AppResources.Guide_CantFindDevice; } else { NetworkStatus.Text = AppResources.Guide_WiFiNotEnabled; } if (cameraManager.CurrentDeviceInfo != null) { var modelName = cameraManager.CurrentDeviceInfo.FriendlyName; if (modelName != null) { NetworkStatus.Text = AppResources.ConnectedDevice.Replace("_ssid_", modelName); GuideMessage.Visibility = System.Windows.Visibility.Visible; } } else { NetworkStatus.Text = AppResources.Guide_CantFindDevice; GuideMessage.Visibility = System.Windows.Visibility.Collapsed; } ProgressBar.Visibility = System.Windows.Visibility.Collapsed; } private void GoToShootingPage() { if (MyPivot.SelectedIndex == 1) { LiveviewPageLoaded(); } else { MyPivot.SelectedIndex = 1; } } private void GoToMainPage() { MyPivot.IsLocked = false; MyPivot.SelectedIndex = 0; } internal void WifiInfoUpdated(CameraStatus cameraStatus) { UpdateNetworkStatus(); } private string GetSSIDName() { foreach (var network in new NetworkInterfaceList()) { if ((network.InterfaceType == NetworkInterfaceType.Wireless80211) && (network.InterfaceState == ConnectState.Connected)) { return network.InterfaceName; } } return "<Not connected>"; } private void LiveViewInit() { cameraManager.RequestCloseLiveView(); OnZooming = false; } private async void CameraButtons_ShutterKeyPressed(object sender, EventArgs e) { if (cameraManager == null || cpm == null || cpm.IsShowing() || IsAppSettingPanelShowing()) { return; } if (StartContShootingAvailable()) { ContShootOperating = true; await StartContShooting(); return; } RecStartStop(); } private async void CameraButtons_ShutterKeyReleased(object sender, EventArgs e) { if (cameraManager == null || cpm == null || cpm.IsShowing() || IsAppSettingPanelShowing()) { return; } if (StopContShootingAvailable()) { ContShootOperating = false; await StopContShooting(); } cameraManager.CancelHalfPressShutter(); } void CameraButtons_ShutterKeyHalfPressed(object sender, EventArgs e) { if (cameraManager == null || cpm == null || cpm.IsShowing() || IsAppSettingPanelShowing()) { return; } cameraManager.RequestHalfPressShutter(); } private void takeImageButton_Click(object sender, RoutedEventArgs e) { RecStartStop(); } private bool StartContShootingAvailable() { if (!cameraManager.IntervalManager.IsRunning && cameraManager.Status != null && cameraManager.Status.Status == EventParam.Idle && cameraManager.Status.ShootMode.Current == ShootModeParam.Still && cameraManager.Status.ContShootingMode != null && ( cameraManager.Status.ContShootingMode.Current == ContinuousShootMode.Cont || cameraManager.Status.ContShootingMode.Current == ContinuousShootMode.SpeedPriority) ) { return true; } return false; } private bool StopContShootingAvailable() { if (!cameraManager.IntervalManager.IsRunning && cameraManager.Status != null && cameraManager.Status.Status == EventParam.StCapturing && cameraManager.Status.ShootMode.Current == ShootModeParam.Still && cameraManager.Status.ContShootingMode != null && ( cameraManager.Status.ContShootingMode.Current == ContinuousShootMode.Cont || cameraManager.Status.ContShootingMode.Current == ContinuousShootMode.SpeedPriority) ) { return true; } return false; } private async void ShootButton_ManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e) { if (StartContShootingAvailable()) { ContShootOperating = true; await StartContShooting(); } } bool ContShootingDelay = false; // touching shooting button or pressing shutter key bool ContShootOperating = false; private async Task StartContShooting() { ContShootingDelay = true; await cameraManager.CameraApi.StartContShootingAsync(); await Task.Run(async delegate { await Task.Delay(1000); Dispatcher.BeginInvoke(async () => { if (ContShootOperating) { ContShootOperating = false; } else { await cameraManager.CameraApi.StopContShootingAsync(); } ContShootingDelay = false; }); }); } private async Task StopContShooting() { if (!ContShootingDelay) { ContShootOperating = false; await cameraManager.CameraApi.StopContShootingAsync(); } } private async void RecStartStop() { if (cameraManager.IntervalManager.IsRunning) { cameraManager.StopLocalIntervalRec(); if (cpm != null) { cpm.OnControlPanelPropertyChanged("CpIsAvailableSelfTimer"); cpm.OnControlPanelPropertyChanged("CpIsAvailableShootMode"); cpm.OnControlPanelPropertyChanged("CpIsAvailablePostviewSize"); cpm.OnControlPanelPropertyChanged("CpIsAvailableStillImageFunctions"); } return; } ContShootOperating = false; var status = cameraManager.Status; if (status == null || status.Status == null || status.ShootMode == null) { return; } switch (status.Status) { case EventParam.Idle: switch (status.ShootMode.Current) { case ShootModeParam.Still: if (ApplicationSettings.GetInstance().IsIntervalShootingEnabled) { cameraManager.StartLocalIntervalRec(); if (cpm != null) { cpm.OnControlPanelPropertyChanged("CpIsAvailableSelfTimer"); cpm.OnControlPanelPropertyChanged("CpIsAvailableShootMode"); cpm.OnControlPanelPropertyChanged("CpIsAvailablePostviewSize"); cpm.OnControlPanelPropertyChanged("CpIsAvailableStillImageFunctions"); } } else { if (!ContShootingDelay) { cameraManager.RequestActTakePicture(); } } break; case ShootModeParam.Movie: cameraManager.StartMovieRec(); break; case ShootModeParam.Audio: cameraManager.StartAudioRec(); break; case ShootModeParam.Interval: cameraManager.StartIntervalStillRec(); break; } break; case EventParam.MvRecording: cameraManager.StopMovieRec(); break; case EventParam.AuRecording: cameraManager.StopAudioRec(); break; case EventParam.ItvRecording: cameraManager.StopIntervalStillRec(); break; case EventParam.StCapturing: if (status.ContShootingMode != null && (status.ContShootingMode.Current == ContinuousShootMode.Cont || status.ContShootingMode.Current == ContinuousShootMode.SpeedPriority)) { await StopContShooting(); } break; } } private int PreviousSelectedPivotIndex = -1; private void MyPivot_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { var pivot = sender as Pivot; if (pivot == null) { return; } if (PreviousSelectedPivotIndex == pivot.SelectedIndex) { return; } PreviousSelectedPivotIndex = pivot.SelectedIndex; switch (PreviousSelectedPivotIndex) { case 0: LiveviewPageUnloaded(); EntrancePageLoaded(); break; case 1: EntrancePageUnloaded(); LiveviewPageLoaded(); break; default: break; } } private void EntrancePageUnloaded() { EntrancePivot.Opacity = 0; ClearNFCInfo(); } private async void LiveviewPageLoaded() { SetPivotIsLocked(true); AppStatus.GetInstance().IsInShootingDisplay = true; ShootingPivot.Opacity = 1; SetLayoutByOrientation(this.Orientation); cameraManager.ShowToast += ShowToast; cameraManager.OnFocusFrameRetrived += cameraManager_OnFocusFrameRetrived; ToastApparance.Completed += ToastApparance_Completed; FraimingGrids.ManipulationCompleted += FraimingGrids_ManipulationCompleted; CameraButtons.ShutterKeyPressed += CameraButtons_ShutterKeyPressed; CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed; CameraButtons.ShutterKeyReleased += CameraButtons_ShutterKeyReleased; cameraManager.OnAfStatusChanged += cameraManager_OnAfStatusChanged; cameraManager.OnExposureModeChanged += cameraManager_OnExposureModeChanged; if (svd != null) { svd.SlidersVisibilityChanged += SlidersVisibilityChanged; } await Task.Delay(500); if (cameraManager.IsClientReady()) { progress.Text = AppResources.ProgressMessageConnecting; progress.IsVisible = true; cameraManager.RunEventObserver(); await cameraManager.OperateInitialProcess(); Dispatcher.BeginInvoke(() => { progress.IsVisible = false; }); } else if (FilterBySsid && !GetSSIDName().StartsWith(AP_NAME_PREFIX)) { Dispatcher.BeginInvoke(() => { GoToMainPage(); }); return; } else { DebugUtil.Log("Await for async device discovery"); AppStatus.GetInstance().IsSearchingDevice = true; Dispatcher.BeginInvoke(() => { progress.Text = AppResources.ProgressMessageConnecting; progress.IsVisible = true; }); var found = await PrepareConnectionAsync(); Dispatcher.BeginInvoke(() => { AppStatus.GetInstance().IsSearchingDevice = false; }); DebugUtil.Log("Async device discovery result: " + found); if (found) { cameraManager.RunEventObserver(); await cameraManager.OperateInitialProcess(); Dispatcher.BeginInvoke(() => { progress.IsVisible = false; }); } else { Dispatcher.BeginInvoke(() => { progress.IsVisible = false; GoToMainPage(); }); return; } } AppBarOpacity = APPBAR_OPACITY_LIVEVIEW; abm.Clear(); if (cpm != null && cpm.ItemCount > 0) { abm.Enable(IconMenu.ControlPanel); } abm.Enable(IconMenu.ApplicationSetting).Enable(IconMenu.CameraRoll); Dispatcher.BeginInvoke(() => { if (cpm != null) cpm.Hide(); ApplicationBar = abm.CreateNew(AppBarOpacity); }); InitializeHitogram(); cameraManager.OnHistogramUpdated += cameraManager_OnHistogramUpdated; GeopositionManager.GetInstance().GeopositionUpdated += GeopositionStatusUpdated; GeopositionManager.GetInstance().Enable = ApplicationSettings.GetInstance().GeotagEnabled; if (ApplicationSettings.GetInstance().GeotagEnabled) { await GeopositionManager.GetInstance().AcquireGeoPosition(); } } private void SupportedApiUpdated() { var available = cameraManager.Status.IsSupported("setLiveviewFrameInfo"); DebugUtil.Log("Focus frame setting visibility: " + available); if (FocusFrameSetting == null) { return; } if (available) { FocusFrameSetting.SettingVisibility = System.Windows.Visibility.Visible; } else { FocusFrameSetting.SettingVisibility = System.Windows.Visibility.Collapsed; } } private void cameraManager_OnFocusFrameRetrived(ImageStream.FocusFramePacket p) { if (ApplicationSettings.GetInstance().RequestFocusFrameInfo) { FocusFrames.SetFocusFrames(p.FocusFrames); } } void cameraManager_OnExposureModeChanged(string obj) { if (Sliders.Visibility == System.Windows.Visibility.Visible) { this.CloseSliderPanel(); } } private void OnFetchingImages(int count) { Dispatcher.BeginInvoke(() => { if (count != 0) { progress.Text = AppResources.ProgressMessageFetching; progress.IsVisible = true; } else { progress.IsVisible = false; } }); } internal void GeopositionStatusUpdated(GeopositionEventArgs args) { DebugUtil.Log("Geoposition status updated: " + args.Status); Dispatcher.BeginInvoke(() => { switch (args.Status) { case GeopositiomManagerStatus.Acquiring: GeopositionStatusImage.Source = GeoInfoStatusImage_Updating; break; case GeopositiomManagerStatus.OK: GeopositionStatusImage.Source = GeoInfoStatusImage_OK; break; case GeopositiomManagerStatus.Failed: GeopositionStatusImage.Source = GeoInfoStatusImage_NG; break; case GeopositiomManagerStatus.Unauthorized: GeopositionStatusImage.Source = GeoInfoStatusImage_NG; if (geoSetting != null) { geoSetting.CurrentSetting = false; } ActivateGeoTagSetting(false); // MessageBox.Show(AppResources.ErrorMessage_LocationAccessUnauthorized); break; } }); } private void SlidersVisibilityChanged(System.Windows.Visibility visibility) { DebugUtil.Log("Slider visibility changed: " + visibility); if (visibility == System.Windows.Visibility.Collapsed) { CloseSliderPanel(); } } private void InitializeHitogram() { Histogram.Init(WPPMM.Controls.Histogram.ColorType.White, 1500); } private void cameraManager_OnHistogramUpdated(int[] r, int[] g, int[] b) { Histogram.SetHistogramValue(r, g, b); } void cameraManager_OnAfStatusChanged(CameraStatus status) { if (status.FocusStatus == null) { return; } if (status.AfType == CameraStatus.AutoFocusType.Touch && ((status.TouchFocusStatus == null && status.FocusStatus != FocusState.Released) || // QX10/100 may not return TouchFocusStatus record (status.TouchFocusStatus != null && status.TouchFocusStatus.Focused))) // SmartRemote gives TouchFocusStatus { // focus locked. if (!abm.IsEnabled(IconMenu.TouchAfCancel)) { if (cpm != null && !cpm.IsShowing()) { ApplicationBar = abm.Enable(IconMenu.TouchAfCancel).CreateNew(AppBarOpacity); } else { abm.Enable(IconMenu.TouchAfCancel); } } } else { // touch AF cancelled. if (abm.IsEnabled(IconMenu.TouchAfCancel)) { if (cpm != null && !cpm.IsShowing()) { ApplicationBar = abm.Disable(IconMenu.TouchAfCancel).CreateNew(AppBarOpacity); } else { abm.Disable(IconMenu.TouchAfCancel); } } } } void FraimingGrids_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e) { if (cpm.IsShowing()) { cpm.Hide(); if (ApplicationBar != null) { Dispatcher.BeginInvoke(() => { ApplicationBar.IsVisible = true; }); } return; } if (Sliders.Visibility == System.Windows.Visibility.Visible) { CloseSliderPanel(); return; } if (!cameraManager.IsTouchAfAvailable()) { return; } var grids = sender as FramingGrids; var touchX = e.ManipulationOrigin.X; var touchY = e.ManipulationOrigin.Y; var posX = touchX * 100.0 / grids.ActualWidth; var posY = touchY * 100.0 / grids.ActualHeight; Dispatcher.BeginInvoke(() => { TouchAFPointer.Margin = new Thickness(touchX - TouchAFPointer.Width / 2, touchY - TouchAFPointer.Height / 2, 0, 0); }); // DebugUtil.Log("tx: " + touchX + " ty: " + touchY); DebugUtil.Log("touch position X: " + posX + " Y: " + posY); cameraManager.RequestTouchAF(posX, posY); } private Task<bool> PrepareConnectionAsync() { var tcs = new TaskCompletionSource<bool>(); bool done = false; cameraManager.RequestSearchDevices(() => { if (!done) { done = true; tcs.SetResult(true); } }, () => { if (!done) { done = true; tcs.SetResult(false); } }); return tcs.Task; } private void LiveviewPageUnloaded() { SetPivotIsLocked(false); AppStatus.GetInstance().IsInShootingDisplay = false; ShootingPivot.Opacity = 0; cameraManager.ShowToast -= ShowToast; cameraManager.OnFocusFrameRetrived -= cameraManager_OnFocusFrameRetrived; ToastApparance.Completed -= ToastApparance_Completed; CameraButtons.ShutterKeyPressed -= CameraButtons_ShutterKeyPressed; CameraButtons.ShutterKeyHalfPressed -= CameraButtons_ShutterKeyHalfPressed; CameraButtons.ShutterKeyReleased -= CameraButtons_ShutterKeyReleased; cameraManager.OnAfStatusChanged -= cameraManager_OnAfStatusChanged; cameraManager.OnExposureModeChanged -= cameraManager_OnExposureModeChanged; FraimingGrids.ManipulationCompleted -= FraimingGrids_ManipulationCompleted; cameraManager.IntervalManager.Stop(); if (svd != null) { svd.SlidersVisibilityChanged -= SlidersVisibilityChanged; } if (cpm != null) { cpm.Hide(); } if (IsAppSettingPanelShowing()) { this.CloseAppSettingPanel(); } cameraManager.OnHistogramUpdated -= cameraManager_OnHistogramUpdated; GeopositionManager.GetInstance().GeopositionUpdated -= GeopositionStatusUpdated; } private void EntrancePageLoaded() { EntrancePivot.Opacity = 1; AppBarOpacity = APPBAR_OPACITY_ENTRANCE; #if DEBUG ApplicationBar = abm.Clear().Enable(Menu.Log).Enable(Menu.Contents).Enable(IconMenu.WiFi).Enable(IconMenu.Hidden).CreateNew(AppBarOpacity); #else ApplicationBar = abm.Clear().Enable(IconMenu.WiFi).Enable(IconMenu.Hidden).CreateNew(AppBarOpacity); #endif } private void OnZoomInClick(object sender, RoutedEventArgs e) { DebugUtil.Log("Stop Zoom In (if started)"); if (OnZooming) { cameraManager.RequestActZoom(ZoomParam.DirectionIn, ZoomParam.ActionStop); } } private void OnZoomOutClick(object sender, RoutedEventArgs e) { DebugUtil.Log("Stop zoom out (if started)"); if (OnZooming) { cameraManager.RequestActZoom(ZoomParam.DirectionOut, ZoomParam.ActionStop); } } private void OnZoomInHold(object sender, System.Windows.Input.GestureEventArgs e) { DebugUtil.Log("Zoom In: Start"); cameraManager.RequestActZoom(ZoomParam.DirectionIn, ZoomParam.ActionStart); OnZooming = true; } private void OnZoomOutHold(object sender, System.Windows.Input.GestureEventArgs e) { DebugUtil.Log("Zoom Out: Start"); cameraManager.RequestActZoom(ZoomParam.DirectionOut, ZoomParam.ActionStart); OnZooming = true; } private void OnZoomInTap(object sender, System.Windows.Input.GestureEventArgs e) { DebugUtil.Log("Zoom In: OneShot"); cameraManager.RequestActZoom(ZoomParam.DirectionIn, ZoomParam.Action1Shot); } private void OnZoomOutTap(object sender, System.Windows.Input.GestureEventArgs e) { DebugUtil.Log("Zoom In: OneShot"); cameraManager.RequestActZoom(ZoomParam.DirectionOut, ZoomParam.Action1Shot); } private void ScreenImage_Loaded(object sender, RoutedEventArgs e) { DebugUtil.Log("ScreenImage_Loaded"); ScreenImage.DataContext = cameraManager.LiveviewImage; } private void ScreenImage_Unloaded(object sender, RoutedEventArgs e) { DebugUtil.Log("ScreenImage_UnLoaded"); ScreenImage.DataContext = null; } protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { DebugUtil.Log("onbackkey"); if (MyPivot.SelectedIndex == PIVOTINDEX_LIVEVIEW) { e.Cancel = true; if (IsAppSettingPanelShowing()) { this.CloseAppSettingPanel(); return; } if (cpm != null && cpm.IsShowing()) { CloseControlPanel(); return; } if (Sliders.Visibility == System.Windows.Visibility.Visible) { CloseSliderPanel(); return; } GoToMainPage(); } else { e.Cancel = false; } } private void CloseControlPanel() { if (cpm != null) { cpm.Hide(); } if (ApplicationBar != null) { ApplicationBar.IsVisible = true; } } private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { svd = new ShootingViewData(AppStatus.GetInstance(), cameraManager.Status); ShootingPivot.DataContext = svd; IntervalStatusPanel.DataContext = cameraManager.IntervalManager; ScreenImageWrapper.DataContext = cameraManager.Status; AudioScreenImage.DataContext = cameraManager.Status; ShootButtonWrapper.DataContext = ApplicationSettings.GetInstance(); ShootButton.DataContext = svd; TouchAFPointer.DataContext = svd; Histogram.DataContext = ApplicationSettings.GetInstance(); GeopositionStatusImage.DataContext = ApplicationSettings.GetInstance(); this.FraimingGrids.DataContext = ApplicationSettings.GetInstance(); cpm.ReplacePanel(ControlPanel); } private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e) { /* ShootingPivot.DataContext = null; IntervalStatusPanel.DataContext = null; ScreenImageWrapper.DataContext = null; AudioScreenImage.DataContext = null; ShootButtonWrapper.DataContext = null; ShootButton.DataContext = null; TouchAFPointer.DataContext = null; Histogram.DataContext = null; GeopositionStatusImage.DataContext = null; svd = null; * */ } private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e) { DebugUtil.Log("OrientationChagned: " + e.Orientation); if (cameraManager != null) { cameraManager.CancelTouchAF(); cameraManager.CancelHalfPressShutter(); } SetLayoutByOrientation(e.Orientation); } private void SetLayoutByOrientation(PageOrientation orientation) { try { switch (orientation) { case PageOrientation.LandscapeLeft: AppTitle.Margin = new Thickness(60, 0, 0, 0); UpperLeftElements.Margin = new Thickness(42, 46, 0, 0); StatusDisplayelements.Margin = new Thickness(40, 6, 60, 0); AppSettings.Margin = new Thickness(20, 64, 40, 64); AppSettingPanel.Margin = new Thickness(0, -36, 0, 24); BottomElements.Margin = new Thickness(0); ZoomElements.Margin = new Thickness(50, 0, 0, 0); ShootButtonWrapper.Margin = new Thickness(0, 0, 80, 0); OpenSlider.Margin = new Thickness(60, 0, 0, 0); Sliders.Margin = new Thickness(70, 0, 70, 0); EntrancePivot.Margin = new Thickness(70, 0, 70, 0); NFCMessage.Margin = new Thickness(30, 20, 30, 30); Grid.SetRow(Histogram, 1); Grid.SetColumn(Histogram, 0); Grid.SetRow(IntervalStatusPanel, 2); Grid.SetColumn(IntervalStatusPanel, 0); SupportItems.Margin = new Thickness(70, 0, 70, 0); break; case PageOrientation.LandscapeRight: AppTitle.Margin = new Thickness(60, 0, 0, 0); UpperLeftElements.Margin = new Thickness(42, 46, 0, 0); StatusDisplayelements.Margin = new Thickness(40, 6, 60, 0); AppSettings.Margin = new Thickness(36, 64, 16, 64); AppSettingPanel.Margin = new Thickness(0, -36, 0, 24); BottomElements.Margin = new Thickness(0); ZoomElements.Margin = new Thickness(90, 0, 0, 0); ShootButtonWrapper.Margin = new Thickness(0, 0, 80, 0); OpenSlider.Margin = new Thickness(90, 0, 0, 0); Sliders.Margin = new Thickness(70, 0, 70, 0); EntrancePivot.Margin = new Thickness(70, 0, 70, 0); NFCMessage.Margin = new Thickness(30, 20, 30, 30); Grid.SetRow(Histogram, 1); Grid.SetColumn(Histogram, 0); Grid.SetRow(IntervalStatusPanel, 2); Grid.SetColumn(IntervalStatusPanel, 0); SupportItems.Margin = new Thickness(70, 0, 70, 0); break; case PageOrientation.PortraitUp: AppTitle.Margin = new Thickness(0); UpperLeftElements.Margin = new Thickness(10, 46, 0, 0); StatusDisplayelements.Margin = new Thickness(10, 6, 0, 0); AppSettings.Margin = new Thickness(-12, 64, 0, 74); AppSettingPanel.Margin = new Thickness(0, -36, 0, 90); BottomElements.Margin = new Thickness(0, 0, 0, 70); ZoomElements.Margin = new Thickness(20, 0, 0, 0); ShootButtonWrapper.Margin = new Thickness(0, 0, 30, 0); OpenSlider.Margin = new Thickness(5, 0, 0, 0); Sliders.Margin = new Thickness(5, 0, 0, 0); EntrancePivot.Margin = new Thickness(0); NFCMessage.Margin = new Thickness(30, 50, 30, 30); Grid.SetRow(Histogram, 1); Grid.SetColumn(Histogram, 0); Grid.SetRow(IntervalStatusPanel, 1); Grid.SetColumn(IntervalStatusPanel, 1); SupportItems.Margin = new Thickness(0, 0, 0, 70); break; } } catch (NullReferenceException ex) { DebugUtil.Log("Caught NullReferenceException: " + ex.StackTrace); } } public void ShowToast(string message) { Dispatcher.BeginInvoke(() => { ToastMessage.Text = message; ToastApparance.Begin(); }); } void ToastApparance_Completed(object sender, EventArgs e) { Scheduler.Dispatcher.Schedule(() => { ToastDisApparance.Begin(); }, TimeSpan.FromSeconds(3)); } void SetPivotIsLocked(bool l) { Dispatcher.BeginInvoke(() => { MyPivot.IsLocked = l; }); } private void InitializeProximityDevice() { try { ProximitiyDevice = ProximityDevice.GetDefault(); } catch (System.IO.FileNotFoundException) { ProximitiyDevice = null; DebugUtil.Log("Caught ununderstandable exception. "); return; } catch (System.Runtime.InteropServices.COMException) { ProximitiyDevice = null; DebugUtil.Log("Caught ununderstandable exception. "); return; } if (ProximitiyDevice == null) { DebugUtil.Log("It seems this is not NFC available device"); return; } try { SubscriptionIdNdef = ProximitiyDevice.SubscribeForMessage("NDEF", NFCMessageReceivedHandler); } catch (Exception e) { ProximitiyDevice = null; DebugUtil.Log("Caught ununderstandable exception. " + e.Message + e.StackTrace); return; } NFCMessage.Visibility = System.Windows.Visibility.Visible; } private void NFCMessageReceivedHandler(ProximityDevice sender, ProximityMessage message) { var parser = new NdefParser(message); var ndefRecords = new List<NdefRecord>(); var err = AppResources.ErrorMessage_fatal; var caption = AppResources.MessageCaption_error; try { ndefRecords = parser.Parse(); } catch (NoSonyNdefRecordException) { err = AppResources.ErrorMessage_CantFindSonyRecord; Dispatcher.BeginInvoke(() => { MessageBox.Show(err, caption, MessageBoxButton.OK); }); } catch (NoNdefRecordException) { err = AppResources.ErrorMessage_ParseNFC; Dispatcher.BeginInvoke(() => { MessageBox.Show(err, caption, MessageBoxButton.OK); }); } catch (NdefParseException) { err = AppResources.ErrorMessage_ParseNFC; Dispatcher.BeginInvoke(() => { MessageBox.Show(err, caption, MessageBoxButton.OK); }); } catch (Exception) { err = AppResources.ErrorMessage_fatal; Dispatcher.BeginInvoke(() => { MessageBox.Show(err, caption, MessageBoxButton.OK); }); } if (ndefRecords.Count > 0) { foreach (NdefRecord r in ndefRecords) { if (r.SSID.Length > 0 && r.Password.Length > 0) { Dispatcher.BeginInvoke(() => { Clipboard.SetText(r.Password); var sb = new StringBuilder(); sb.Append(AppResources.Message_NFC_succeed); sb.Append(System.Environment.NewLine); sb.Append(System.Environment.NewLine); sb.Append("SSID: "); sb.Append(r.SSID); sb.Append(System.Environment.NewLine); sb.Append("Password: "); sb.Append(r.Password); sb.Append(System.Environment.NewLine); sb.Append(System.Environment.NewLine); sb.Append(AppResources.NFC_iiwake); MessageBox.Show(sb.ToString(), AppResources.MessageCaption_NFC_Succeed, MessageBoxButton.OK); }); break; } } } } private void ClearNFCInfo() { if (ProximitiyDevice != null) { NFCMessage.Visibility = System.Windows.Visibility.Visible; } } private AppSettingData<bool> geoSetting; private AppSettingData<int> gridColorSetting; private AppSettingData<int> fibonacciOriginSetting; private AppSettingData<bool> FocusFrameSetting; private void InitAppSettingPanel() { var image_settings = new SettingSection(AppResources.SettingSection_Image); AppSettings.Children.Add(image_settings); image_settings.Add(new CheckBoxSetting( new AppSettingData<bool>(AppResources.PostviewTransferSetting, AppResources.Guide_ReceiveCapturedImage, () => { return ApplicationSettings.GetInstance().IsPostviewTransferEnabled; }, enabled => { ApplicationSettings.GetInstance().IsPostviewTransferEnabled = enabled; }))); geoSetting = new AppSettingData<bool>(AppResources.AddGeotag, AppResources.AddGeotag_guide, () => { return ApplicationSettings.GetInstance().GeotagEnabled; }, enabled => { ApplicationSettings.GetInstance().GeotagEnabled = enabled; GeopositionManager.GetInstance().Enable = enabled; }); image_settings.Add(new CheckBoxSetting(geoSetting)); var display_settings = new SettingSection(AppResources.SettingSection_Display); AppSettings.Children.Add(display_settings); display_settings.Add(new CheckBoxSetting( new AppSettingData<bool>(AppResources.DisplayTakeImageButtonSetting, AppResources.Guide_DisplayTakeImageButtonSetting, () => { return ApplicationSettings.GetInstance().IsShootButtonDisplayed; }, enabled => { ApplicationSettings.GetInstance().IsShootButtonDisplayed = enabled; }))); display_settings.Add(new CheckBoxSetting( new AppSettingData<bool>(AppResources.DisplayHistogram, AppResources.Guide_Histogram, () => { return ApplicationSettings.GetInstance().IsHistogramDisplayed; }, enabled => { ApplicationSettings.GetInstance().IsHistogramDisplayed = enabled; }))); FocusFrameSetting = new AppSettingData<bool>(AppResources.FocusFrameDisplay, AppResources.Guide_FocusFrameDisplay, () => { return ApplicationSettings.GetInstance().RequestFocusFrameInfo; }, enabled => { ApplicationSettings.GetInstance().RequestFocusFrameInfo = enabled; cameraManager.FocusFrameSettingChanged(enabled); if (!enabled) { FocusFrames.ClearFrames(); } }); display_settings.Add(new CheckBoxSetting(FocusFrameSetting)); display_settings.Add(new ListPickerSetting( new AppSettingData<int>(AppResources.FramingGrids, AppResources.Guide_FramingGrids, () => { return ApplicationSettings.GetInstance().GridTypeIndex; }, setting => { ApplicationSettings.GetInstance().GridTypeIndex = setting; DisplayGridColorSetting(ApplicationSettings.GetInstance().GridTypeSettings[setting] != FramingGridTypes.Off); DisplayFibonacciOriginSetting(ApplicationSettings.GetInstance().GridTypeSettings[setting] == FramingGridTypes.Fibonacci); }, SettingsValueConverter.FromFramingGrid(ApplicationSettings.GetInstance().GridTypeSettings.ToArray()) ))); gridColorSetting = new AppSettingData<int>(AppResources.FramingGridColor, null, () => { return ApplicationSettings.GetInstance().GridColorIndex; }, setting => { ApplicationSettings.GetInstance().GridColorIndex = setting; }, SettingsValueConverter.FromFramingGridColor(ApplicationSettings.GetInstance().GridColorSettings.ToArray())); display_settings.Add(new ListPickerSetting(gridColorSetting)); fibonacciOriginSetting = new AppSettingData<int>(AppResources.FibonacciSpiralOrigin, null, () => { return ApplicationSettings.GetInstance().FibonacciOriginIndex; }, setting => { ApplicationSettings.GetInstance().FibonacciOriginIndex = setting; }, SettingsValueConverter.FromFibonacciLineOrigin(ApplicationSettings.GetInstance().FibonacciLineOriginSettings.ToArray())); display_settings.Add(new ListPickerSetting(fibonacciOriginSetting)); HideSettingAnimation.Completed += HideSettingAnimation_Completed; } private void ActivateGeoTagSetting(bool activate) { if (geoSetting != null) { geoSetting.Guide = activate ? AppResources.AddGeotag_guide : AppResources.ErrorMessage_LocationAccessUnauthorized; geoSetting.IsActive = activate; } } private void DisplayGridColorSetting(bool displayed) { if (gridColorSetting != null) { gridColorSetting.IsActive = displayed; } } private void DisplayFibonacciOriginSetting(bool displayed) { if (fibonacciOriginSetting != null) { fibonacciOriginSetting.IsActive = displayed; } } private void OpenAppSettingPanel() { if (cameraManager != null) { cameraManager.CancelTouchAF(); cameraManager.CancelHalfPressShutter(); } AppSettingPanel.Visibility = System.Windows.Visibility.Visible; ApplicationBar = abm.Clear().Enable(IconMenu.Ok).CreateNew(AppBarOpacity); ShowSettingAnimation.Begin(); } private void CloseAppSettingPanel() { HideSettingAnimation.Begin(); ApplicationBar = abm.Clear().Enable(IconMenu.ControlPanel).Enable(IconMenu.ApplicationSetting).Enable(IconMenu.CameraRoll).CreateNew(AppBarOpacity); } void HideSettingAnimation_Completed(object sender, EventArgs e) { AppSettingPanel.Visibility = System.Windows.Visibility.Collapsed; } private bool IsAppSettingPanelShowing() { if (AppSettingPanel.Visibility == System.Windows.Visibility.Visible) { return true; } return false; } private void FNumberSlider_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e) { if (cameraManager == null || cameraManager.Status == null || cameraManager.Status.FNumber == null) { return; } var v = (sender as Slider).Value; var value = (int)Math.Round(v); FNumberSlider.Value = value; if (value < cameraManager.Status.FNumber.Candidates.Count) { cameraManager.SetFNumber(cameraManager.Status.FNumber.Candidates[value]); } } private void ShutterSpeedSlider_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e) { if (cameraManager == null || cameraManager.Status == null || cameraManager.Status.ShutterSpeed == null) { return; } var v = (sender as Slider).Value; var value = (int)Math.Round(v); ShutterSpeedSlider.Value = value; if (value < cameraManager.Status.ShutterSpeed.Candidates.Count) { cameraManager.SetShutterSpeed(cameraManager.Status.ShutterSpeed.Candidates[value]); } } private void EvSlider_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e) { if (cameraManager == null || cameraManager.Status == null || cameraManager.Status.EvInfo == null) { return; } var v = (sender as Slider).Value; var value = (int)Math.Round(v); EvSlider.Value = value; if (value >= cameraManager.Status.EvInfo.Candidate.MinIndex && value <= cameraManager.Status.EvInfo.Candidate.MaxIndex) { cameraManager.SetExposureCompensation(value); } } private void IsoSlider_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e) { if (cameraManager == null || cameraManager.Status == null || cameraManager.Status.ISOSpeedRate == null) { return; } var v = (sender as Slider).Value; var value = (int)Math.Round(v); IsoSlider.Value = value; if (value < cameraManager.Status.ISOSpeedRate.Candidates.Count) { cameraManager.SetIsoSpeedRate(cameraManager.Status.ISOSpeedRate.Candidates[value]); } } private async void ProgramShiftBar_OnRelease(object sender, OnReleaseArgs e) { if (cameraManager == null || cameraManager.CameraApi == null) { return; } try { await cameraManager.CameraApi.SetProgramShiftAsync(e.Value); } catch (RemoteApiException ex) { DebugUtil.Log("Failed to set program shift: " + ex.code); } } private void OpenSliderPanel() { if (cpm.IsShowing()) { CloseControlPanel(); } Sliders.Visibility = Visibility.Visible; // make shoot button and zoom bar/buttons invisible. ApplicationSettings.GetInstance().ShootButtonTemporaryCollapsed = true; if (svd != null) { svd.ZoomElementsTemporaryCollapsed = true; } StartOpenSliderAnimation(0, 180); } private void CloseSliderPanel() { Sliders.Visibility = Visibility.Collapsed; ApplicationSettings.GetInstance().ShootButtonTemporaryCollapsed = false; if (svd != null) { svd.ZoomElementsTemporaryCollapsed = false; } StartOpenSliderAnimation(180, 0); } public void StartOpenSliderAnimation(double from, double to) { var duration = new Duration(TimeSpan.FromMilliseconds(200)); var sb = new Storyboard(); sb.Duration = duration; var da = new DoubleAnimation(); da.Duration = duration; sb.Children.Add(da); var rt = new RotateTransform(); Storyboard.SetTarget(da, rt); Storyboard.SetTargetProperty(da, new PropertyPath("Angle")); da.From = from; da.To = to; OpenSlider.RenderTransform = rt; OpenSlider.RenderTransformOrigin = new Point(0.5, 0.5); sb.Begin(); } private void OpenSlider_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e) { if (Sliders.Visibility == Visibility.Collapsed) { OpenSliderPanel(); } else { CloseSliderPanel(); } e.Handled = true; } private void CameraParameters_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e) { if (!e.Handled) { if (Sliders.Visibility == Visibility.Collapsed) { OpenSliderPanel(); } else { CloseSliderPanel(); } } } private void ScreenImage_SizeChanged(object sender, SizeChangedEventArgs e) { var rh = (sender as Image).RenderSize.Height; var rw = (sender as Image).RenderSize.Width; // DebugUtil.Log("render size: " + rw + " x " + rh); this.FraimingGrids.Height = rh; this.FraimingGrids.Width = rw; } private void AboutButton_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("/Pages/AboutPage.xaml", UriKind.Relative)); } private async void LocanaButton_Click(object sender, RoutedEventArgs e) { try { var uri = new Uri("ms-windows-store:navigate?appid=20a7e645-2aff-4962-80b7-32a50e801a98"); await Windows.System.Launcher.LaunchUriAsync(uri); } catch { DebugUtil.Log("Failed to open locana store page"); } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <[email protected]> This file is part of the fyiReporting RDL project. 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. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Collections.Generic; using System.ComponentModel; // need this for the properties metadata using System.Drawing.Design; using System.Globalization; using System.Windows.Forms; using System.Windows.Forms.Design; namespace fyiReporting.RdlDesign { /// <summary> /// PropertyAction - /// </summary> [TypeConverter(typeof(PropertyBackgroundConverter))] [Editor(typeof(PropertyBackgroundUIEditor), typeof(UITypeEditor))] internal class PropertyBackground : IReportItem { PropertyReportItem pri; string[] _names; string[] _subitems; internal PropertyBackground(PropertyReportItem ri) { pri = ri; _names = null; _subitems = new string[] { "Style", "" }; } internal PropertyBackground(PropertyReportItem ri, params string[] names) { pri = ri; _names = names; // now build the array used to get/set values _subitems = new string[names.Length + 2]; int i = 0; foreach (string s in names) _subitems[i++] = s; _subitems[i++] = "Style"; } internal PropertyReportItem RI { get { return pri; } } internal string[] Names { get { return _names; } } [RefreshProperties(RefreshProperties.Repaint)] [TypeConverter(typeof(ColorConverter))] [LocalizedDisplayName("Background_Color")] [LocalizedDescription("Background_Color")] public string Color { get { return GetStyleValue("BackgroundColor", ""); } set { SetStyleValue("BackgroundColor", value); } } [RefreshProperties(RefreshProperties.Repaint)] [TypeConverter(typeof(ColorConverter))] [LocalizedDisplayName("Background_EndColor")] [LocalizedDescription("Background_EndColor")] public string EndColor { get { return GetStyleValue("BackgroundGradientEndColor", ""); } set { SetStyleValue("BackgroundGradientEndColor", value); } } [RefreshProperties(RefreshProperties.Repaint)] [TypeConverter(typeof(GradientTypeConverter))] [LocalizedDisplayName("Background_GradientType")] [LocalizedDescription("Background_GradientType")] public string GradientType { get { return GetStyleValue("BackgroundGradientType", "None"); } set { SetStyleValue("BackgroundGradientType", value); } } [LocalizedDisplayName("Background_Image")] [LocalizedDescription("Background_Image")] public PropertyBackgroundImage Image { get { return new PropertyBackgroundImage(pri, _names); } } private string GetStyleValue(string l1, string def) { _subitems[_subitems.Length - 1] = l1; return pri.GetWithList(def, _subitems); } private void SetStyleValue(string l1, string val) { _subitems[_subitems.Length - 1] = l1; pri.SetWithList(val, _subitems); } public override string ToString() { return GetStyleValue("BackgroundColor", ""); } #region IReportItem Members public PropertyReportItem GetPRI() { return pri; } #endregion } internal class PropertyBackgroundConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyBackground)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyBackground) { PropertyBackground pf = value as PropertyBackground; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } internal class PropertyBackgroundUIEditor : UITypeEditor { internal PropertyBackgroundUIEditor() { } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context == null) || (provider == null)) return base.EditValue(context, provider, value); // Access the Property Browser's UI display service IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (editorService == null) return base.EditValue(context, provider, value); // Create an instance of the UI editor form IReportItem iri = context.Instance as IReportItem; if (iri == null) return base.EditValue(context, provider, value); PropertyReportItem pre = iri.GetPRI(); string[] names; PropertyBackground pb = value as PropertyBackground; if (pb != null) names = pb.Names; else { PropertyBackgroundImage pbi = value as PropertyBackgroundImage; if (pbi == null) return base.EditValue(context, provider, value); names = pbi.Names; } using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes, SingleCtlTypeEnum.BackgroundCtl, names)) { // Display the UI editor dialog if (editorService.ShowDialog(scd) == DialogResult.OK) { // Return the new property value from the UI editor form return new PropertyBackground(pre); } return base.EditValue(context, provider, value); } } } #region GradientType internal class GradientTypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(StaticLists.GradientList); } } #endregion [TypeConverter(typeof(PropertyBackgroundImageConverter))] [Editor(typeof(PropertyBackgroundUIEditor), typeof(UITypeEditor))] internal class PropertyBackgroundImage : IReportItem { PropertyReportItem pri; string[] _names; string[] _subitems; internal PropertyBackgroundImage(PropertyReportItem ri, string[] names) { pri = ri; _names = names; if (names == null) { _subitems = new string[] { "Style", "BackgroundImage", "" }; } else { // now build the array used to get/set values _subitems = new string[names.Length + 3]; int i = 0; foreach (string s in names) _subitems[i++] = s; _subitems[i++] = "Style"; _subitems[i++] = "BackgroundImage"; } } internal string[] Names { get { return _names; } } public override string ToString() { string s = this.Source; string v = ""; if (s.ToLower().Trim() != "none") v = this.Value.Expression; return string.Format("{0} {1}", s, v); } [RefreshProperties(RefreshProperties.Repaint)] [TypeConverter(typeof(ImageSourceConverter))] [LocalizedDisplayName("BackgroundImage_Source")] [LocalizedDescription("BackgroundImage_Source")] public string Source { get { _subitems[_subitems.Length-1] = "Source"; return pri.GetWithList("None", _subitems); } set { if (value.ToLower().Trim() == "none") { List<string> l = new List<string>(_subitems); l.RemoveAt(l.Count - 1); pri.RemoveWithList(l.ToArray()); } else { _subitems[_subitems.Length - 1] = "Source"; pri.SetWithList(value, _subitems); } } } [RefreshProperties(RefreshProperties.Repaint)] [LocalizedDisplayName("BackgroundImage_Value")] [LocalizedDescription("BackgroundImage_Value")] public PropertyExpr Value { get { _subitems[_subitems.Length - 1] = "Value"; return new PropertyExpr(pri.GetWithList("", _subitems)); } set { if (this.Source.ToLower().Trim() == "none") throw new ArgumentException("Value isn't relevent when Source=None."); _subitems[_subitems.Length - 1] = "Value"; pri.SetWithList(value.Expression, _subitems); } } [RefreshProperties(RefreshProperties.Repaint)] [TypeConverter(typeof(ImageMIMETypeConverter))] [LocalizedDisplayName("BackgroundImage_MIMEType")] [LocalizedDescription("BackgroundImage_MIMEType")] public string MIMEType { get { _subitems[_subitems.Length - 1] = "MIMEType"; return pri.GetWithList("", _subitems); } set { if (this.Source.ToLower().Trim() != "database") throw new ArgumentException("MIMEType isn't relevent when Source isn't Database."); _subitems[_subitems.Length - 1] = "MIMEType"; pri.SetWithList(value, _subitems); } } [RefreshProperties(RefreshProperties.Repaint)] [TypeConverter(typeof(ImageRepeatConverter))] [LocalizedDisplayName("BackgroundImage_Repeat")] [LocalizedDescription("BackgroundImage_Repeat")] public string Repeat { get { _subitems[_subitems.Length - 1] = "BackgroundRepeat"; return pri.GetWithList("Repeat", _subitems); } set { if (this.Source.ToLower().Trim() == "none") throw new ArgumentException("Repeat isn't relevent when Source=None."); _subitems[_subitems.Length - 1] = "BackgroundRepeat"; pri.SetWithList(value, _subitems); } } #region IReportItem Members public PropertyReportItem GetPRI() { return pri; } #endregion } internal class PropertyBackgroundImageConverter : ExpandableObjectConverter { public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(PropertyBackgroundImage)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is PropertyBackgroundImage) { PropertyBackgroundImage pf = value as PropertyBackgroundImage; return pf.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } #region ImageSource internal class ImageSourceConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (context.Instance is PropertyImageI) return new StandardValuesCollection(new string[] { "External", "Embedded", "Database"}); else return new StandardValuesCollection(new string[] { "None", "External", "Embedded", "Database"}); } } #endregion #region ImageMIMEType internal class ImageMIMETypeConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] { "image/bmp", "image/jpeg", "image/gif", "image/png","image/x-png"}); } } #endregion #region ImageRepeat internal class ImageRepeatConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; // allow user to also edit directly } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] { "Repeat", "NoRepeat", "RepeatX", "RepeatY"}); } } #endregion }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.ClientStack.LindenUDP; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors.Hypergrid; using OpenMetaverse; using OpenMetaverse.Packets; using log4net; using Nini.Config; using Mono.Addins; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Region.CoreModules.Framework.UserManagement { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserManagementModule")] public class UserManagementModule : ISharedRegionModule, IUserManagement, IPeople { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected bool m_Enabled; protected List<Scene> m_Scenes = new List<Scene>(); protected IServiceThrottleModule m_ServiceThrottle; // The cache protected Dictionary<UUID, UserData> m_UserCache = new Dictionary<UUID, UserData>(); protected bool m_DisplayChangingHomeURI = false; #region ISharedRegionModule public virtual void Initialise(IConfigSource config) { string umanmod = config.Configs["Modules"].GetString("UserManagementModule", Name); if (umanmod == Name) { m_Enabled = true; Init(); m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name); } if(!m_Enabled) { return; } IConfig userManagementConfig = config.Configs["UserManagement"]; if (userManagementConfig == null) return; m_DisplayChangingHomeURI = userManagementConfig.GetBoolean("DisplayChangingHomeURI", false); } public virtual bool IsSharedModule { get { return true; } } public virtual string Name { get { return "BasicUserManagementModule"; } } public virtual Type ReplaceableInterface { get { return null; } } public virtual void AddRegion(Scene scene) { if (m_Enabled) { lock (m_Scenes) { m_Scenes.Add(scene); } scene.RegisterModuleInterface<IUserManagement>(this); scene.RegisterModuleInterface<IPeople>(this); scene.EventManager.OnNewClient += new EventManager.OnNewClientDelegate(EventManager_OnNewClient); scene.EventManager.OnPrimsLoaded += new EventManager.PrimsLoaded(EventManager_OnPrimsLoaded); } } public virtual void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IUserManagement>(this); lock (m_Scenes) { m_Scenes.Remove(scene); } } } public virtual void RegionLoaded(Scene s) { if (m_Enabled && m_ServiceThrottle == null) m_ServiceThrottle = s.RequestModuleInterface<IServiceThrottleModule>(); } public virtual void PostInitialise() { } public virtual void Close() { lock (m_Scenes) { m_Scenes.Clear(); } lock (m_UserCache) m_UserCache.Clear(); } #endregion ISharedRegionModule #region Event Handlers protected virtual void EventManager_OnPrimsLoaded(Scene s) { // let's sniff all the user names referenced by objects in the scene m_log.DebugFormat("[USER MANAGEMENT MODULE]: Caching creators' data from {0} ({1} objects)...", s.RegionInfo.RegionName, s.GetEntities().Length); s.ForEachSOG(delegate(SceneObjectGroup sog) { CacheCreators(sog); }); } protected virtual void EventManager_OnNewClient(IClientAPI client) { client.OnConnectionClosed += new Action<IClientAPI>(HandleConnectionClosed); client.OnNameFromUUIDRequest += new UUIDNameRequest(HandleUUIDNameRequest); client.OnAvatarPickerRequest += new AvatarPickerRequest(HandleAvatarPickerRequest); } protected virtual void HandleConnectionClosed(IClientAPI client) { client.OnNameFromUUIDRequest -= new UUIDNameRequest(HandleUUIDNameRequest); client.OnAvatarPickerRequest -= new AvatarPickerRequest(HandleAvatarPickerRequest); } protected virtual void HandleUUIDNameRequest(UUID uuid, IClientAPI client) { // m_log.DebugFormat( // "[USER MANAGEMENT MODULE]: Handling request for name binding of UUID {0} from {1}", // uuid, remote_client.Name); if(m_Scenes.Count <= 0) return; if (m_Scenes[0].LibraryService != null && (m_Scenes[0].LibraryService.LibraryRootFolder.Owner == uuid)) { client.SendNameReply(uuid, "Mr", "OpenSim"); } else { UserData user; /* bypass that continuation here when entry is already available */ lock (m_UserCache) { if (m_UserCache.TryGetValue(uuid, out user)) { if (!user.IsUnknownUser && user.HasGridUserTried) { client.SendNameReply(uuid, user.FirstName, user.LastName); return; } } } // Not found in cache, queue continuation m_ServiceThrottle.Enqueue("uuidname", uuid.ToString(), delegate { //m_log.DebugFormat("[YYY]: Name request {0}", uuid); // As least upto September 2013, clients permanently cache UUID -> Name bindings. Some clients // appear to clear this when the user asks it to clear the cache, but others may not. // // So to avoid clients // (particularly Hypergrid clients) permanently binding "Unknown User" to a given UUID, we will // instead drop the request entirely. if(!client.IsActive) return; if (GetUser(uuid, out user)) { if(client.IsActive) client.SendNameReply(uuid, user.FirstName, user.LastName); } // else // m_log.DebugFormat( // "[USER MANAGEMENT MODULE]: No bound name for {0} found, ignoring request from {1}", // uuid, client.Name); }); } } public virtual void HandleAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query) { //EventManager.TriggerAvatarPickerRequest(); m_log.DebugFormat("[USER MANAGEMENT MODULE]: HandleAvatarPickerRequest for {0}", query); List<UserData> users = GetUserData(query, 500, 1); AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket)PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply); // TODO: don't create new blocks if recycling an old packet AvatarPickerReplyPacket.DataBlock[] searchData = new AvatarPickerReplyPacket.DataBlock[users.Count]; AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock(); agentData.AgentID = avatarID; agentData.QueryID = RequestID; replyPacket.AgentData = agentData; //byte[] bytes = new byte[AvatarResponses.Count*32]; int i = 0; foreach (UserData item in users) { UUID translatedIDtem = item.Id; searchData[i] = new AvatarPickerReplyPacket.DataBlock(); searchData[i].AvatarID = translatedIDtem; searchData[i].FirstName = Utils.StringToBytes((string)item.FirstName); searchData[i].LastName = Utils.StringToBytes((string)item.LastName); i++; } if (users.Count == 0) { searchData = new AvatarPickerReplyPacket.DataBlock[0]; } replyPacket.Data = searchData; AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs(); agent_data.AgentID = replyPacket.AgentData.AgentID; agent_data.QueryID = replyPacket.AgentData.QueryID; List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>(); for (i = 0; i < replyPacket.Data.Length; i++) { AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs(); data_arg.AvatarID = replyPacket.Data[i].AvatarID; data_arg.FirstName = replyPacket.Data[i].FirstName; data_arg.LastName = replyPacket.Data[i].LastName; data_args.Add(data_arg); } client.SendAvatarPickerReply(agent_data, data_args); } protected virtual void AddAdditionalUsers(string query, List<UserData> users) { } #endregion Event Handlers #region IPeople public virtual List<UserData> GetUserData(string query, int page_size, int page_number) { if(m_Scenes.Count <= 0) return new List<UserData>();; // search the user accounts service List<UserAccount> accs = m_Scenes[0].UserAccountService.GetUserAccounts(m_Scenes[0].RegionInfo.ScopeID, query); List<UserData> users = new List<UserData>(); if (accs != null) { foreach (UserAccount acc in accs) { UserData ud = new UserData(); ud.FirstName = acc.FirstName; ud.LastName = acc.LastName; ud.Id = acc.PrincipalID; ud.HasGridUserTried = true; ud.IsUnknownUser = false; users.Add(ud); } } // search the local cache foreach (UserData data in m_UserCache.Values) { if (data.Id != UUID.Zero && !data.IsUnknownUser && users.Find(delegate(UserData d) { return d.Id == data.Id; }) == null && (data.FirstName.ToLower().StartsWith(query.ToLower()) || data.LastName.ToLower().StartsWith(query.ToLower()))) users.Add(data); } AddAdditionalUsers(query, users); return users; } #endregion IPeople protected virtual void CacheCreators(SceneObjectGroup sog) { //m_log.DebugFormat("[USER MANAGEMENT MODULE]: processing {0} {1}; {2}", sog.RootPart.Name, sog.RootPart.CreatorData, sog.RootPart.CreatorIdentification); AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData); foreach (SceneObjectPart sop in sog.Parts) { AddUser(sop.CreatorID, sop.CreatorData); foreach (TaskInventoryItem item in sop.TaskInventory.Values) AddUser(item.CreatorID, item.CreatorData); } } /// <summary> /// /// </summary> /// <param name="uuid"></param> /// <param name="names">Caller please provide a properly instantiated array for names, string[2]</param> /// <returns></returns> protected virtual bool TryGetUserNames(UUID uuid, string[] names) { if (names == null) names = new string[2]; if (TryGetUserNamesFromCache(uuid, names)) return true; if (TryGetUserNamesFromServices(uuid, names)) return true; return false; } protected virtual bool TryGetUserNamesFromCache(UUID uuid, string[] names) { lock (m_UserCache) { if (m_UserCache.ContainsKey(uuid)) { names[0] = m_UserCache[uuid].FirstName; names[1] = m_UserCache[uuid].LastName; return true; } } return false; } /// <summary> /// Try to get the names bound to the given uuid, from the services. /// </summary> /// <returns>True if the name was found, false if not.</returns> /// <param name='uuid'></param> /// <param name='names'>The array of names if found. If not found, then names[0] = "Unknown" and names[1] = "User"</param> protected virtual bool TryGetUserNamesFromServices(UUID uuid, string[] names) { if(m_Scenes.Count <= 0) return false; UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, uuid); if (account != null) { names[0] = account.FirstName; names[1] = account.LastName; UserData user = new UserData(); user.FirstName = account.FirstName; user.LastName = account.LastName; lock (m_UserCache) m_UserCache[uuid] = user; return true; } else { // Let's try the GridUser service GridUserInfo uInfo = m_Scenes[0].GridUserService.GetGridUserInfo(uuid.ToString()); if (uInfo != null) { string url, first, last, tmp; UUID u; if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out u, out url, out first, out last, out tmp)) { AddUser(uuid, first, last, url); if (m_UserCache.ContainsKey(uuid)) { names[0] = m_UserCache[uuid].FirstName; names[1] = m_UserCache[uuid].LastName; return true; } } else m_log.DebugFormat("[USER MANAGEMENT MODULE]: Unable to parse UUI {0}", uInfo.UserID); } // else // { // m_log.DebugFormat("[USER MANAGEMENT MODULE]: No grid user found for {0}", uuid); // } names[0] = "Unknown"; names[1] = "UserUMMTGUN9"; return false; } } #region IUserManagement public virtual UUID GetUserIdByName(string name) { string[] parts = name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 2) throw new Exception("Name must have 2 components"); return GetUserIdByName(parts[0], parts[1]); } public virtual UUID GetUserIdByName(string firstName, string lastName) { if(m_Scenes.Count <= 0) return UUID.Zero; // TODO: Optimize for reverse lookup if this gets used by non-console commands. lock (m_UserCache) { foreach (UserData user in m_UserCache.Values) { if (user.FirstName == firstName && user.LastName == lastName) return user.Id; } } UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName); if (account != null) return account.PrincipalID; return UUID.Zero; } public virtual string GetUserName(UUID uuid) { UserData user; GetUser(uuid, out user); return user.FirstName + " " + user.LastName; } public virtual Dictionary<UUID,string> GetUsersNames(string[] ids) { Dictionary<UUID,string> ret = new Dictionary<UUID,string>(); if(m_Scenes.Count <= 0) return ret; List<string> missing = new List<string>(); Dictionary<UUID,string> untried = new Dictionary<UUID, string>(); // look in cache UserData userdata = new UserData(); UUID uuid = UUID.Zero; foreach(string id in ids) { if(UUID.TryParse(id, out uuid)) { lock (m_UserCache) { if (m_UserCache.TryGetValue(uuid, out userdata) && userdata.FirstName != "Unknown" && userdata.FirstName != string.Empty) { string name = userdata.FirstName + " " + userdata.LastName; if(userdata.HasGridUserTried) ret[uuid] = name; else { untried[uuid] = name; missing.Add(id); } } else missing.Add(id); } } } if(missing.Count == 0) return ret; // try user account service List<UserAccount> accounts = m_Scenes[0].UserAccountService.GetUserAccounts( m_Scenes[0].RegionInfo.ScopeID, missing); if(accounts.Count != 0) { foreach(UserAccount uac in accounts) { if(uac != null) { string name = uac.FirstName + " " + uac.LastName; ret[uac.PrincipalID] = name; missing.Remove(uac.PrincipalID.ToString()); // slowww untried.Remove(uac.PrincipalID); userdata = new UserData(); userdata.Id = uac.PrincipalID; userdata.FirstName = uac.FirstName; userdata.LastName = uac.LastName; userdata.HomeURL = string.Empty; userdata.IsUnknownUser = false; userdata.HasGridUserTried = true; lock (m_UserCache) m_UserCache[uac.PrincipalID] = userdata; } } } if (missing.Count == 0 || m_Scenes[0].GridUserService == null) return ret; // try grid user service GridUserInfo[] pinfos = m_Scenes[0].GridUserService.GetGridUserInfo(missing.ToArray()); if(pinfos.Length > 0) { foreach(GridUserInfo uInfo in pinfos) { if (uInfo != null) { string url, first, last, tmp; if(uInfo.UserID.Length <= 36) continue; if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out uuid, out url, out first, out last, out tmp)) { if (url != string.Empty) { try { userdata = new UserData(); userdata.FirstName = first.Replace(" ", ".") + "." + last.Replace(" ", "."); userdata.LastName = "@" + new Uri(url).Authority; userdata.Id = uuid; userdata.HomeURL = url; userdata.IsUnknownUser = false; userdata.HasGridUserTried = true; lock (m_UserCache) m_UserCache[uuid] = userdata; string name = userdata.FirstName + " " + userdata.LastName; ret[uuid] = name; missing.Remove(uuid.ToString()); untried.Remove(uuid); } catch { } } } } } } // add the untried in cache that still failed if(untried.Count > 0) { foreach(KeyValuePair<UUID, string> kvp in untried) { ret[kvp.Key] = kvp.Value; missing.Remove((kvp.Key).ToString()); } } // add the UMMthings ( not sure we should) if(missing.Count > 0) { foreach(string id in missing) { if(UUID.TryParse(id, out uuid) && uuid != UUID.Zero) { if (m_Scenes[0].LibraryService != null && (m_Scenes[0].LibraryService.LibraryRootFolder.Owner == uuid)) ret[uuid] = "Mr OpenSim"; else ret[uuid] = "Unknown UserUMMAU43"; } } } return ret; } public virtual string GetUserHomeURL(UUID userID) { UserData user; if(GetUser(userID, out user)) { return user.HomeURL; } return string.Empty; } public virtual string GetUserServerURL(UUID userID, string serverType) { UserData userdata; if(!GetUser(userID, out userdata)) { return string.Empty; } if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null) { return userdata.ServerURLs[serverType].ToString(); } if (!string.IsNullOrEmpty(userdata.HomeURL)) { // m_log.DebugFormat("[USER MANAGEMENT MODULE]: Requested url type {0} for {1}", serverType, userID); UserAgentServiceConnector uConn = new UserAgentServiceConnector(userdata.HomeURL); try { userdata.ServerURLs = uConn.GetServerURLs(userID); } catch(System.Net.WebException e) { m_log.DebugFormat("[USER MANAGEMENT MODULE]: GetServerURLs call failed {0}", e.Message); userdata.ServerURLs = new Dictionary<string, object>(); } catch (Exception e) { m_log.Debug("[USER MANAGEMENT MODULE]: GetServerURLs call failed ", e); userdata.ServerURLs = new Dictionary<string, object>(); } if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null) return userdata.ServerURLs[serverType].ToString(); } return string.Empty; } public virtual string GetUserUUI(UUID userID) { string uui; GetUserUUI(userID, out uui); return uui; } public virtual bool GetUserUUI(UUID userID, out string uui) { UserData ud; bool result = GetUser(userID, out ud); if (ud != null) { string homeURL = ud.HomeURL; string first = ud.FirstName, last = ud.LastName; if (ud.LastName.StartsWith("@")) { string[] parts = ud.FirstName.Split('.'); if (parts.Length >= 2) { first = parts[0]; last = parts[1]; } uui = userID + ";" + homeURL + ";" + first + " " + last; return result; } } uui = userID.ToString(); return result; } #region Cache Management public virtual bool GetUser(UUID uuid, out UserData userdata) { if(m_Scenes.Count <= 0) { userdata = new UserData(); return false; } lock (m_UserCache) { if (m_UserCache.TryGetValue(uuid, out userdata)) { if (userdata.HasGridUserTried) { return true; } } else { userdata = new UserData(); userdata.Id = uuid; userdata.FirstName = "Unknown"; userdata.LastName = "UserUMMAU42"; userdata.HomeURL = string.Empty; userdata.IsUnknownUser = true; userdata.HasGridUserTried = false; } } /* BEGIN: do not wrap this code in any lock here * There are HTTP calls in here. */ if (!userdata.HasGridUserTried) { /* rewrite here */ UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid); if (account != null) { userdata.FirstName = account.FirstName; userdata.LastName = account.LastName; userdata.HomeURL = string.Empty; userdata.IsUnknownUser = false; userdata.HasGridUserTried = true; } } if (!userdata.HasGridUserTried) { GridUserInfo uInfo = null; if (null != m_Scenes[0].GridUserService) { uInfo = m_Scenes[0].GridUserService.GetGridUserInfo(uuid.ToString()); } if (uInfo != null) { string url, first, last, tmp; UUID u; if(uInfo.UserID.Length <= 36) { /* not a UUI */ } else if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out u, out url, out first, out last, out tmp)) { if (url != string.Empty) { userdata.FirstName = first.Replace(" ", ".") + "." + last.Replace(" ", "."); userdata.HomeURL = url; try { userdata.LastName = "@" + new Uri(url).Authority; userdata.IsUnknownUser = false; } catch { userdata.LastName = "@unknown"; } userdata.HasGridUserTried = true; } } else m_log.DebugFormat("[USER MANAGEMENT MODULE]: Unable to parse UUI {0}", uInfo.UserID); } } /* END: do not wrap this code in any lock here */ lock (m_UserCache) { m_UserCache[uuid] = userdata; } return !userdata.IsUnknownUser; } public virtual void AddUser(UUID uuid, string first, string last, bool isNPC = false) { lock(m_UserCache) { if(!m_UserCache.ContainsKey(uuid)) { UserData user = new UserData(); user.Id = uuid; user.FirstName = first; user.LastName = last; user.IsUnknownUser = false; user.HasGridUserTried = isNPC; m_UserCache.Add(uuid, user); } } } public virtual void AddUser(UUID uuid, string first, string last, string homeURL) { //m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, first {1}, last {2}, url {3}", uuid, first, last, homeURL); UserData oldUser; lock (m_UserCache) { if (m_UserCache.TryGetValue(uuid, out oldUser)) { if (!oldUser.IsUnknownUser) { if (homeURL != oldUser.HomeURL && m_DisplayChangingHomeURI) { m_log.DebugFormat("[USER MANAGEMENT MODULE]: Different HomeURI for {0} {1} ({2}): {3} and {4}", first, last, uuid.ToString(), homeURL, oldUser.HomeURL); } /* no update needed */ return; } } else if(!m_UserCache.ContainsKey(uuid)) { oldUser = new UserData(); oldUser.HasGridUserTried = false; oldUser.IsUnknownUser = false; if (homeURL != string.Empty) { oldUser.FirstName = first.Replace(" ", ".") + "." + last.Replace(" ", "."); try { oldUser.LastName = "@" + new Uri(homeURL).Authority; oldUser.IsUnknownUser = false; } catch { oldUser.LastName = "@unknown"; } } else { oldUser.FirstName = first; oldUser.LastName = last; } oldUser.HomeURL = homeURL; oldUser.Id = uuid; m_UserCache.Add(uuid, oldUser); } } } public virtual void AddUser(UUID id, string creatorData) { // m_log.InfoFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, creatorData {1}", id, creatorData); if(string.IsNullOrEmpty(creatorData)) { AddUser(id, string.Empty, string.Empty, string.Empty); } else { string homeURL; string firstname = string.Empty; string lastname = string.Empty; //creatorData = <endpoint>;<name> string[] parts = creatorData.Split(';'); if(parts.Length > 1) { string[] nameparts = parts[1].Split(' '); firstname = nameparts[0]; for(int xi = 1; xi < nameparts.Length; ++xi) { if(xi != 1) { lastname += " "; } lastname += nameparts[xi]; } } else { firstname = "Unknown"; lastname = "UserUMMAU5"; } if (parts.Length >= 1) { homeURL = parts[0]; if(Uri.IsWellFormedUriString(homeURL, UriKind.Absolute)) { AddUser(id, firstname, lastname, homeURL); } else { m_log.DebugFormat("[SCENE]: Unable to parse Uri {0} for CreatorID {1}", parts[0], creatorData); lock (m_UserCache) { if(!m_UserCache.ContainsKey(id)) { UserData newUser = new UserData(); newUser.Id = id; newUser.FirstName = firstname + "." + lastname.Replace(' ', '.'); newUser.LastName = "@unknown"; newUser.HomeURL = string.Empty; newUser.HasGridUserTried = false; newUser.IsUnknownUser = true; /* we mark those users as Unknown user so a re-retrieve may be activated */ m_UserCache.Add(id, newUser); } } } } else { lock(m_UserCache) { if(!m_UserCache.ContainsKey(id)) { UserData newUser = new UserData(); newUser.Id = id; newUser.FirstName = "Unknown"; newUser.LastName = "UserUMMAU4"; newUser.HomeURL = string.Empty; newUser.IsUnknownUser = true; newUser.HasGridUserTried = false; m_UserCache.Add(id, newUser); } } } } } #endregion public virtual bool IsLocalGridUser(UUID uuid) { lock (m_Scenes) { if (m_Scenes.Count == 0) return true; UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid); if (account == null || (account != null && !account.LocalToGrid)) return false; } return true; } #endregion IUserManagement protected virtual void Init() { AddUser(UUID.Zero, "Unknown", "User"); RegisterConsoleCmds(); } protected virtual void RegisterConsoleCmds() { MainConsole.Instance.Commands.AddCommand("Users", true, "show name", "show name <uuid>", "Show the bindings between a single user UUID and a user name", String.Empty, HandleShowUser); MainConsole.Instance.Commands.AddCommand("Users", true, "show names", "show names", "Show the bindings between user UUIDs and user names", String.Empty, HandleShowUsers); MainConsole.Instance.Commands.AddCommand("Users", true, "reset user cache", "reset user cache", "reset user cache to allow changed settings to be applied", String.Empty, HandleResetUserCache); } protected virtual void HandleResetUserCache(string module, string[] cmd) { lock(m_UserCache) { m_UserCache.Clear(); } } protected virtual void HandleShowUser(string module, string[] cmd) { if (cmd.Length < 3) { MainConsole.Instance.OutputFormat("Usage: show name <uuid>"); return; } UUID userId; if (!ConsoleUtil.TryParseConsoleUuid(MainConsole.Instance, cmd[2], out userId)) return; UserData ud; if(!GetUser(userId, out ud)) { MainConsole.Instance.OutputFormat("No name known for user with id {0}", userId); return; } ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("UUID", 36); cdt.AddColumn("Name", 30); cdt.AddColumn("HomeURL", 40); cdt.AddRow(userId, string.Format("{0} {1}", ud.FirstName, ud.LastName), ud.HomeURL); MainConsole.Instance.Output(cdt.ToString()); } protected virtual void HandleShowUsers(string module, string[] cmd) { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("UUID", 36); cdt.AddColumn("Name", 30); cdt.AddColumn("HomeURL", 40); cdt.AddColumn("Checked", 10); Dictionary<UUID, UserData> copyDict; lock(m_UserCache) { copyDict = new Dictionary<UUID, UserData>(m_UserCache); } foreach(KeyValuePair<UUID, UserData> kvp in copyDict) { cdt.AddRow(kvp.Key, string.Format("{0} {1}", kvp.Value.FirstName, kvp.Value.LastName), kvp.Value.HomeURL, kvp.Value.HasGridUserTried ? "yes" : "no"); } MainConsole.Instance.Output(cdt.ToString()); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Linq; using FluentAssertions; using Microsoft.DotNet.Cli.CommandResolution; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using NuGet.Frameworks; using NuGet.ProjectModel; using NuGet.Versioning; using Xunit; namespace Microsoft.DotNet.Tests { public class GivenAProjectToolsCommandResolver : TestBase { private static readonly NuGetFramework s_toolPackageFramework = FrameworkConstants.CommonFrameworks.NetCoreApp10; private const string TestProjectName = "AppWithToolDependency"; [Fact] public void It_returns_null_when_CommandName_is_null() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = null, CommandArguments = new string[] { "" }, ProjectDirectory = "/some/directory" }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_ProjectDirectory_is_null() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = null }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_CommandName_does_not_exist_in_ProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "nonexistent-command", CommandArguments = null, ProjectDirectory = testInstance.Path }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_a_CommandSpec_with_DOTNET_as_FileName_and_CommandName_in_Args_when_CommandName_exists_in_ProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Path }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandFile = Path.GetFileNameWithoutExtension(result.Path); commandFile.Should().Be("dotnet"); result.Args.Should().Contain(commandResolverArguments.CommandName); } [Fact] public void It_escapes_CommandArguments_when_returning_a_CommandSpec() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = new[] { "arg with space" }, ProjectDirectory = testInstance.Path }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain("\"arg with space\""); } [Fact] public void It_returns_a_CommandSpec_with_Args_containing_CommandPath_when_returning_a_CommandSpec_and_CommandArguments_are_null() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Path }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain("dotnet-portable.dll"); } [Fact] public void It_writes_a_deps_json_file_next_to_the_lockfile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Path }; var context = ProjectContext.Create(Path.Combine(testInstance.Path, "project.json"), s_toolPackageFramework); var nugetPackagesRoot = context.PackagesDirectory; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var directory = Path.GetDirectoryName(lockFilePath); var depsJsonFile = Directory .EnumerateFiles(directory) .FirstOrDefault(p => Path.GetFileName(p).EndsWith(FileNameSuffixes.DepsJson)); if (depsJsonFile != null) { File.Delete(depsJsonFile); } var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); depsJsonFile = Directory .EnumerateFiles(directory) .FirstOrDefault(p => Path.GetFileName(p).EndsWith(FileNameSuffixes.DepsJson)); depsJsonFile.Should().NotBeNull(); } [Fact] public void Generate_deps_json_method_doesnt_overwrite_when_deps_file_already_exists() { var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var context = ProjectContext.Create(Path.Combine(testInstance.Path, "project.json"), s_toolPackageFramework); var nugetPackagesRoot = context.PackagesDirectory; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var lockFile = new LockFileFormat().Read(lockFilePath); var depsJsonFile = Path.Combine( Path.GetDirectoryName(lockFilePath), "dotnet-portable.deps.json"); if (File.Exists(depsJsonFile)) { File.Delete(depsJsonFile); } File.WriteAllText(depsJsonFile, "temp"); var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); projectToolsCommandResolver.GenerateDepsJsonFile( lockFile, depsJsonFile, new SingleProjectInfo("dotnet-portable", "1.0.0", Enumerable.Empty<ResourceAssemblyInfo>())); File.ReadAllText(depsJsonFile).Should().Be("temp"); File.Delete(depsJsonFile); } private ProjectToolsCommandResolver SetupProjectToolsCommandResolver( IPackagedCommandSpecFactory packagedCommandSpecFactory = null) { packagedCommandSpecFactory = packagedCommandSpecFactory ?? new PackagedCommandSpecFactory(); var projectToolsCommandResolver = new ProjectToolsCommandResolver(packagedCommandSpecFactory); return projectToolsCommandResolver; } } }
// // Context.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using System.Collections.Generic; using Xwt.Backends; namespace Xwt.Drawing { public sealed class Context: DrawingPath { ContextBackendHandler handler; Pattern pattern; double globalAlpha = 1; StyleSet styles; static HashSet<string> registeredStyles = new HashSet<string> (); static StyleSet globalStyles = StyleSet.Empty; SavedContext stackTop; class SavedContext { public double Alpha; public StyleSet Styles; public SavedContext Previous; } internal Context (object backend, Toolkit toolkit): this (backend, toolkit, toolkit.ContextBackendHandler) { } internal Context (object backend, Toolkit toolkit, ContextBackendHandler handler, bool getGlobalStyles = true): base (backend, toolkit, handler) { this.handler = handler; if (getGlobalStyles) { styles = globalStyles; if (styles != StyleSet.Empty) handler.SetStyles (Backend, styles); } } internal ContextBackendHandler Handler { get { return handler; } } internal void Reset (Widget forWidget) { } /// <summary> /// Makes a copy of the current state of the Context and saves it on an internal stack of saved states. /// When Restore() is called, it will be restored to the saved state. /// Multiple calls to Save() and Restore() can be nested; /// each call to Restore() restores the state from the matching paired save(). /// </summary> public void Save () { handler.Save (Backend); stackTop = new SavedContext { Alpha = globalAlpha, Styles = styles, Previous = stackTop, }; } public void Restore () { handler.Restore (Backend); if (stackTop != null) { var info = stackTop; stackTop = stackTop.Previous; globalAlpha = info.Alpha; if (styles != info.Styles) { styles = info.Styles; handler.SetStyles (Backend, styles); } } } public double GlobalAlpha { get { return globalAlpha; } set { globalAlpha = value; handler.SetGlobalAlpha (Backend, globalAlpha); } } internal void SetStyles (StyleSet styles) { this.styles = this.styles.AddRange (styles.Intersect (RegisteredStyles).ToArray ()); this.styles = this.styles.RemoveAll (styles.Where (s => s.StartsWith ("-", StringComparison.Ordinal)).Select (s => s.TrimStart ('-')).ToArray ()); handler.SetStyles (Backend, this.styles); } public void SetStyle (string style) { if (string.IsNullOrEmpty (style)) throw new ArgumentException ("style can't be empty"); if (style[0] == '!') styles = styles.Remove (style.Substring (1)); else styles = styles.Add (style); handler.SetStyles (Backend, styles); } public void ClearStyle (string style) { if (string.IsNullOrEmpty (style)) throw new ArgumentException ("style can't be empty"); styles = styles.Remove (style); handler.SetStyles (Backend, styles); } public void ClearAllStyles () { styles = StyleSet.Empty; handler.SetStyles (Backend, styles); } public bool HasStyle (string name) { return styles.Contains (name); } public IEnumerable<string> Styles { get { return styles; } } public void SetColor (Color color) { handler.SetColor (Backend, color); } /// <summary> /// Establishes a new clip region by intersecting the current clip region with the current Path /// as it would be filled by fill() and according to the current fill rule. /// After clip(), the current path will be cleared from the Context. /// The current clip region affects all drawing operations by effectively masking out any changes to the surface /// that are outside the current clip region. /// Calling clip() can only make the clip region smaller, never larger. /// But the current clip is part of the graphics state, /// so a temporary restriction of the clip region can be achieved by calling clip() within a save()/restore() pair. /// The only other means of increasing the size of the clip region is reset_clip(). /// </summary> public void Clip () { handler.Clip (Backend); } public void ClipPreserve () { handler.ClipPreserve (Backend); } public void Fill () { handler.Fill (Backend); } public void FillPreserve () { handler.FillPreserve (Backend); } public void NewPath () { handler.NewPath (Backend); } public void Stroke () { handler.Stroke (Backend); } public void StrokePreserve () { handler.StrokePreserve (Backend); } public void SetLineWidth (double width) { handler.SetLineWidth (Backend, width); } public void DrawTextLayout (TextLayout layout, Point location) { handler.DrawTextLayout (Backend, layout, location.X, location.Y); } public void DrawTextLayout (TextLayout layout, double x, double y) { handler.DrawTextLayout (Backend, layout, x, y); } public void DrawImage (Image img, Point location, double alpha = 1) { DrawImage (img, location.X, location.Y, alpha); } public void DrawImage (Image img, double x, double y, double alpha = 1) { if (!img.HasFixedSize) throw new InvalidOperationException ("Image doesn't have a fixed size"); var idesc = img.GetImageDescription (ToolkitEngine); idesc.Alpha *= alpha; handler.DrawImage (Backend, idesc, x, y); } public void DrawImage (Image img, Rectangle rect, double alpha = 1) { DrawImage (img, rect.X, rect.Y, rect.Width, rect.Height, alpha); } public void DrawImage (Image img, double x, double y, double width, double height, double alpha = 1) { if (width <= 0 || height <= 0) return; var idesc = img.GetImageDescription (ToolkitEngine); idesc.Alpha *= alpha; idesc.Size = new Size (width, height); handler.DrawImage (Backend, idesc, x, y); } public void DrawImage (Image img, Rectangle srcRect, Rectangle destRect) { DrawImage (img, srcRect, destRect, 1); } public void DrawImage (Image img, Rectangle srcRect, Rectangle destRect, double alpha) { if (!img.HasFixedSize) throw new InvalidOperationException ("Image doesn't have a fixed size"); var idesc = img.GetImageDescription (ToolkitEngine); idesc.Alpha *= alpha; handler.DrawImage (Backend, idesc, srcRect, destRect); } /// <summary> /// Applies a rotation transformation /// </summary> /// <param name='angle'> /// Angle in degrees /// </param> /// <remarks> /// Modifies the current transformation matrix (CTM) by rotating the user-space axes by angle degrees. /// The rotation of the axes takes places after any existing transformation of user space. /// The rotation direction for positive angles is from the positive X axis toward the positive Y axis. /// </remarks> public void Rotate (double angle) { handler.Rotate (Backend, angle); } public void Scale (double scaleX, double scaleY) { handler.Scale (Backend, scaleX, scaleY); } public void Translate (double tx, double ty) { handler.Translate (Backend, tx, ty); } public void Translate (Point p) { handler.Translate (Backend, p.X, p.Y); } /// <summary> /// Modifies the Current Transformation Matrix (CTM) by prepending the Matrix transform specified /// </summary> /// <remarks> /// This enables any 'non-standard' transforms (eg skew, reflection) to be used for drawing, /// and provides the link to the extra transform capabilities provided by Xwt.Drawing.Matrix /// </remarks> public void ModifyCTM (Matrix transform) { handler.ModifyCTM (Backend, transform); } /// <summary> /// Returns a copy of the current transformation matrix (CTM) /// </summary> public Matrix GetCTM () { return handler.GetCTM (Backend); } /// <summary> /// Transforms the point (x, y) by the current transformation matrix (CTM) /// </summary> public void TransformPoint (ref double x, ref double y) { Matrix m = GetCTM (); Point p = m.Transform (new Point (x, y)); x = p.X; y = p.Y; } /// <summary> /// Transforms the point (x, y) by the current transformation matrix (CTM) /// </summary> public Point TransformPoint (Point p) { Matrix m = GetCTM (); return m.Transform (p); } /// <summary> /// Transforms the distance (dx, dy) by the scale and rotation elements (only) of the CTM /// </summary> public void TransformDistance (ref double dx, ref double dy) { Matrix m = GetCTM (); Point p = m.TransformVector (new Point (dx, dy)); dx = p.X; dy = p.Y; } /// <summary> /// Transforms the distance (dx, dy) by the scale and rotation elements (only) of the CTM /// </summary> public Distance TransformDistance (Distance distance) { double dx = distance.Dx; double dy = distance.Dy; TransformDistance (ref dx, ref dy); return new Distance (dx, dy); } /// <summary> /// Transforms the array of points by the current transformation matrix (CTM) /// </summary> public void TransformPoints (Point[] points) { Matrix m = GetCTM (); m.Transform (points); } /// <summary> /// Transforms the array of distances by the scale and rotation elements (only) of the CTM /// </summary> public void TransformDistances (Distance[] vectors) { Point p; Matrix m = GetCTM (); for (int i = 0; i < vectors.Length; ++i) { p = (Point)vectors[i]; m.TransformVector (p); vectors[i].Dx = p.X; vectors[i].Dy = p.Y; } } public bool IsPointInStroke (Point p) { return IsPointInStroke (p.X, p.Y); } /// <summary> /// Tests whether the given point is inside the area that would be affected if Stroke were called on this Context. /// </summary> /// <returns> /// <c>true</c> if the specified point would be in the stroke; otherwise, <c>false</c>. /// </returns> /// <param name='x'> /// The x coordinate. /// </param> /// <param name='y'> /// The y coordinate. /// </param> public bool IsPointInStroke (double x, double y) { return handler.IsPointInStroke (Backend, x, y); } public Pattern Pattern { get { return pattern; } set { pattern = value; handler.SetPattern (Backend, value); } } /// <summary> /// Sets the dash pattern to be used by stroke(). /// A dash pattern is specified by dashes, an array of positive values. /// Each value provides the user-space length of altenate "on" and "off" portions of the stroke. /// The offset specifies an offset into the pattern at which the stroke begins. /// If dashes is empty dashing is disabled. If the size of dashes is 1, /// a symmetric pattern is assumed with alternating on and off portions of the size specified by the single value in dashes. /// It is invalid for any value in dashes to be negative, or for all values to be 0. /// If this is the case, an exception will be thrown /// </summary> /// <param name='offset'> /// Offset. /// </param> /// <param name='pattern'> /// Pattern. /// </param> public void SetLineDash (double offset, params double[] pattern) { handler.SetLineDash (Backend, offset, pattern); } internal double ScaleFactor { get { return handler.GetScaleFactor (Backend); } } public static void RegisterStyles (params string[] styleNames) { registeredStyles.UnionWith (styleNames); } public static void UnregisterStyles (params string[] styleNames) { registeredStyles.ExceptWith (styleNames); } public static bool HasGlobalStyle (string style) { return globalStyles.Contains (style); } public static void SetGlobalStyle (string style) { // Make a copy of the collection since it may be referenced from context instances, // which don't expect the collection to change globalStyles = globalStyles.Add (style); NotifyGlobalStylesChanged (); } public static void ClearGlobalStyle (string style) { globalStyles = globalStyles.Remove (style); NotifyGlobalStylesChanged (); } public static IEnumerable<string> RegisteredStyles { get { return registeredStyles; } } public static IEnumerable<string> GlobalStyles { get { return globalStyles; } } internal static int GlobalStylesVersion { get { return stylesVersion; } } static int stylesVersion; static void NotifyGlobalStylesChanged () { stylesVersion++; if (GlobalStylesChanged != null) GlobalStylesChanged (null, EventArgs.Empty); } public static event EventHandler GlobalStylesChanged; } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.2.5. Articulation parameters for movable parts and attached parts of an entity. Specifes wether or not a change has occured, the part identifcation of the articulated part to which it is attached, and the type and value of each parameter. /// </summary> [Serializable] [XmlRoot] public partial class ArticulationParameter { private byte _parameterTypeDesignator; private byte _changeIndicator; private ushort _partAttachedTo; private int _parameterType; private double _parameterValue; /// <summary> /// Initializes a new instance of the <see cref="ArticulationParameter"/> class. /// </summary> public ArticulationParameter() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(ArticulationParameter left, ArticulationParameter right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(ArticulationParameter left, ArticulationParameter right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 1; // this._parameterTypeDesignator marshalSize += 1; // this._changeIndicator marshalSize += 2; // this._partAttachedTo marshalSize += 4; // this._parameterType marshalSize += 8; // this._parameterValue return marshalSize; } /// <summary> /// Gets or sets the parameterTypeDesignator /// </summary> [XmlElement(Type = typeof(byte), ElementName = "parameterTypeDesignator")] public byte ParameterTypeDesignator { get { return this._parameterTypeDesignator; } set { this._parameterTypeDesignator = value; } } /// <summary> /// Gets or sets the changeIndicator /// </summary> [XmlElement(Type = typeof(byte), ElementName = "changeIndicator")] public byte ChangeIndicator { get { return this._changeIndicator; } set { this._changeIndicator = value; } } /// <summary> /// Gets or sets the partAttachedTo /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "partAttachedTo")] public ushort PartAttachedTo { get { return this._partAttachedTo; } set { this._partAttachedTo = value; } } /// <summary> /// Gets or sets the parameterType /// </summary> [XmlElement(Type = typeof(int), ElementName = "parameterType")] public int ParameterType { get { return this._parameterType; } set { this._parameterType = value; } } /// <summary> /// Gets or sets the parameterValue /// </summary> [XmlElement(Type = typeof(double), ElementName = "parameterValue")] public double ParameterValue { get { return this._parameterValue; } set { this._parameterValue = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteUnsignedByte((byte)this._parameterTypeDesignator); dos.WriteUnsignedByte((byte)this._changeIndicator); dos.WriteUnsignedShort((ushort)this._partAttachedTo); dos.WriteInt((int)this._parameterType); dos.WriteDouble((double)this._parameterValue); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._parameterTypeDesignator = dis.ReadUnsignedByte(); this._changeIndicator = dis.ReadUnsignedByte(); this._partAttachedTo = dis.ReadUnsignedShort(); this._parameterType = dis.ReadInt(); this._parameterValue = dis.ReadDouble(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<ArticulationParameter>"); try { sb.AppendLine("<parameterTypeDesignator type=\"byte\">" + this._parameterTypeDesignator.ToString(CultureInfo.InvariantCulture) + "</parameterTypeDesignator>"); sb.AppendLine("<changeIndicator type=\"byte\">" + this._changeIndicator.ToString(CultureInfo.InvariantCulture) + "</changeIndicator>"); sb.AppendLine("<partAttachedTo type=\"ushort\">" + this._partAttachedTo.ToString(CultureInfo.InvariantCulture) + "</partAttachedTo>"); sb.AppendLine("<parameterType type=\"int\">" + this._parameterType.ToString(CultureInfo.InvariantCulture) + "</parameterType>"); sb.AppendLine("<parameterValue type=\"double\">" + this._parameterValue.ToString(CultureInfo.InvariantCulture) + "</parameterValue>"); sb.AppendLine("</ArticulationParameter>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as ArticulationParameter; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(ArticulationParameter obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._parameterTypeDesignator != obj._parameterTypeDesignator) { ivarsEqual = false; } if (this._changeIndicator != obj._changeIndicator) { ivarsEqual = false; } if (this._partAttachedTo != obj._partAttachedTo) { ivarsEqual = false; } if (this._parameterType != obj._parameterType) { ivarsEqual = false; } if (this._parameterValue != obj._parameterValue) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._parameterTypeDesignator.GetHashCode(); result = GenerateHash(result) ^ this._changeIndicator.GetHashCode(); result = GenerateHash(result) ^ this._partAttachedTo.GetHashCode(); result = GenerateHash(result) ^ this._parameterType.GetHashCode(); result = GenerateHash(result) ^ this._parameterValue.GetHashCode(); return result; } } }
// 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.Xml; using System.Collections; namespace System.Data.Common { internal sealed class Int16Storage : DataStorage { private const short defaultValue = 0; private short[] _values; internal Int16Storage(DataColumn column) : base(column, typeof(short), defaultValue, StorageType.Int16) { } public override object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: long sum = defaultValue; foreach (int record in records) { if (HasValue(record)) { checked { sum += _values[record]; } hasData = true; } } if (hasData) { return sum; } return _nullValue; case AggregateType.Mean: long meanSum = defaultValue; int meanCount = 0; foreach (int record in records) { if (HasValue(record)) { checked { meanSum += _values[record]; } meanCount++; hasData = true; } } if (hasData) { short mean; checked { mean = (short)(meanSum / meanCount); } return mean; } return _nullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; double var = 0.0f; double prec = 0.0f; double dsum = 0.0f; double sqrsum = 0.0f; foreach (int record in records) { if (HasValue(record)) { dsum += _values[record]; sqrsum += _values[record] * (double)_values[record]; count++; } } if (count > 1) { var = count * sqrsum - (dsum * dsum); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var < 0)) var = 0; else var = var / (count * (count - 1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var); } return var; } return _nullValue; case AggregateType.Min: short min = short.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { min = Math.Min(_values[record], min); hasData = true; } } if (hasData) { return min; } return _nullValue; case AggregateType.Max: short max = short.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { max = Math.Max(_values[record], max); hasData = true; } } if (hasData) { return max; } return _nullValue; case AggregateType.First: if (records.Length > 0) { return _values[records[0]]; } return null; case AggregateType.Count: count = 0; for (int i = 0; i < records.Length; i++) { if (HasValue(records[i])) { count++; } } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(short)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { short valueNo1 = _values[recordNo1]; short valueNo2 = _values[recordNo2]; if (valueNo1 == defaultValue || valueNo2 == defaultValue) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) { return bitCheck; } } //return valueNo1.CompareTo(valueNo2); return (valueNo1 - valueNo2); // copied from Int16.CompareTo(Int16) } public override int CompareValueTo(int recordNo, object value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { return (HasValue(recordNo) ? 1 : 0); } short valueNo1 = _values[recordNo]; if ((defaultValue == valueNo1) && !HasValue(recordNo)) { return -1; } return valueNo1.CompareTo((short)value); //return(valueNo1 - valueNo2); // copied from Int16.CompareTo(Int16) } public override object ConvertValue(object value) { if (_nullValue != value) { if (null != value) { value = ((IConvertible)value).ToInt16(FormatProvider); } else { value = _nullValue; } } return value; } public override void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { short value = _values[record]; if (value != defaultValue) { return value; } return GetBits(record); } public override void Set(int record, object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { _values[record] = defaultValue; SetNullBit(record, true); } else { _values[record] = ((IConvertible)value).ToInt16(FormatProvider); SetNullBit(record, false); } } public override void SetCapacity(int capacity) { short[] newValues = new short[capacity]; if (null != _values) { Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length)); } _values = newValues; base.SetCapacity(capacity); } public override object ConvertXmlToObject(string s) { return XmlConvert.ToInt16(s); } public override string ConvertObjectToXml(object value) { return XmlConvert.ToString((short)value); } protected override object GetEmptyStorage(int recordCount) { return new short[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { short[] typedStore = (short[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, !HasValue(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (short[])store; SetNullStorage(nullbits); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Threading; using Bmz.Framework.Configuration.Startup; using Bmz.Framework.Dependency; using Bmz.Framework.Extensions; namespace Bmz.Framework.Localization.Dictionaries { /// <summary> /// This class is used to build a localization source /// which works on memory based dictionaries to find strings. /// </summary> public class DictionaryBasedLocalizationSource : IDictionaryBasedLocalizationSource { /// <summary> /// Unique Name of the source. /// </summary> public string Name { get; private set; } public ILocalizationDictionaryProvider DictionaryProvider { get { return _dictionaryProvider; } } protected ILocalizationConfiguration LocalizationConfiguration { get; private set; } private readonly ILocalizationDictionaryProvider _dictionaryProvider; /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="dictionaryProvider"></param> public DictionaryBasedLocalizationSource(string name, ILocalizationDictionaryProvider dictionaryProvider) { if (name.IsNullOrEmpty()) { throw new ArgumentNullException("name"); } Name = name; if (dictionaryProvider == null) { throw new ArgumentNullException("dictionaryProvider"); } _dictionaryProvider = dictionaryProvider; } /// <inheritdoc/> public virtual void Initialize(ILocalizationConfiguration configuration, IIocResolver iocResolver) { LocalizationConfiguration = configuration; DictionaryProvider.Initialize(Name); } /// <inheritdoc/> public string GetString(string name) { return GetString(name, Thread.CurrentThread.CurrentUICulture); } /// <inheritdoc/> public string GetString(string name, CultureInfo culture) { var value = GetStringOrNull(name, culture); if (value == null) { return ReturnGivenNameOrThrowException(name); } return value; } public string GetStringOrNull(string name, bool tryDefaults = true) { return GetStringOrNull(name, Thread.CurrentThread.CurrentUICulture, tryDefaults); } public string GetStringOrNull(string name, CultureInfo culture, bool tryDefaults = true) { var cultureName = culture.Name; var dictionaries = DictionaryProvider.Dictionaries; //Try to get from original dictionary (with country code) ILocalizationDictionary originalDictionary; if (dictionaries.TryGetValue(cultureName, out originalDictionary)) { var strOriginal = originalDictionary.GetOrNull(name); if (strOriginal != null) { return strOriginal.Value; } } if (!tryDefaults) { return null; } //Try to get from same language dictionary (without country code) if (cultureName.Contains("-")) //Example: "tr-TR" (length=5) { ILocalizationDictionary langDictionary; if (dictionaries.TryGetValue(GetBaseCultureName(cultureName), out langDictionary)) { var strLang = langDictionary.GetOrNull(name); if (strLang != null) { return strLang.Value; } } } //Try to get from default language var defaultDictionary = DictionaryProvider.DefaultDictionary; if (defaultDictionary == null) { return null; } var strDefault = defaultDictionary.GetOrNull(name); if (strDefault == null) { return null; } return strDefault.Value; } /// <inheritdoc/> public IReadOnlyList<LocalizedString> GetAllStrings(bool includeDefaults = true) { return GetAllStrings(Thread.CurrentThread.CurrentUICulture, includeDefaults); } /// <inheritdoc/> public IReadOnlyList<LocalizedString> GetAllStrings(CultureInfo culture, bool includeDefaults = true) { //TODO: Can be optimized (example: if it's already default dictionary, skip overriding) var dictionaries = DictionaryProvider.Dictionaries; //Create a temp dictionary to build var allStrings = new Dictionary<string, LocalizedString>(); if (includeDefaults) { //Fill all strings from default dictionary var defaultDictionary = DictionaryProvider.DefaultDictionary; if (defaultDictionary != null) { foreach (var defaultDictString in defaultDictionary.GetAllStrings()) { allStrings[defaultDictString.Name] = defaultDictString; } } //Overwrite all strings from the language based on country culture if (culture.Name.Contains("-")) { ILocalizationDictionary langDictionary; if (dictionaries.TryGetValue(GetBaseCultureName(culture.Name), out langDictionary)) { foreach (var langString in langDictionary.GetAllStrings()) { allStrings[langString.Name] = langString; } } } } //Overwrite all strings from the original dictionary ILocalizationDictionary originalDictionary; if (dictionaries.TryGetValue(culture.Name, out originalDictionary)) { foreach (var originalLangString in originalDictionary.GetAllStrings()) { allStrings[originalLangString.Name] = originalLangString; } } return allStrings.Values.ToImmutableList(); } /// <summary> /// Extends the source with given dictionary. /// </summary> /// <param name="dictionary">Dictionary to extend the source</param> public virtual void Extend(ILocalizationDictionary dictionary) { DictionaryProvider.Extend(dictionary); } protected virtual string ReturnGivenNameOrThrowException(string name) { return LocalizationSourceHelper.ReturnGivenNameOrThrowException(LocalizationConfiguration, Name, name); } private static string GetBaseCultureName(string cultureName) { return cultureName.Contains("-") ? cultureName.Left(cultureName.IndexOf("-", StringComparison.InvariantCulture)) : cultureName; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class InventoryServicesConnector : ISessionAuthInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; private Dictionary<UUID, InventoryReceiptCallback> m_RequestingInventory = new Dictionary<UUID, InventoryReceiptCallback>(); private Dictionary<UUID, DateTime> m_RequestTime = new Dictionary<UUID, DateTime>(); public InventoryServicesConnector() { } public InventoryServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public InventoryServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig inventoryConfig = source.Configs["InventoryService"]; if (inventoryConfig == null) { m_log.Error("[INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini"); throw new Exception("InventoryService missing from OpenSim.ini"); } string serviceURI = inventoryConfig.GetString("InventoryServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[INVENTORY CONNECTOR]: No Server URI named in section InventoryService"); throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); } m_ServerURI = serviceURI.TrimEnd('/'); } #region ISessionAuthInventoryService public string Host { get { return m_ServerURI; } } /// <summary> /// Caller must catch eventual Exceptions. /// </summary> /// <param name="userID"></param> /// <param name="sessionID"></param> /// <param name="callback"></param> public void GetUserInventory(string userIDStr, UUID sessionID, InventoryReceiptCallback callback) { UUID userID = UUID.Zero; if (UUID.TryParse(userIDStr, out userID)) { lock (m_RequestingInventory) { // *HACK ALERT* // If an inventory request times out, it blocks any further requests from the // same user, even after a relog. This is bad, and makes me sad. // Really, we should detect a timeout and report a failure to the callback, // BUT in my testing i found that it's hard to detect a timeout.. sometimes, // a partial response is recieved, and sometimes a null response. // So, for now, add a timer of ten seconds (which is the request timeout). // This should basically have the same effect. lock (m_RequestTime) { if (m_RequestTime.ContainsKey(userID)) { TimeSpan interval = DateTime.Now - m_RequestTime[userID]; if (interval.TotalSeconds > 10) { m_RequestTime.Remove(userID); if (m_RequestingInventory.ContainsKey(userID)) { m_RequestingInventory.Remove(userID); } } } if (!m_RequestingInventory.ContainsKey(userID)) { m_RequestTime.Add(userID, DateTime.Now); m_RequestingInventory.Add(userID, callback); } else { m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetUserInventory - ignoring repeated request for user {0}", userID); return; } } } m_log.InfoFormat( "[INVENTORY CONNECTOR]: Requesting inventory from {0}/GetInventory/ for user {1}", m_ServerURI, userID); RestSessionObjectPosterResponse<Guid, InventoryCollection> requester = new RestSessionObjectPosterResponse<Guid, InventoryCollection>(); requester.ResponseCallback = InventoryResponse; requester.BeginPostObject(m_ServerURI + "/GetInventory/", userID.Guid, sessionID.ToString(), userID.ToString()); } } /// <summary> /// Gets the user folder for the given folder-type /// </summary> /// <param name="userID"></param> /// <param name="type"></param> /// <returns></returns> public Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(string userID, UUID sessionID) { List<InventoryFolderBase> folders = null; Dictionary<AssetType, InventoryFolderBase> dFolders = new Dictionary<AssetType, InventoryFolderBase>(); try { folders = SynchronousRestSessionObjectPoster<Guid, List<InventoryFolderBase>>.BeginPostObject( "POST", m_ServerURI + "/SystemFolders/", new Guid(userID), sessionID.ToString(), userID.ToString()); foreach (InventoryFolderBase f in folders) dFolders[(AssetType)f.Type] = f; return dFolders; } catch (Exception e) { // Maybe we're talking to an old inventory server. Try this other thing. m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetSystemFolders operation failed, {0} {1} (old sever?). Trying GetInventory.", e.Source, e.Message); try { InventoryCollection inventory = SynchronousRestSessionObjectPoster<Guid, InventoryCollection>.BeginPostObject( "POST", m_ServerURI + "/GetInventory/", new Guid(userID), sessionID.ToString(), userID.ToString()); folders = inventory.Folders; } catch (Exception ex) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetInventory operation also failed, {0} {1}. Giving up.", e.Source, ex.Message); } if ((folders != null) && (folders.Count > 0)) { m_log.DebugFormat("[INVENTORY CONNECTOR]: Received entire inventory ({0} folders) for user {1}", folders.Count, userID); foreach (InventoryFolderBase f in folders) { if ((f.Type != (short)AssetType.Folder) && (f.Type != (short)AssetType.Unknown)) dFolders[(AssetType)f.Type] = f; } UUID rootFolderID = dFolders[AssetType.Animation].ParentID; InventoryFolderBase rootFolder = new InventoryFolderBase(rootFolderID, new UUID(userID)); rootFolder = QueryFolder(userID, rootFolder, sessionID); dFolders[AssetType.Folder] = rootFolder; m_log.DebugFormat("[INVENTORY CONNECTOR]: {0} system folders for user {1}", dFolders.Count, userID); return dFolders; } } return new Dictionary<AssetType, InventoryFolderBase>(); } /// <summary> /// Gets everything (folders and items) inside a folder /// </summary> /// <param name="userId"></param> /// <param name="folderID"></param> /// <returns></returns> public InventoryCollection GetFolderContent(string userID, UUID folderID, UUID sessionID) { try { // normal case return SynchronousRestSessionObjectPoster<Guid, InventoryCollection>.BeginPostObject( "POST", m_ServerURI + "/GetFolderContent/", folderID.Guid, sessionID.ToString(), userID.ToString()); } catch (TimeoutException e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetFolderContent operation to {0} timed out {0} {1}.", m_ServerURI, e.Source, e.Message); } catch (Exception e) { // Maybe we're talking to an old inventory server. Try this other thing. m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetFolderContent operation failed, {0} {1} (old server?). Trying GetInventory.", e.Source, e.Message); InventoryCollection inventory; List<InventoryFolderBase> folders = null; try { inventory = SynchronousRestSessionObjectPoster<Guid, InventoryCollection>.BeginPostObject( "POST", m_ServerURI + "/GetInventory/", new Guid(userID), sessionID.ToString(), userID.ToString()); if (inventory != null) folders = inventory.Folders; } catch (Exception ex) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetInventory operation also failed, {0} {1}. Giving up.", e.Source, ex.Message); return new InventoryCollection(); } if ((folders != null) && (folders.Count > 0)) { m_log.DebugFormat("[INVENTORY CONNECTOR]: Received entire inventory ({0} folders) for user {1}", folders.Count, userID); folders = folders.FindAll(delegate(InventoryFolderBase f) { return f.ParentID == folderID; }); List<InventoryItemBase> items = inventory.Items; if (items != null) { items = items.FindAll(delegate(InventoryItemBase i) { return i.Folder == folderID; }); } inventory.Items = items; inventory.Folders = folders; return inventory; } } InventoryCollection nullCollection = new InventoryCollection(); nullCollection.Folders = new List<InventoryFolderBase>(); nullCollection.Items = new List<InventoryItemBase>(); nullCollection.UserID = new UUID(userID); return nullCollection; } public bool AddFolder(string userID, InventoryFolderBase folder, UUID sessionID) { try { return SynchronousRestSessionObjectPoster<InventoryFolderBase, bool>.BeginPostObject( "POST", m_ServerURI + "/NewFolder/", folder, sessionID.ToString(), folder.Owner.ToString()); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Add new inventory folder operation failed, {0} {1}", e.Source, e.Message); } return false; } public bool UpdateFolder(string userID, InventoryFolderBase folder, UUID sessionID) { try { return SynchronousRestSessionObjectPoster<InventoryFolderBase, bool>.BeginPostObject( "POST", m_ServerURI + "/UpdateFolder/", folder, sessionID.ToString(), folder.Owner.ToString()); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Update inventory folder operation failed, {0} {1}", e.Source, e.Message); } return false; } public bool DeleteFolders(string userID, List<UUID> folderIDs, UUID sessionID) { try { List<Guid> guids = new List<Guid>(); foreach (UUID u in folderIDs) guids.Add(u.Guid); return SynchronousRestSessionObjectPoster<List<Guid>, bool>.BeginPostObject( "POST", m_ServerURI + "/DeleteFolders/", guids, sessionID.ToString(), userID); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Delete inventory folders operation failed, {0} {1}", e.Source, e.Message); } return false; } public bool MoveFolder(string userID, InventoryFolderBase folder, UUID sessionID) { try { return SynchronousRestSessionObjectPoster<InventoryFolderBase, bool>.BeginPostObject( "POST", m_ServerURI + "/MoveFolder/", folder, sessionID.ToString(), folder.Owner.ToString()); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Move inventory folder operation failed, {0} {1}", e.Source, e.Message); } return false; } public bool PurgeFolder(string userID, InventoryFolderBase folder, UUID sessionID) { try { return SynchronousRestSessionObjectPoster<InventoryFolderBase, bool>.BeginPostObject( "POST", m_ServerURI + "/PurgeFolder/", folder, sessionID.ToString(), folder.Owner.ToString()); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Move inventory folder operation failed, {0} {1}", e.Source, e.Message); } return false; } public List<InventoryItemBase> GetFolderItems(string userID, UUID folderID, UUID sessionID) { try { InventoryFolderBase folder = new InventoryFolderBase(folderID, new UUID(userID)); return SynchronousRestSessionObjectPoster<InventoryFolderBase, List<InventoryItemBase>>.BeginPostObject( "POST", m_ServerURI + "/GetItems/", folder, sessionID.ToString(), userID); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Get folder items operation failed, {0} {1}", e.Source, e.Message); } return null; } public bool AddItem(string userID, InventoryItemBase item, UUID sessionID) { try { return SynchronousRestSessionObjectPoster<InventoryItemBase, bool>.BeginPostObject( "POST", m_ServerURI + "/NewItem/", item, sessionID.ToString(), item.Owner.ToString()); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Add new inventory item operation failed, {0} {1}", e.Source, e.Message); } return false; } public bool UpdateItem(string userID, InventoryItemBase item, UUID sessionID) { try { return SynchronousRestSessionObjectPoster<InventoryItemBase, bool>.BeginPostObject( "POST", m_ServerURI + "/NewItem/", item, sessionID.ToString(), item.Owner.ToString()); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Update new inventory item operation failed, {0} {1}", e.Source, e.Message); } return false; } /** * MoveItems Async group */ delegate void MoveItemsDelegate(string userID, List<InventoryItemBase> items, UUID sessionID); private void MoveItemsAsync(string userID, List<InventoryItemBase> items, UUID sessionID) { if (items == null) { m_log.WarnFormat("[INVENTORY CONNECTOR]: request to move items got a null list."); return; } try { //SynchronousRestSessionObjectPoster<List<InventoryItemBase>, bool>.BeginPostObject( // "POST", m_ServerURI + "/MoveItems/", items, sessionID.ToString(), userID.ToString()); //// Success //return; string uri = m_ServerURI + "/inventory/" + userID; if (SynchronousRestObjectRequester. MakeRequest<List<InventoryItemBase>, bool>("PUT", uri, items)) m_log.DebugFormat("[INVENTORY CONNECTOR]: move {0} items poster succeeded {1}", items.Count, uri); else m_log.DebugFormat("[INVENTORY CONNECTOR]: move {0} items poster failed {1}", items.Count, uri); ; return; } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Move inventory items operation failed, {0} {1} (old server?). Trying slow way.", e.Source, e.Message); } foreach (InventoryItemBase item in items) { InventoryItemBase itm = this.QueryItem(userID, item, sessionID); itm.Name = item.Name; itm.Folder = item.Folder; this.UpdateItem(userID, itm, sessionID); } } private void MoveItemsCompleted(IAsyncResult iar) { } public bool MoveItems(string userID, List<InventoryItemBase> items, UUID sessionID) { MoveItemsDelegate d = MoveItemsAsync; d.BeginInvoke(userID, items, sessionID, MoveItemsCompleted, d); return true; } public bool DeleteItems(string userID, List<UUID> items, UUID sessionID) { try { List<Guid> guids = new List<Guid>(); foreach (UUID u in items) guids.Add(u.Guid); return SynchronousRestSessionObjectPoster<List<Guid>, bool>.BeginPostObject( "POST", m_ServerURI + "/DeleteItem/", guids, sessionID.ToString(), userID); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Delete inventory item operation failed, {0} {1}", e.Source, e.Message); } return false; } public InventoryItemBase QueryItem(string userID, InventoryItemBase item, UUID sessionID) { try { return SynchronousRestSessionObjectPoster<InventoryItemBase, InventoryItemBase>.BeginPostObject( "POST", m_ServerURI + "/QueryItem/", item, sessionID.ToString(), item.Owner.ToString()); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Query inventory item operation failed, {0} {1}", e.Source, e.Message); } return null; } public InventoryFolderBase QueryFolder(string userID, InventoryFolderBase folder, UUID sessionID) { try { return SynchronousRestSessionObjectPoster<InventoryFolderBase, InventoryFolderBase>.BeginPostObject( "POST", m_ServerURI + "/QueryFolder/", folder, sessionID.ToString(), userID); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Query inventory item operation failed, {0} {1}", e.Source, e.Message); } return null; } public int GetAssetPermissions(string userID, UUID assetID, UUID sessionID) { try { InventoryItemBase item = new InventoryItemBase(); item.Owner = new UUID(userID); item.AssetID = assetID; return SynchronousRestSessionObjectPoster<InventoryItemBase, int>.BeginPostObject( "POST", m_ServerURI + "/AssetPermissions/", item, sessionID.ToString(), userID); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY CONNECTOR]: AssetPermissions operation failed, {0} {1}", e.Source, e.Message); } return 0; } #endregion /// <summary> /// Callback used by the inventory server GetInventory request /// </summary> /// <param name="userID"></param> private void InventoryResponse(InventoryCollection response) { UUID userID = response.UserID; InventoryReceiptCallback callback = null; lock (m_RequestingInventory) { if (m_RequestingInventory.ContainsKey(userID)) { callback = m_RequestingInventory[userID]; m_RequestingInventory.Remove(userID); lock (m_RequestTime) { if (m_RequestTime.ContainsKey(userID)) { m_RequestTime.Remove(userID); } } } else { m_log.WarnFormat( "[INVENTORY CONNECTOR]: " + "Received inventory response for {0} for which we do not have a record of requesting!", userID); return; } } m_log.InfoFormat("[INVENTORY CONNECTOR]: " + "Received inventory response for user {0} containing {1} folders and {2} items", userID, response.Folders.Count, response.Items.Count); InventoryFolderImpl rootFolder = null; ICollection<InventoryFolderImpl> folders = new List<InventoryFolderImpl>(); ICollection<InventoryItemBase> items = new List<InventoryItemBase>(); foreach (InventoryFolderBase folder in response.Folders) { if (folder.ParentID == UUID.Zero) { rootFolder = new InventoryFolderImpl(folder); folders.Add(rootFolder); break; } } if (rootFolder != null) { foreach (InventoryFolderBase folder in response.Folders) { if (folder.ID != rootFolder.ID) { folders.Add(new InventoryFolderImpl(folder)); } } foreach (InventoryItemBase item in response.Items) { items.Add(item); } } else { m_log.ErrorFormat("[INVENTORY CONNECTOR]: Did not get back an inventory containing a root folder for user {0}", userID); } callback(folders, items); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the SysMedicamento class. /// </summary> [Serializable] public partial class SysMedicamentoCollection : ActiveList<SysMedicamento, SysMedicamentoCollection> { public SysMedicamentoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysMedicamentoCollection</returns> public SysMedicamentoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysMedicamento o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_Medicamento table. /// </summary> [Serializable] public partial class SysMedicamento : ActiveRecord<SysMedicamento>, IActiveRecord { #region .ctors and Default Settings public SysMedicamento() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysMedicamento(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysMedicamento(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysMedicamento(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_Medicamento", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdMedicamento = new TableSchema.TableColumn(schema); colvarIdMedicamento.ColumnName = "idMedicamento"; colvarIdMedicamento.DataType = DbType.Int32; colvarIdMedicamento.MaxLength = 0; colvarIdMedicamento.AutoIncrement = true; colvarIdMedicamento.IsNullable = false; colvarIdMedicamento.IsPrimaryKey = true; colvarIdMedicamento.IsForeignKey = false; colvarIdMedicamento.IsReadOnly = false; colvarIdMedicamento.DefaultSetting = @""; colvarIdMedicamento.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMedicamento); TableSchema.TableColumn colvarIdMedicamentoRubro = new TableSchema.TableColumn(schema); colvarIdMedicamentoRubro.ColumnName = "idMedicamentoRubro"; colvarIdMedicamentoRubro.DataType = DbType.Int32; colvarIdMedicamentoRubro.MaxLength = 0; colvarIdMedicamentoRubro.AutoIncrement = false; colvarIdMedicamentoRubro.IsNullable = true; colvarIdMedicamentoRubro.IsPrimaryKey = false; colvarIdMedicamentoRubro.IsForeignKey = true; colvarIdMedicamentoRubro.IsReadOnly = false; colvarIdMedicamentoRubro.DefaultSetting = @""; colvarIdMedicamentoRubro.ForeignKeyTableName = "Sys_MedicamentoRubro"; schema.Columns.Add(colvarIdMedicamentoRubro); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 255; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarUnidad = new TableSchema.TableColumn(schema); colvarUnidad.ColumnName = "unidad"; colvarUnidad.DataType = DbType.String; colvarUnidad.MaxLength = 255; colvarUnidad.AutoIncrement = false; colvarUnidad.IsNullable = true; colvarUnidad.IsPrimaryKey = false; colvarUnidad.IsForeignKey = false; colvarUnidad.IsReadOnly = false; colvarUnidad.DefaultSetting = @""; colvarUnidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnidad); TableSchema.TableColumn colvarNecesitaVencimiento = new TableSchema.TableColumn(schema); colvarNecesitaVencimiento.ColumnName = "necesitaVencimiento"; colvarNecesitaVencimiento.DataType = DbType.Boolean; colvarNecesitaVencimiento.MaxLength = 0; colvarNecesitaVencimiento.AutoIncrement = false; colvarNecesitaVencimiento.IsNullable = true; colvarNecesitaVencimiento.IsPrimaryKey = false; colvarNecesitaVencimiento.IsForeignKey = false; colvarNecesitaVencimiento.IsReadOnly = false; colvarNecesitaVencimiento.DefaultSetting = @""; colvarNecesitaVencimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarNecesitaVencimiento); TableSchema.TableColumn colvarActivo = new TableSchema.TableColumn(schema); colvarActivo.ColumnName = "activo"; colvarActivo.DataType = DbType.Boolean; colvarActivo.MaxLength = 0; colvarActivo.AutoIncrement = false; colvarActivo.IsNullable = true; colvarActivo.IsPrimaryKey = false; colvarActivo.IsForeignKey = false; colvarActivo.IsReadOnly = false; colvarActivo.DefaultSetting = @""; colvarActivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarActivo); TableSchema.TableColumn colvarUltimaModificacion = new TableSchema.TableColumn(schema); colvarUltimaModificacion.ColumnName = "ultimaModificacion"; colvarUltimaModificacion.DataType = DbType.DateTime; colvarUltimaModificacion.MaxLength = 0; colvarUltimaModificacion.AutoIncrement = false; colvarUltimaModificacion.IsNullable = true; colvarUltimaModificacion.IsPrimaryKey = false; colvarUltimaModificacion.IsForeignKey = false; colvarUltimaModificacion.IsReadOnly = false; colvarUltimaModificacion.DefaultSetting = @""; colvarUltimaModificacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarUltimaModificacion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_Medicamento",schema); } } #endregion #region Props [XmlAttribute("IdMedicamento")] [Bindable(true)] public int IdMedicamento { get { return GetColumnValue<int>(Columns.IdMedicamento); } set { SetColumnValue(Columns.IdMedicamento, value); } } [XmlAttribute("IdMedicamentoRubro")] [Bindable(true)] public int? IdMedicamentoRubro { get { return GetColumnValue<int?>(Columns.IdMedicamentoRubro); } set { SetColumnValue(Columns.IdMedicamentoRubro, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("Unidad")] [Bindable(true)] public string Unidad { get { return GetColumnValue<string>(Columns.Unidad); } set { SetColumnValue(Columns.Unidad, value); } } [XmlAttribute("NecesitaVencimiento")] [Bindable(true)] public bool? NecesitaVencimiento { get { return GetColumnValue<bool?>(Columns.NecesitaVencimiento); } set { SetColumnValue(Columns.NecesitaVencimiento, value); } } [XmlAttribute("Activo")] [Bindable(true)] public bool? Activo { get { return GetColumnValue<bool?>(Columns.Activo); } set { SetColumnValue(Columns.Activo, value); } } [XmlAttribute("UltimaModificacion")] [Bindable(true)] public DateTime? UltimaModificacion { get { return GetColumnValue<DateTime?>(Columns.UltimaModificacion); } set { SetColumnValue(Columns.UltimaModificacion, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.AprAplicacionVacunaCollection colAprAplicacionVacunaRecords; public DalSic.AprAplicacionVacunaCollection AprAplicacionVacunaRecords { get { if(colAprAplicacionVacunaRecords == null) { colAprAplicacionVacunaRecords = new DalSic.AprAplicacionVacunaCollection().Where(AprAplicacionVacuna.Columns.IdVacuna, IdMedicamento).Load(); colAprAplicacionVacunaRecords.ListChanged += new ListChangedEventHandler(colAprAplicacionVacunaRecords_ListChanged); } return colAprAplicacionVacunaRecords; } set { colAprAplicacionVacunaRecords = value; colAprAplicacionVacunaRecords.ListChanged += new ListChangedEventHandler(colAprAplicacionVacunaRecords_ListChanged); } } void colAprAplicacionVacunaRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprAplicacionVacunaRecords[e.NewIndex].IdVacuna = IdMedicamento; } } private DalSic.AprCalendarioVacunaCollection colAprCalendarioVacunaRecords; public DalSic.AprCalendarioVacunaCollection AprCalendarioVacunaRecords { get { if(colAprCalendarioVacunaRecords == null) { colAprCalendarioVacunaRecords = new DalSic.AprCalendarioVacunaCollection().Where(AprCalendarioVacuna.Columns.IdVacuna, IdMedicamento).Load(); colAprCalendarioVacunaRecords.ListChanged += new ListChangedEventHandler(colAprCalendarioVacunaRecords_ListChanged); } return colAprCalendarioVacunaRecords; } set { colAprCalendarioVacunaRecords = value; colAprCalendarioVacunaRecords.ListChanged += new ListChangedEventHandler(colAprCalendarioVacunaRecords_ListChanged); } } void colAprCalendarioVacunaRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprCalendarioVacunaRecords[e.NewIndex].IdVacuna = IdMedicamento; } } private DalSic.RemRelMedicamentoSeguimientoCollection colRemRelMedicamentoSeguimientoRecords; public DalSic.RemRelMedicamentoSeguimientoCollection RemRelMedicamentoSeguimientoRecords { get { if(colRemRelMedicamentoSeguimientoRecords == null) { colRemRelMedicamentoSeguimientoRecords = new DalSic.RemRelMedicamentoSeguimientoCollection().Where(RemRelMedicamentoSeguimiento.Columns.IdMedicamento, IdMedicamento).Load(); colRemRelMedicamentoSeguimientoRecords.ListChanged += new ListChangedEventHandler(colRemRelMedicamentoSeguimientoRecords_ListChanged); } return colRemRelMedicamentoSeguimientoRecords; } set { colRemRelMedicamentoSeguimientoRecords = value; colRemRelMedicamentoSeguimientoRecords.ListChanged += new ListChangedEventHandler(colRemRelMedicamentoSeguimientoRecords_ListChanged); } } void colRemRelMedicamentoSeguimientoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colRemRelMedicamentoSeguimientoRecords[e.NewIndex].IdMedicamento = IdMedicamento; } } private DalSic.RemRelMedicamentoClasificacionCollection colRemRelMedicamentoClasificacionRecords; public DalSic.RemRelMedicamentoClasificacionCollection RemRelMedicamentoClasificacionRecords { get { if(colRemRelMedicamentoClasificacionRecords == null) { colRemRelMedicamentoClasificacionRecords = new DalSic.RemRelMedicamentoClasificacionCollection().Where(RemRelMedicamentoClasificacion.Columns.IdMedicamento, IdMedicamento).Load(); colRemRelMedicamentoClasificacionRecords.ListChanged += new ListChangedEventHandler(colRemRelMedicamentoClasificacionRecords_ListChanged); } return colRemRelMedicamentoClasificacionRecords; } set { colRemRelMedicamentoClasificacionRecords = value; colRemRelMedicamentoClasificacionRecords.ListChanged += new ListChangedEventHandler(colRemRelMedicamentoClasificacionRecords_ListChanged); } } void colRemRelMedicamentoClasificacionRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colRemRelMedicamentoClasificacionRecords[e.NewIndex].IdMedicamento = IdMedicamento; } } private DalSic.RemMedicamentoCronicoCollection colRemMedicamentoCronicoRecords; public DalSic.RemMedicamentoCronicoCollection RemMedicamentoCronicoRecords { get { if(colRemMedicamentoCronicoRecords == null) { colRemMedicamentoCronicoRecords = new DalSic.RemMedicamentoCronicoCollection().Where(RemMedicamentoCronico.Columns.IdMedicamento, IdMedicamento).Load(); colRemMedicamentoCronicoRecords.ListChanged += new ListChangedEventHandler(colRemMedicamentoCronicoRecords_ListChanged); } return colRemMedicamentoCronicoRecords; } set { colRemMedicamentoCronicoRecords = value; colRemMedicamentoCronicoRecords.ListChanged += new ListChangedEventHandler(colRemMedicamentoCronicoRecords_ListChanged); } } void colRemMedicamentoCronicoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colRemMedicamentoCronicoRecords[e.NewIndex].IdMedicamento = IdMedicamento; } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysMedicamentoRubro ActiveRecord object related to this SysMedicamento /// /// </summary> public DalSic.SysMedicamentoRubro SysMedicamentoRubro { get { return DalSic.SysMedicamentoRubro.FetchByID(this.IdMedicamentoRubro); } set { SetColumnValue("idMedicamentoRubro", value.IdMedicamentoRubro); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int? varIdMedicamentoRubro,string varNombre,string varUnidad,bool? varNecesitaVencimiento,bool? varActivo,DateTime? varUltimaModificacion) { SysMedicamento item = new SysMedicamento(); item.IdMedicamentoRubro = varIdMedicamentoRubro; item.Nombre = varNombre; item.Unidad = varUnidad; item.NecesitaVencimiento = varNecesitaVencimiento; item.Activo = varActivo; item.UltimaModificacion = varUltimaModificacion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdMedicamento,int? varIdMedicamentoRubro,string varNombre,string varUnidad,bool? varNecesitaVencimiento,bool? varActivo,DateTime? varUltimaModificacion) { SysMedicamento item = new SysMedicamento(); item.IdMedicamento = varIdMedicamento; item.IdMedicamentoRubro = varIdMedicamentoRubro; item.Nombre = varNombre; item.Unidad = varUnidad; item.NecesitaVencimiento = varNecesitaVencimiento; item.Activo = varActivo; item.UltimaModificacion = varUltimaModificacion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdMedicamentoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdMedicamentoRubroColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn UnidadColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn NecesitaVencimientoColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn ActivoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn UltimaModificacionColumn { get { return Schema.Columns[6]; } } #endregion #region Columns Struct public struct Columns { public static string IdMedicamento = @"idMedicamento"; public static string IdMedicamentoRubro = @"idMedicamentoRubro"; public static string Nombre = @"nombre"; public static string Unidad = @"unidad"; public static string NecesitaVencimiento = @"necesitaVencimiento"; public static string Activo = @"activo"; public static string UltimaModificacion = @"ultimaModificacion"; } #endregion #region Update PK Collections public void SetPKValues() { if (colAprAplicacionVacunaRecords != null) { foreach (DalSic.AprAplicacionVacuna item in colAprAplicacionVacunaRecords) { if (item.IdVacuna != IdMedicamento) { item.IdVacuna = IdMedicamento; } } } if (colAprCalendarioVacunaRecords != null) { foreach (DalSic.AprCalendarioVacuna item in colAprCalendarioVacunaRecords) { if (item.IdVacuna != IdMedicamento) { item.IdVacuna = IdMedicamento; } } } if (colRemRelMedicamentoSeguimientoRecords != null) { foreach (DalSic.RemRelMedicamentoSeguimiento item in colRemRelMedicamentoSeguimientoRecords) { if (item.IdMedicamento != IdMedicamento) { item.IdMedicamento = IdMedicamento; } } } if (colRemRelMedicamentoClasificacionRecords != null) { foreach (DalSic.RemRelMedicamentoClasificacion item in colRemRelMedicamentoClasificacionRecords) { if (item.IdMedicamento != IdMedicamento) { item.IdMedicamento = IdMedicamento; } } } if (colRemMedicamentoCronicoRecords != null) { foreach (DalSic.RemMedicamentoCronico item in colRemMedicamentoCronicoRecords) { if (item.IdMedicamento != IdMedicamento) { item.IdMedicamento = IdMedicamento; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colAprAplicacionVacunaRecords != null) { colAprAplicacionVacunaRecords.SaveAll(); } if (colAprCalendarioVacunaRecords != null) { colAprCalendarioVacunaRecords.SaveAll(); } if (colRemRelMedicamentoSeguimientoRecords != null) { colRemRelMedicamentoSeguimientoRecords.SaveAll(); } if (colRemRelMedicamentoClasificacionRecords != null) { colRemRelMedicamentoClasificacionRecords.SaveAll(); } if (colRemMedicamentoCronicoRecords != null) { colRemMedicamentoCronicoRecords.SaveAll(); } } #endregion } }
#region MIT license // // MIT license // // Copyright (c) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #endregion using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.Linq; using System.Linq; namespace DbLinq.Null { [System.ComponentModel.DesignerCategory("Code")] class NullConnection : DbConnection { public NullConnection () { ConnectionString = ""; } public override string ConnectionString {get; set;} public override string Database {get {return "NullDatabase";}} public override string DataSource {get {return "NullDataSource";}} public override string ServerVersion {get {return "0.0";}} public override ConnectionState State {get {return ConnectionState.Closed;}} public override void ChangeDatabase (string databaseName) { throw new NotSupportedException (); } public override void Close () { } public override void Open () { } protected override DbTransaction BeginDbTransaction (IsolationLevel level) { throw new NotSupportedException (); } protected override DbCommand CreateDbCommand () { return new NullCommand (); } } class NullParameter : DbParameter { public override DbType DbType {get; set;} public override ParameterDirection Direction {get; set;} public override bool IsNullable {get; set;} public override string ParameterName {get; set;} public override int Size {get; set;} public override string SourceColumn {get; set;} public override bool SourceColumnNullMapping {get; set;} public override DataRowVersion SourceVersion {get; set;} public override object Value {get; set;} public override void ResetDbType () { throw new NotSupportedException (); } } class DbParameterCollection<TParameter> : DbParameterCollection where TParameter : DbParameter { List<TParameter> parameters = new List<TParameter> (); public DbParameterCollection () { } public override int Count {get {return parameters.Count;}} public override bool IsFixedSize {get {return false;}} public override bool IsReadOnly {get {return false;}} public override bool IsSynchronized {get {return false;}} public override object SyncRoot {get {return parameters;}} public override int Add (object value) { if (!(value is TParameter)) throw new ArgumentException ("wrong type", "value"); parameters.Add ((TParameter) value); return parameters.Count-1; } public override void AddRange (Array values) { foreach (TParameter p in values) Add (p); } public override void Clear () { parameters.Clear (); } public override bool Contains (object value) { return parameters.Contains ((TParameter) value); } public override bool Contains (string value) { return parameters.Any (p => p.ParameterName == value); } public override void CopyTo (Array array, int index) { ((ICollection) parameters).CopyTo (array, index); } public override IEnumerator GetEnumerator () { return parameters.GetEnumerator (); } public override int IndexOf (object value) { return parameters.IndexOf ((TParameter) value); } public override int IndexOf (string value) { for (int i = 0; i < parameters.Count; ++i) if (parameters [i].ParameterName == value) return i; return -1; } public override void Insert (int index, object value) { parameters.Insert (index, (TParameter) value); } public override void Remove (object value) { parameters.Remove ((TParameter) value); } public override void RemoveAt (int index) { parameters.RemoveAt (index); } public override void RemoveAt (string value) { int idx = IndexOf (value); if (idx >= 0) parameters.RemoveAt (idx); } protected override DbParameter GetParameter (int index) { return parameters [index]; } protected override DbParameter GetParameter (string value) { return parameters.Where (p => p.ParameterName == value) .FirstOrDefault (); } protected override void SetParameter (int index, DbParameter value) { parameters [index] = (TParameter) value; } protected override void SetParameter (string index, DbParameter value) { parameters [IndexOf (value)] = (TParameter) value; } } class NullCommand : DbCommand { DbParameterCollection<NullParameter> parameters = new DbParameterCollection<NullParameter> (); public NullCommand () { } public override string CommandText { get; set; } public override int CommandTimeout { get; set; } public override CommandType CommandType { get; set; } public override bool DesignTimeVisible { get; set; } public override UpdateRowSource UpdatedRowSource { get; set; } protected override DbConnection DbConnection { get; set; } protected override DbParameterCollection DbParameterCollection {get {return parameters;}} protected override DbTransaction DbTransaction { get; set; } public override void Cancel () { } public override int ExecuteNonQuery () { throw new NotSupportedException (); } public override object ExecuteScalar () { throw new NotSupportedException (); } public override void Prepare () { } protected override DbParameter CreateDbParameter () { return new NullParameter (); } protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior) { throw new NotSupportedException (); } } class NullDataReader : DbDataReader { public override void Close() { throw new NotImplementedException(); } public override int Depth { get { throw new NotImplementedException(); } } public override int FieldCount { get { throw new NotImplementedException(); } } public override bool GetBoolean(int ordinal) { throw new NotImplementedException(); } public override byte GetByte(int ordinal) { throw new NotImplementedException(); } public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) { throw new NotImplementedException(); } public override char GetChar(int ordinal) { throw new NotImplementedException(); } public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) { throw new NotImplementedException(); } public override string GetDataTypeName(int ordinal) { throw new NotImplementedException(); } public override DateTime GetDateTime(int ordinal) { throw new NotImplementedException(); } public override decimal GetDecimal(int ordinal) { throw new NotImplementedException(); } public override double GetDouble(int ordinal) { throw new NotImplementedException(); } public override IEnumerator GetEnumerator() { throw new NotImplementedException(); } public override Type GetFieldType(int ordinal) { throw new NotImplementedException(); } public override float GetFloat(int ordinal) { throw new NotImplementedException(); } public override Guid GetGuid(int ordinal) { throw new NotImplementedException(); } public override short GetInt16(int ordinal) { throw new NotImplementedException(); } public override int GetInt32(int ordinal) { throw new NotImplementedException(); } public override long GetInt64(int ordinal) { throw new NotImplementedException(); } public override string GetName(int ordinal) { throw new NotImplementedException(); } public override int GetOrdinal(string name) { throw new NotImplementedException(); } public override DataTable GetSchemaTable() { throw new NotImplementedException(); } public override string GetString(int ordinal) { throw new NotImplementedException(); } public override object GetValue(int ordinal) { throw new NotImplementedException(); } public override int GetValues(object[] values) { throw new NotImplementedException(); } public override bool HasRows { get { throw new NotImplementedException(); } } public override bool IsClosed { get { throw new NotImplementedException(); } } public override bool IsDBNull(int ordinal) { throw new NotImplementedException(); } public override bool NextResult() { throw new NotImplementedException(); } public override bool Read() { throw new NotImplementedException(); } public override int RecordsAffected { get { throw new NotImplementedException(); } } public override object this[string name] { get { throw new NotImplementedException(); } } public override object this[int ordinal] { get { throw new NotImplementedException(); } } } }
using System; using SharpVectors.Dom; using SharpVectors.Dom.Css; using SharpVectors.Dom.Events; using SharpVectors.Dom.Stylesheets; using SharpVectors.Dom.Svg; using SharpVectors.Dom.Views; using System.Xml; namespace SharpVectors.Scripting { /// /// IScriptableDomTimeStamp /// public class ScriptableDomTimeStamp : ScriptableObject, IScriptableDomTimeStamp { public ScriptableDomTimeStamp(object baseObject) : base (baseObject) { } } /// <summary> /// Implementation wrapper for IScriptableDomImplementation /// </summary> public class ScriptableDomImplementation : ScriptableObject, IScriptableDomImplementation { public ScriptableDomImplementation(object baseObject) : base (baseObject) { } #region Methods - IScriptableDomImplementation public bool hasFeature(string feature, string version) { return ((XmlImplementation)baseObject).HasFeature(feature, version); } public IScriptableDocumentType createDocumentType(string qualifiedName, string publicId, string systemId) { throw new NotSupportedException(); //object result = ((XmlImplementation)baseObject).CreateDocumentType(qualifiedName, publicId, systemId); //return (result != null) ? (IScriptableDocumentType)ScriptableObject.CreateWrapper(result) : null; } public IScriptableDocument createDocument(string namespaceURI, string qualifiedName, IScriptableDocumentType doctype) { throw new NotSupportedException(); //object result = ((XmlImplementation)baseObject).CreateDocument(namespaceURI, qualifiedName, ((IDocumentType)((ScriptableDocumentType)doctype).baseObject)); //return (result != null) ? (IScriptableDocument)ScriptableObject.CreateWrapper(result) : null; } #endregion } /// <summary> /// Implementation wrapper for IScriptableNode /// </summary> public class ScriptableNode : ScriptableObject, IScriptableNode { const ushort ELEMENT_NODE = 1; const ushort ATTRIBUTE_NODE = 2; const ushort TEXT_NODE = 3; const ushort CDATA_SECTION_NODE = 4; const ushort ENTITY_REFERENCE_NODE = 5; const ushort ENTITY_NODE = 6; const ushort PROCESSING_INSTRUCTION_NODE = 7; const ushort COMMENT_NODE = 8; const ushort DOCUMENT_NODE = 9; const ushort DOCUMENT_TYPE_NODE = 10; const ushort DOCUMENT_FRAGMENT_NODE = 11; const ushort NOTATION_NODE = 12; public ScriptableNode(object baseObject) : base (baseObject) { } #region Methods - IScriptableNode public IScriptableNode insertBefore(IScriptableNode newChild, IScriptableNode refChild) { object result = ((INode)baseObject).InsertBefore(((XmlNode)((ScriptableNode)newChild).baseObject), ((XmlNode)((ScriptableNode)refChild).baseObject)); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode replaceChild(IScriptableNode newChild, IScriptableNode oldChild) { object result = ((INode)baseObject).ReplaceChild(((XmlNode)((ScriptableNode)newChild).baseObject), ((XmlNode)((ScriptableNode)oldChild).baseObject)); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode removeChild(IScriptableNode oldChild) { object result = ((INode)baseObject).RemoveChild(((XmlNode)((ScriptableNode)oldChild).baseObject)); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode appendChild(IScriptableNode newChild) { object result = ((INode)baseObject).AppendChild(((XmlNode)((ScriptableNode)newChild).baseObject)); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public bool hasChildNodes() { return ((INode)baseObject).HasChildNodes; } public IScriptableNode cloneNode(bool deep) { object result = ((INode)baseObject).CloneNode(deep); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public void normalize() { ((INode)baseObject).Normalize(); } public bool isSupported(string feature, string version) { return ((INode)baseObject).Supports(feature, version); } public bool hasAttributes() { return ((INode)baseObject).Attributes.Count > 0; } #endregion #region Properties - IScriptableNode public string nodeName { get { return ((INode)baseObject).Name; } } public string nodeValue { get { return ((INode)baseObject).Value; } set { ((INode)baseObject).Value = value; } } public ushort nodeType { get { return (ushort)((INode)baseObject).NodeType; } } public IScriptableNode parentNode { get { object result = ((INode)baseObject).ParentNode; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableNodeList childNodes { get { object result = ((INode)baseObject).ChildNodes; return (result != null) ? (IScriptableNodeList)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableNode firstChild { get { object result = ((INode)baseObject).FirstChild; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableNode lastChild { get { object result = ((INode)baseObject).LastChild; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableNode previousSibling { get { object result = ((INode)baseObject).PreviousSibling; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableNode nextSibling { get { object result = ((INode)baseObject).NextSibling; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableNamedNodeMap attributes { get { object result = ((INode)baseObject).Attributes; return (result != null) ? (IScriptableNamedNodeMap)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableDocument ownerDocument { get { object result = ((INode)baseObject).OwnerDocument; return (result != null) ? (IScriptableDocument)ScriptableObject.CreateWrapper(result) : null; } } public string namespaceURI { get { return ((INode)baseObject).NamespaceURI; } } public string prefix { get { return ((INode)baseObject).Prefix; } set { ((INode)baseObject).Prefix = value; } } public string localName { get { return ((INode)baseObject).LocalName; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableNodeList /// </summary> public class ScriptableNodeList : ScriptableObject, IScriptableNodeList { public ScriptableNodeList(object baseObject) : base (baseObject) { } #region Methods - IScriptableNodeList public IScriptableNode item(ulong index) { object result = ((INodeList)baseObject)[index]; return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } #endregion #region Properties - IScriptableNodeList public ulong length { get { return ((INodeList)baseObject).Count; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableNamedNodeMap /// </summary> public class ScriptableNamedNodeMap : ScriptableObject, IScriptableNamedNodeMap { public ScriptableNamedNodeMap(object baseObject) : base (baseObject) { } #region Methods - IScriptableNamedNodeMap public IScriptableNode getNamedItem(string name) { object result = ((XmlNamedNodeMap)baseObject).GetNamedItem(name); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode setNamedItem(IScriptableNode arg) { object result = ((XmlNamedNodeMap)baseObject).SetNamedItem(((XmlNode)((ScriptableNode)arg).baseObject)); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode removeNamedItem(string name) { object result = ((XmlNamedNodeMap)baseObject).RemoveNamedItem(name); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode item(ulong index) { object result = ((XmlNamedNodeMap)baseObject).Item((int)index); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode getNamedItemNS(string namespaceURI, string localName) { object result = ((XmlNamedNodeMap)baseObject).GetNamedItem(localName, namespaceURI == null ? "" : namespaceURI); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode setNamedItemNS(IScriptableNode arg) { object result = ((XmlNamedNodeMap)baseObject).SetNamedItem(((XmlNode)((ScriptableNode)arg).baseObject)); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode removeNamedItemNS(string namespaceURI, string localName) { object result = ((XmlNamedNodeMap)baseObject).RemoveNamedItem(localName, namespaceURI == null ? "" : namespaceURI); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } #endregion #region Properties - IScriptableNamedNodeMap public ulong length { get { return (ulong)((XmlNamedNodeMap)baseObject).Count; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableCharacterData /// </summary> public class ScriptableCharacterData : ScriptableNode, IScriptableCharacterData { public ScriptableCharacterData(object baseObject) : base (baseObject) { } #region Methods - IScriptableCharacterData public string substringData(ulong offset, ulong count) { if (((ICharacterData)baseObject).Value != null) return ((ICharacterData)baseObject).Value.Substring((int)offset, (int)count); else return null; } public void appendData(string arg) { ((ICharacterData)baseObject).Value += arg; } public void insertData(ulong offset, string arg) { if (((ICharacterData)baseObject).Value != null) ((ICharacterData)baseObject).Value.Insert((int)offset, arg); else ((ICharacterData)baseObject).Value = arg; } public void deleteData(ulong offset, ulong count) { if (((ICharacterData)baseObject).Value != null) ((ICharacterData)baseObject).Value.Remove((int)offset, (int)count); } public void replaceData(ulong offset, ulong count, string arg) { deleteData(offset, count); insertData(offset, arg); } #endregion #region Properties - IScriptableCharacterData public string data { get { return ((ICharacterData)baseObject).Value; } set { ((ICharacterData)baseObject).Value = value; } } public ulong length { get { return (((ICharacterData)baseObject).Value != null) ? (ulong)((ICharacterData)baseObject).Value.Length : (ulong)0; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableAttr /// </summary> public class ScriptableAttr : ScriptableNode, IScriptableAttr { public ScriptableAttr(object baseObject) : base (baseObject) { } #region Properties - IScriptableAttr public string name { get { return ((IAttribute)baseObject).Name; } } public bool specified { get { return ((XmlAttribute)baseObject).Specified; } } public string value { get { return ((IAttribute)baseObject).Value; } set { ((IAttribute)baseObject).Value = value; } } public IScriptableElement ownerElement { get { object result = ((IAttribute)baseObject).ParentNode; return (result != null) ? (IScriptableElement)ScriptableObject.CreateWrapper(result) : null; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableElement /// </summary> public class ScriptableElement : ScriptableNode, IScriptableElement { public ScriptableElement(object baseObject) : base (baseObject) { } #region Methods - IScriptableElement public string getAttribute(string name) { return ((IElement)baseObject).GetAttribute(name); } public void setAttribute(string name, string value) { ((IElement)baseObject).SetAttribute(name, value); } public void removeAttribute(string name) { ((IElement)baseObject).RemoveAttribute(name); } public IScriptableAttr getAttributeNode(string name) { object result = ((IElement)baseObject).GetAttributeNode(name); return (result != null) ? (IScriptableAttr)ScriptableObject.CreateWrapper(result) : null; } public IScriptableAttr setAttributeNode(IScriptableAttr newAttr) { object result = ((IElement)baseObject).SetAttributeNode(((XmlAttribute)((ScriptableAttr)newAttr).baseObject)); return (result != null) ? (IScriptableAttr)ScriptableObject.CreateWrapper(result) : null; } public IScriptableAttr removeAttributeNode(IScriptableAttr oldAttr) { object result = ((IElement)baseObject).RemoveAttributeNode(((XmlAttribute)((ScriptableAttr)oldAttr).baseObject)); return (result != null) ? (IScriptableAttr)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNodeList getElementsByTagName(string name) { object result = ((IElement)baseObject).GetElementsByTagName(name); return (result != null) ? (IScriptableNodeList)ScriptableObject.CreateWrapper(result) : null; } public string getAttributeNS(string namespaceURI, string localName) { return ((IElement)baseObject).GetAttribute(localName, namespaceURI == null ? "" : namespaceURI ); } public void setAttributeNS(string namespaceURI, string qualifiedName, string value) { ((IElement)baseObject).SetAttribute(qualifiedName, namespaceURI == null ? "" : namespaceURI, value); } public void removeAttributeNS(string namespaceURI, string localName) { ((IElement)baseObject).RemoveAttribute(localName, namespaceURI == null ? "" : namespaceURI); } public IScriptableAttr getAttributeNodeNS(string namespaceURI, string localName) { object result = ((IElement)baseObject).GetAttributeNode(localName, namespaceURI == null ? "" : namespaceURI); return (result != null) ? (IScriptableAttr)ScriptableObject.CreateWrapper(result) : null; } public IScriptableAttr setAttributeNodeNS(IScriptableAttr newAttr) { object result = ((IElement)baseObject).SetAttributeNode(((XmlAttribute)((ScriptableAttr)newAttr).baseObject)); return (result != null) ? (IScriptableAttr)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNodeList getElementsByTagNameNS(string namespaceURI, string localName) { object result = ((IElement)baseObject).GetElementsByTagName(localName, namespaceURI == null ? "" : namespaceURI); return (result != null) ? (IScriptableNodeList)ScriptableObject.CreateWrapper(result) : null; } public bool hasAttribute(string name) { return ((IElement)baseObject).HasAttribute(name); } public bool hasAttributeNS(string namespaceURI, string localName) { return ((IElement)baseObject).HasAttribute(localName, namespaceURI == null ? "" : namespaceURI); } #endregion #region Properties - IScriptableElement public string tagName { get { return ((IElement)baseObject).Name; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableText /// </summary> public class ScriptableText : ScriptableCharacterData, IScriptableText { public ScriptableText(object baseObject) : base (baseObject) { } #region Methods - IScriptableText public IScriptableText splitText(ulong offset) { object result = ((XmlText)baseObject).SplitText((int)offset); return (result != null) ? (IScriptableText)ScriptableObject.CreateWrapper(result) : null; } #endregion } /// <summary> /// Implementation wrapper for IScriptableComment /// </summary> public class ScriptableComment : ScriptableCharacterData, IScriptableComment { public ScriptableComment(object baseObject) : base (baseObject) { } } /// <summary> /// Implementation wrapper for IScriptableCDataSection /// </summary> public class ScriptableCDataSection : ScriptableText, IScriptableCDataSection { public ScriptableCDataSection(object baseObject) : base (baseObject) { } } /// <summary> /// Implementation wrapper for IScriptableDocumentType /// </summary> public class ScriptableDocumentType : ScriptableNode, IScriptableDocumentType { public ScriptableDocumentType(object baseObject) : base (baseObject) { } #region Properties - IScriptableDocumentType public string name { get { return ((XmlDocumentType)baseObject).Name; } } public IScriptableNamedNodeMap entities { get { object result = ((XmlDocumentType)baseObject).Entities; return (result != null) ? (IScriptableNamedNodeMap)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableNamedNodeMap notations { get { object result = ((XmlDocumentType)baseObject).Notations; return (result != null) ? (IScriptableNamedNodeMap)ScriptableObject.CreateWrapper(result) : null; } } public string publicId { get { return ((XmlDocumentType)baseObject).PublicId; } } public string systemId { get { return ((XmlDocumentType)baseObject).SystemId; } } public string internalSubset { get { return ((XmlDocumentType)baseObject).InternalSubset; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableNotation /// </summary> public class ScriptableNotation : ScriptableNode, IScriptableNotation { public ScriptableNotation(object baseObject) : base (baseObject) { } #region Properties - IScriptableNotation public string publicId { get { return ((XmlNotation)baseObject).PublicId; } } public string systemId { get { return ((XmlNotation)baseObject).SystemId; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableEntity /// </summary> public class ScriptableEntity : ScriptableNode, IScriptableEntity { public ScriptableEntity(object baseObject) : base (baseObject) { } #region Properties - IScriptableEntity public string publicId { get { return ((XmlEntity)baseObject).PublicId; } } public string systemId { get { return ((XmlEntity)baseObject).SystemId; } } public string notationName { get { return ((XmlEntity)baseObject).NotationName; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableEntityReference /// </summary> public class ScriptableEntityReference : ScriptableNode, IScriptableEntityReference { public ScriptableEntityReference(object baseObject) : base (baseObject) { } } /// <summary> /// Implementation wrapper for IScriptableProcessingInstruction /// </summary> public class ScriptableProcessingInstruction : ScriptableNode, IScriptableProcessingInstruction { public ScriptableProcessingInstruction(object baseObject) : base (baseObject) { } #region Properties - IScriptableProcessingInstruction public string target { get { return ((XmlProcessingInstruction)baseObject).Target; } } public string data { get { return ((XmlProcessingInstruction)baseObject).Data; } set { ((XmlProcessingInstruction)baseObject).Data = value; } } #endregion } /// <summary> /// Implementation wrapper for IScriptableDocumentFragment /// </summary> public class ScriptableDocumentFragment : ScriptableNode, IScriptableDocumentFragment { public ScriptableDocumentFragment(object baseObject) : base (baseObject) { } } /// <summary> /// Implementation wrapper for IScriptableDocument /// </summary> public class ScriptableDocument : ScriptableNode, IScriptableDocument { public ScriptableDocument(object baseObject) : base (baseObject) { } #region Methods - IScriptableDocument public IScriptableElement createElement(string tagName) { object result = ((IDocument)baseObject).CreateElement(tagName); return (result != null) ? (IScriptableElement)ScriptableObject.CreateWrapper(result) : null; } public IScriptableDocumentFragment createDocumentFragment() { object result = ((IDocument)baseObject).CreateDocumentFragment(); return (result != null) ? (IScriptableDocumentFragment)ScriptableObject.CreateWrapper(result) : null; } public IScriptableText createTextNode(string data) { object result = ((IDocument)baseObject).CreateTextNode(data); return (result != null) ? (IScriptableText)ScriptableObject.CreateWrapper(result) : null; } public IScriptableComment createComment(string data) { object result = ((IDocument)baseObject).CreateComment(data); return (result != null) ? (IScriptableComment)ScriptableObject.CreateWrapper(result) : null; } public IScriptableCDataSection createCDATASection(string data) { object result = ((IDocument)baseObject).CreateCDataSection(data); return (result != null) ? (IScriptableCDataSection)ScriptableObject.CreateWrapper(result) : null; } public IScriptableProcessingInstruction createProcessingInstruction(string target, string data) { object result = ((IDocument)baseObject).CreateProcessingInstruction(target, data); return (result != null) ? (IScriptableProcessingInstruction)ScriptableObject.CreateWrapper(result) : null; } public IScriptableAttr createAttribute(string name) { object result = ((IDocument)baseObject).CreateAttribute(name); return (result != null) ? (IScriptableAttr)ScriptableObject.CreateWrapper(result) : null; } public IScriptableEntityReference createEntityReference(string name) { object result = ((IDocument)baseObject).CreateEntityReference(name); return (result != null) ? (IScriptableEntityReference)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNodeList getElementsByTagName(string tagname) { object result = ((IDocument)baseObject).GetElementsByTagName(tagname); return (result != null) ? (IScriptableNodeList)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNode importNode(IScriptableNode importedNode, bool deep) { object result = ((IDocument)baseObject).ImportNode(((INode)((ScriptableNode)importedNode).baseObject), deep); return (result != null) ? (IScriptableNode)ScriptableObject.CreateWrapper(result) : null; } public IScriptableElement createElementNS(string namespaceURI, string qualifiedName) { object result = ((IDocument)baseObject).CreateElementNs(namespaceURI == null ? "" : namespaceURI, qualifiedName); return (result != null) ? (IScriptableElement)ScriptableObject.CreateWrapper(result) : null; } public IScriptableAttr createAttributeNS(string namespaceURI, string qualifiedName) { object result = ((IDocument)baseObject).CreateAttributeNs(namespaceURI == null ? "" : namespaceURI, qualifiedName); return (result != null) ? (IScriptableAttr)ScriptableObject.CreateWrapper(result) : null; } public IScriptableNodeList getElementsByTagNameNS(string namespaceURI, string localName) { object result = ((IDocument)baseObject).GetElementsByTagNameNs(namespaceURI == null ? "" : namespaceURI, localName); return (result != null) ? (IScriptableNodeList)ScriptableObject.CreateWrapper(result) : null; } public IScriptableElement getElementById(string elementId) { object result = ((IDocument)baseObject).GetElementById(elementId); return (result != null) ? (IScriptableElement)ScriptableObject.CreateWrapper(result) : null; } #endregion #region Properties - IScriptableDocument public IScriptableDocumentType doctype { get { object result = ((IDocument)baseObject).Doctype; return (result != null) ? (IScriptableDocumentType)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableDomImplementation implementation { get { object result = ((IDocument)baseObject).Implementation; return (result != null) ? (IScriptableDomImplementation)ScriptableObject.CreateWrapper(result) : null; } } public IScriptableElement documentElement { get { object result = ((IDocument)baseObject).DocumentElement; return (result != null) ? (IScriptableElement)ScriptableObject.CreateWrapper(result) : null; } } #endregion } }
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; namespace BusinessObjects.Documents { [Serializable] public partial class cDocuments_Quote: cDocuments_Document<cDocuments_Quote> { #region Business Methods private static readonly PropertyInfo< System.Int32? > subjectIdProperty = RegisterProperty<System.Int32?>(p => p.SubjectId, string.Empty); public System.Int32? SubjectId { get { return GetProperty(subjectIdProperty); } set { SetProperty(subjectIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > documents_Enums_DocumentStatusIdProperty = RegisterProperty<System.Int32?>(p => p.Documents_Enums_DocumentStatusId, string.Empty,(System.Int32?)null); public System.Int32? Documents_Enums_DocumentStatusId { get { return GetProperty(documents_Enums_DocumentStatusIdProperty); } set { SetProperty(documents_Enums_DocumentStatusIdProperty, value); } } private static readonly PropertyInfo<System.DateTime> maturityDateProperty = RegisterProperty<System.DateTime>(p => p.MaturityDate, string.Empty, System.DateTime.Now); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.DateTime MaturityDate { get { return GetProperty(maturityDateProperty); } set { SetProperty(maturityDateProperty, value); } } private static readonly PropertyInfo< bool? > reversedProperty = RegisterProperty<bool?>(p => p.Reversed, string.Empty,(bool?)null); public bool? Reversed { get { return GetProperty(reversedProperty); } set { SetProperty(reversedProperty, value); } } private static readonly PropertyInfo< bool? > invoicedProperty = RegisterProperty<bool?>(p => p.Invoiced, string.Empty,(bool?)null); public bool? Invoiced { get { return GetProperty(invoicedProperty); } set { SetProperty(invoicedProperty, value); } } private static readonly PropertyInfo< System.Int32? > documents_InvoiceIdProperty = RegisterProperty<System.Int32?>(p => p.Documents_InvoiceId, string.Empty,(System.Int32?)null); public System.Int32? Documents_InvoiceId { get { return GetProperty(documents_InvoiceIdProperty); } set { SetProperty(documents_InvoiceIdProperty, value); } } private static readonly PropertyInfo<System.DateTime?> dispatchDateProperty = RegisterProperty<System.DateTime?>(p => p.DispatchDate, string.Empty, System.DateTime.Now); public System.DateTime? DispatchDate { get { return GetProperty(dispatchDateProperty); } set { SetProperty(dispatchDateProperty, value); } } private static readonly PropertyInfo< System.Int32? > dispatchTypeIdProperty = RegisterProperty<System.Int32?>(p => p.DispatchTypeId, string.Empty,(System.Int32?)null); public System.Int32? DispatchTypeId { get { return GetProperty(dispatchTypeIdProperty); } set { SetProperty(dispatchTypeIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > dispatchCompanyIdProperty = RegisterProperty<System.Int32?>(p => p.DispatchCompanyId, string.Empty,(System.Int32?)null); public System.Int32? DispatchCompanyId { get { return GetProperty(dispatchCompanyIdProperty); } set { SetProperty(dispatchCompanyIdProperty, value); } } private static readonly PropertyInfo< System.String > dispatchDescriptionProperty = RegisterProperty<System.String>(p => p.DispatchDescription, string.Empty, (System.String)null); public System.String DispatchDescription { get { return GetProperty(dispatchDescriptionProperty); } set { SetProperty(dispatchDescriptionProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo< System.Decimal > wholesaleValueProperty = RegisterProperty<System.Decimal>(p => p.WholesaleValue, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Decimal WholesaleValue { get { return GetProperty(wholesaleValueProperty); } set { SetProperty(wholesaleValueProperty, value); } } private static readonly PropertyInfo< System.Decimal > taxValueProperty = RegisterProperty<System.Decimal>(p => p.TaxValue, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Decimal TaxValue { get { return GetProperty(taxValueProperty); } set { SetProperty(taxValueProperty, value); } } private static readonly PropertyInfo< System.Decimal? > rabateValueProperty = RegisterProperty<System.Decimal?>(p => p.RabateValue, string.Empty, (System.Decimal?)null); public System.Decimal? RabateValue { get { return GetProperty(rabateValueProperty); } set { SetProperty(rabateValueProperty, value); } } private static readonly PropertyInfo< System.Decimal? > otherDiscountsValueProperty = RegisterProperty<System.Decimal?>(p => p.OtherDiscountsValue, string.Empty, (System.Decimal?)null); public System.Decimal? OtherDiscountsValue { get { return GetProperty(otherDiscountsValueProperty); } set { SetProperty(otherDiscountsValueProperty, value); } } private static readonly PropertyInfo< System.Decimal > retailValueProperty = RegisterProperty<System.Decimal>(p => p.RetailValue, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Decimal RetailValue { get { return GetProperty(retailValueProperty); } set { SetProperty(retailValueProperty, value); } } private static readonly PropertyInfo< System.String > conditionsProperty = RegisterProperty<System.String>(p => p.Conditions, string.Empty, (System.String)null); public System.String Conditions { get { return GetProperty(conditionsProperty); } set { SetProperty(conditionsProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo< System.Int32? > mDGeneral_Enums_CurrencyIdProperty = RegisterProperty<System.Int32?>(p => p.MDGeneral_Enums_CurrencyId, string.Empty,(System.Int32?)null); //private static readonly PropertyInfo<System.Int32?> mDGeneral_Enums_CurrencyIdProperty = RegisterProperty<System.Int32?>(p => p.MDGeneral_Enums_CurrencyId, string.Empty, 2); public System.Int32? MDGeneral_Enums_CurrencyId { get { return GetProperty(mDGeneral_Enums_CurrencyIdProperty); } set { SetProperty(mDGeneral_Enums_CurrencyIdProperty, value); } } private static readonly PropertyInfo< System.Decimal? > courseValueProperty = RegisterProperty<System.Decimal?>(p => p.CourseValue, string.Empty, 1); public System.Decimal? CourseValue { get { return GetProperty(courseValueProperty); } set { SetProperty(courseValueProperty, value); } } private static readonly PropertyInfo<System.String> billToAddress_NameProperty = RegisterProperty<System.String>(p => p.BillToAddress_Name, string.Empty, (System.String)null); public System.String BillToAddress_Name { get { return GetProperty(billToAddress_NameProperty); } set { SetProperty(billToAddress_NameProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo< System.Int32? > billToAddress_PlaceIdProperty = RegisterProperty<System.Int32?>(p => p.BillToAddress_PlaceId, string.Empty); public System.Int32? BillToAddress_PlaceId { get { return GetProperty(billToAddress_PlaceIdProperty); } set { SetProperty(billToAddress_PlaceIdProperty, value); } } private static readonly PropertyInfo< System.String > billToAddress_StreetProperty = RegisterProperty<System.String>(p => p.BillToAddress_Street, string.Empty, (System.String)null); public System.String BillToAddress_Street { get { return GetProperty(billToAddress_StreetProperty); } set { SetProperty(billToAddress_StreetProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo< System.String > billToAddress_NumberProperty = RegisterProperty<System.String>(p => p.BillToAddress_Number, string.Empty, (System.String)null); public System.String BillToAddress_Number { get { return GetProperty(billToAddress_NumberProperty); } set { SetProperty(billToAddress_NumberProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo< System.String > billToAddress_DescriptionProperty = RegisterProperty<System.String>(p => p.BillToAddress_Description, string.Empty, (System.String)null); public System.String BillToAddress_Description { get { return GetProperty(billToAddress_DescriptionProperty); } set { SetProperty(billToAddress_DescriptionProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo< System.Int32? > shipToAddress_PlaceIdProperty = RegisterProperty<System.Int32?>(p => p.ShipToAddress_PlaceId, string.Empty); public System.Int32? ShipToAddress_PlaceId { get { return GetProperty(shipToAddress_PlaceIdProperty); } set { SetProperty(shipToAddress_PlaceIdProperty, value); } } private static readonly PropertyInfo< System.String > shipToAddress_StreetProperty = RegisterProperty<System.String>(p => p.ShipToAddress_Street, string.Empty, (System.String)null); public System.String ShipToAddress_Street { get { return GetProperty(shipToAddress_StreetProperty); } set { SetProperty(shipToAddress_StreetProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo< System.String > shipToAddress_NumberProperty = RegisterProperty<System.String>(p => p.ShipToAddress_Number, string.Empty, (System.String)null); public System.String ShipToAddress_Number { get { return GetProperty(shipToAddress_NumberProperty); } set { SetProperty(shipToAddress_NumberProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo< System.String > shipToAddress_DescriptionProperty = RegisterProperty<System.String>(p => p.ShipToAddress_Description, string.Empty, (System.String)null); public System.String ShipToAddress_Description { get { return GetProperty(shipToAddress_DescriptionProperty); } set { SetProperty(shipToAddress_DescriptionProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<bool?> dispatchedProperty = RegisterProperty<bool?>(p => p.Dispatched, string.Empty, (bool?)null); public bool? Dispatched { get { return GetProperty(dispatchedProperty); } set { SetProperty(dispatchedProperty, value); } } private static readonly PropertyInfo<System.Int32?> documents_DispatchedIdProperty = RegisterProperty<System.Int32?>(p => p.Documents_DispatchedId, string.Empty, (System.Int32?)null); public System.Int32? Documents_DispatchedId { get { return GetProperty(documents_DispatchedIdProperty); } set { SetProperty(documents_DispatchedIdProperty, value); } } private static readonly PropertyInfo<bool?> enteredInTheAccountsProperty = RegisterProperty<bool?>(p => p.EnteredInTheAccounts, string.Empty, (bool?)null); public bool? EnteredInTheAccounts { get { return GetProperty(enteredInTheAccountsProperty); } set { SetProperty(enteredInTheAccountsProperty, value); } } private static readonly PropertyInfo<System.Int16?> statusProperty = RegisterProperty<System.Int16?>(p => p.Status, string.Empty, (System.Int16?)null); public System.Int16? Status { get { return GetProperty(statusProperty); } set { SetProperty(statusProperty, value); } } #endregion #region Factory Methods public static cDocuments_Quote NewDocuments_Quote() { return DataPortal.Create<cDocuments_Quote>(); } public static cDocuments_Quote GetDocuments_Quote(int uniqueId) { return DataPortal.Fetch<cDocuments_Quote>(new SingleCriteria<cDocuments_Quote, int>(uniqueId)); } internal static cDocuments_Quote GetDocuments_Quote(Documents_Quote data) { return DataPortal.Fetch<cDocuments_Quote>(data); } #endregion #region Data Access [RunLocal] protected override void DataPortal_Create() { BusinessRules.CheckRules(); } private void DataPortal_Fetch(SingleCriteria<cDocuments_Quote, int> criteria) { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = ctx.ObjectContext.Documents_Document.OfType<Documents_Quote>().First(p => p.Id == criteria.Value); LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LoadProperty<Guid>(GUIDProperty, data.GUID); LoadProperty<short>(documentTypeProperty, data.DocumentType); LoadProperty<string>(uniqueIdentifierProperty, data.UniqueIdentifier); LoadProperty<string>(barcodeProperty, data.Barcode); LoadProperty<int>(ordinalNumberProperty, data.OrdinalNumber); LoadProperty<int>(ordinalNumberInYearProperty, data.OrdinalNumberInYear); LoadProperty<DateTime>(documentDateTimeProperty, data.DocumentDateTime); LoadProperty<DateTime>(creationDateTimeProperty, data.CreationDateTime); LoadProperty<int>(mDSubjects_Employee_AuthorIdProperty, data.MDSubjects_Employee_AuthorId); LoadProperty<string>(descriptionProperty, data.Description); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<DateTime>(lastActivityDateProperty, data.LastActivityDate); LoadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty, data.MDSubjects_EmployeeWhoChengedId); LoadProperty<short?>(statusProperty, data.Status); LoadProperty<int?>(subjectIdProperty, data.SubjectId); LoadProperty<int?>(documents_Enums_DocumentStatusIdProperty, data.Documents_Enums_DocumentStatusId); LoadProperty<DateTime>(maturityDateProperty, data.MaturityDate); LoadProperty<bool?>(reversedProperty, data.Reversed); LoadProperty<bool?>(invoicedProperty, data.Invoiced); LoadProperty<int?>(documents_InvoiceIdProperty, data.Documents_InvoiceId); LoadProperty<DateTime?>(dispatchDateProperty, data.DispatchDate); LoadProperty<int?>(dispatchTypeIdProperty, data.DispatchTypeId); LoadProperty<int?>(dispatchCompanyIdProperty, data.DispatchCompanyId); LoadProperty<string>(dispatchDescriptionProperty, data.DispatchDescription); LoadProperty<decimal>(wholesaleValueProperty, data.WholesaleValue); LoadProperty<decimal>(taxValueProperty, data.TaxValue); LoadProperty<decimal?>(rabateValueProperty, data.RabateValue); LoadProperty<decimal?>(otherDiscountsValueProperty, data.OtherDiscountsValue); LoadProperty<decimal>(retailValueProperty, data.RetailValue); LoadProperty<string>(conditionsProperty, data.Conditions); LoadProperty<int?>(mDGeneral_Enums_CurrencyIdProperty, data.MDGeneral_Enums_CurrencyId); LoadProperty<decimal?>(courseValueProperty, data.CourseValue); LoadProperty<string>(billToAddress_NameProperty, data.BillToAddress_Name); LoadProperty<int?>(billToAddress_PlaceIdProperty, data.BillToAddress_PlaceId); LoadProperty<string>(billToAddress_StreetProperty, data.BillToAddress_Street); LoadProperty<string>(billToAddress_NumberProperty, data.BillToAddress_Number); LoadProperty<string>(billToAddress_DescriptionProperty, data.BillToAddress_Description); LoadProperty<int?>(shipToAddress_PlaceIdProperty, data.ShipToAddress_PlaceId); LoadProperty<string>(shipToAddress_StreetProperty, data.ShipToAddress_Street); LoadProperty<string>(shipToAddress_NumberProperty, data.ShipToAddress_Number); LoadProperty<string>(shipToAddress_DescriptionProperty, data.ShipToAddress_Description); LoadProperty<bool?>(dispatchedProperty, data.Dispatched); LoadProperty<int?>(documents_DispatchedIdProperty, data.Documents_DispatchedId); LoadProperty<bool?>(enteredInTheAccountsProperty, data.EnteredInTheAccounts); LastChanged = data.LastChanged; LoadProperty<cDocuments_ItemsCol>(Documents_ItemsColProperty, cDocuments_ItemsCol.GetDocuments_ItemsCol(data.Documents_ItemsCol)); BusinessRules.CheckRules(); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_Quote(); data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty); data.GUID = ReadProperty<Guid>(GUIDProperty); data.DocumentType = ReadProperty<short>(documentTypeProperty); data.UniqueIdentifier = ReadProperty<string>(uniqueIdentifierProperty); data.Barcode = ReadProperty<string>(barcodeProperty); data.OrdinalNumber = ReadProperty<int>(ordinalNumberProperty); data.OrdinalNumberInYear = ReadProperty<int>(ordinalNumberInYearProperty); data.DocumentDateTime = ReadProperty<DateTime>(documentDateTimeProperty); data.CreationDateTime = ReadProperty<DateTime>(creationDateTimeProperty); data.MDSubjects_Employee_AuthorId = ReadProperty<int>(mDSubjects_Employee_AuthorIdProperty); data.Description = ReadProperty<string>(descriptionProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty); data.Status = ReadProperty<short?>(statusProperty); data.SubjectId = ReadProperty<int?>(subjectIdProperty); data.MaturityDate = ReadProperty<DateTime>(maturityDateProperty); data.Reversed = ReadProperty<bool?>(reversedProperty); data.Invoiced = ReadProperty<bool?>(invoicedProperty); data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty); data.DispatchDate = ReadProperty<DateTime?>(dispatchDateProperty); data.DispatchTypeId = ReadProperty<int?>(dispatchTypeIdProperty); data.DispatchCompanyId = ReadProperty<int?>(dispatchCompanyIdProperty); data.DispatchDescription = ReadProperty<string>(dispatchDescriptionProperty); data.WholesaleValue = ReadProperty<decimal>(wholesaleValueProperty); data.TaxValue = ReadProperty<decimal>(taxValueProperty); data.RabateValue = ReadProperty<decimal?>(rabateValueProperty); data.OtherDiscountsValue = ReadProperty<decimal?>(otherDiscountsValueProperty); data.RetailValue = ReadProperty<decimal>(retailValueProperty); data.Conditions = ReadProperty<string>(conditionsProperty); data.MDGeneral_Enums_CurrencyId = ReadProperty<int?>(mDGeneral_Enums_CurrencyIdProperty); data.CourseValue = ReadProperty<decimal?>(courseValueProperty); data.BillToAddress_Name = ReadProperty<string>(billToAddress_NameProperty); data.BillToAddress_PlaceId = ReadProperty<int?>(billToAddress_PlaceIdProperty); data.BillToAddress_Street = ReadProperty<string>(billToAddress_StreetProperty); data.BillToAddress_Number = ReadProperty<string>(billToAddress_NumberProperty); data.BillToAddress_Description = ReadProperty<string>(billToAddress_DescriptionProperty); data.ShipToAddress_PlaceId = ReadProperty<int?>(shipToAddress_PlaceIdProperty); data.ShipToAddress_Street = ReadProperty<string>(shipToAddress_StreetProperty); data.ShipToAddress_Number = ReadProperty<string>(shipToAddress_NumberProperty); data.ShipToAddress_Description = ReadProperty<string>(shipToAddress_DescriptionProperty); data.Dispatched = ReadProperty<bool?>(dispatchedProperty); data.Documents_DispatchedId = ReadProperty<int?>(documents_DispatchedIdProperty); data.EnteredInTheAccounts = ReadProperty<bool?>(enteredInTheAccountsProperty); ctx.ObjectContext.AddToDocuments_Document(data); DataPortal.UpdateChild(ReadProperty<cDocuments_ItemsCol>(Documents_ItemsColProperty), data); ctx.ObjectContext.SaveChanges(); //Get New id int newId = data.Id; //Load New Id into object LoadProperty(IdProperty, newId); //Load New EntityKey into Object LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey)); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_Quote(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty); data.GUID = ReadProperty<Guid>(GUIDProperty); data.DocumentType = ReadProperty<short>(documentTypeProperty); data.UniqueIdentifier = ReadProperty<string>(uniqueIdentifierProperty); data.Barcode = ReadProperty<string>(barcodeProperty); data.OrdinalNumber = ReadProperty<int>(ordinalNumberProperty); data.OrdinalNumberInYear = ReadProperty<int>(ordinalNumberInYearProperty); data.DocumentDateTime = ReadProperty<DateTime>(documentDateTimeProperty); data.CreationDateTime = ReadProperty<DateTime>(creationDateTimeProperty); data.MDSubjects_Employee_AuthorId = ReadProperty<int>(mDSubjects_Employee_AuthorIdProperty); data.Description = ReadProperty<string>(descriptionProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.MDSubjects_EmployeeWhoChengedId = ReadProperty<int>(mDSubjects_EmployeeWhoChengedIdProperty); data.Status = ReadProperty<short?>(statusProperty); data.SubjectId = ReadProperty<int?>(subjectIdProperty); data.MaturityDate = ReadProperty<DateTime>(maturityDateProperty); data.Reversed = ReadProperty<bool?>(reversedProperty); data.Invoiced = ReadProperty<bool?>(invoicedProperty); data.Documents_InvoiceId = ReadProperty<int?>(documents_InvoiceIdProperty); data.DispatchDate = ReadProperty<DateTime?>(dispatchDateProperty); data.DispatchTypeId = ReadProperty<int?>(dispatchTypeIdProperty); data.DispatchCompanyId = ReadProperty<int?>(dispatchCompanyIdProperty); data.DispatchDescription = ReadProperty<string>(dispatchDescriptionProperty); data.WholesaleValue = ReadProperty<decimal>(wholesaleValueProperty); data.TaxValue = ReadProperty<decimal>(taxValueProperty); data.RabateValue = ReadProperty<decimal?>(rabateValueProperty); data.OtherDiscountsValue = ReadProperty<decimal?>(otherDiscountsValueProperty); data.RetailValue = ReadProperty<decimal>(retailValueProperty); data.Conditions = ReadProperty<string>(conditionsProperty); data.MDGeneral_Enums_CurrencyId = ReadProperty<int?>(mDGeneral_Enums_CurrencyIdProperty); data.CourseValue = ReadProperty<decimal?>(courseValueProperty); data.BillToAddress_Name = ReadProperty<string>(billToAddress_NameProperty); data.BillToAddress_PlaceId = ReadProperty<int?>(billToAddress_PlaceIdProperty); data.BillToAddress_Street = ReadProperty<string>(billToAddress_StreetProperty); data.BillToAddress_Number = ReadProperty<string>(billToAddress_NumberProperty); data.BillToAddress_Description = ReadProperty<string>(billToAddress_DescriptionProperty); data.ShipToAddress_PlaceId = ReadProperty<int?>(shipToAddress_PlaceIdProperty); data.ShipToAddress_Street = ReadProperty<string>(shipToAddress_StreetProperty); data.ShipToAddress_Number = ReadProperty<string>(shipToAddress_NumberProperty); data.ShipToAddress_Description = ReadProperty<string>(shipToAddress_DescriptionProperty); data.Dispatched = ReadProperty<bool?>(dispatchedProperty); data.Documents_DispatchedId = ReadProperty<int?>(documents_DispatchedIdProperty); data.EnteredInTheAccounts = ReadProperty<bool?>(enteredInTheAccountsProperty); DataPortal.UpdateChild(ReadProperty<cDocuments_ItemsCol>(Documents_ItemsColProperty), data); ctx.ObjectContext.SaveChanges(); } } #endregion } }
using System.Collections.Generic; using System.Linq; using Bridge.Contract; using Bridge.Contract.Constants; using ICSharpCode.NRefactory.CSharp; namespace Bridge.Translator { public class ConditionalBlock : ConversionBlock { public ConditionalBlock(IEmitter emitter, ConditionalExpression conditionalExpression) : base(emitter, conditionalExpression) { this.Emitter = emitter; this.ConditionalExpression = conditionalExpression; } public ConditionalExpression ConditionalExpression { get; set; } public List<IAsyncStep> EmittedAsyncSteps { get; set; } protected override Expression GetExpression() { return this.ConditionalExpression; } protected override void EmitConversionExpression() { var conditionalExpression = this.ConditionalExpression; if (this.Emitter.IsAsync && this.GetAwaiters(this.ConditionalExpression).Length > 0) { if (this.Emitter.AsyncBlock.WrittenAwaitExpressions.Contains(conditionalExpression)) { var index = System.Array.IndexOf(this.Emitter.AsyncBlock.AwaitExpressions, conditionalExpression) + 1; this.Write(JS.Vars.ASYNC_TASK_RESULT + index); } else { var index = System.Array.IndexOf(this.Emitter.AsyncBlock.AwaitExpressions, this.ConditionalExpression) + 1; this.WriteAsyncConditionalExpression(index); } } else { conditionalExpression.Condition.AcceptVisitor(this.Emitter); this.Write(" ? "); conditionalExpression.TrueExpression.AcceptVisitor(this.Emitter); this.Write(" : "); conditionalExpression.FalseExpression.AcceptVisitor(this.Emitter); } } internal void WriteAsyncConditionalExpression(int index) { if (this.Emitter.AsyncBlock.WrittenAwaitExpressions.Contains(this.ConditionalExpression)) { return; } this.Emitter.AsyncBlock.WrittenAwaitExpressions.Add(this.ConditionalExpression); this.WriteAwaiters(this.ConditionalExpression.Condition); this.WriteIf(); this.WriteOpenParentheses(); var oldValue = this.Emitter.ReplaceAwaiterByVar; var oldAsyncExpressionHandling = this.Emitter.AsyncExpressionHandling; this.Emitter.ReplaceAwaiterByVar = true; this.Emitter.AsyncExpressionHandling = true; this.ConditionalExpression.Condition.AcceptVisitor(this.Emitter); this.WriteCloseParentheses(); this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; int startCount = 0; int elseCount = 0; IAsyncStep trueStep = null; IAsyncStep elseStep = null; startCount = this.Emitter.AsyncBlock.Steps.Count; this.EmittedAsyncSteps = this.Emitter.AsyncBlock.EmittedAsyncSteps; this.Emitter.AsyncBlock.EmittedAsyncSteps = new List<IAsyncStep>(); var taskResultVar = JS.Vars.ASYNC_TASK_RESULT + index; if (!this.Emitter.Locals.ContainsKey(taskResultVar)) { this.AddLocal(taskResultVar, null, AstType.Null); } this.WriteSpace(); this.BeginBlock(); this.Write($"{JS.Vars.ASYNC_STEP} = {this.Emitter.AsyncBlock.Step};"); this.WriteNewLine(); this.Write("continue;"); var writer = this.SaveWriter(); this.Emitter.AsyncBlock.AddAsyncStep(); this.WriteAwaiters(this.ConditionalExpression.TrueExpression); oldValue = this.Emitter.ReplaceAwaiterByVar; oldAsyncExpressionHandling = this.Emitter.AsyncExpressionHandling; this.Emitter.ReplaceAwaiterByVar = true; this.Emitter.AsyncExpressionHandling = true; this.Write(taskResultVar + " = "); this.ConditionalExpression.TrueExpression.AcceptVisitor(this.Emitter); this.WriteSemiColon(); this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; if (this.Emitter.AsyncBlock.Steps.Count > startCount) { trueStep = this.Emitter.AsyncBlock.Steps.Last(); } if (this.RestoreWriter(writer) && !this.IsOnlyWhitespaceOnPenultimateLine(true)) { this.WriteNewLine(); } this.EndBlock(); this.WriteSpace(); elseCount = this.Emitter.AsyncBlock.Steps.Count; this.WriteSpace(); this.WriteElse(); this.BeginBlock(); this.Write($"{JS.Vars.ASYNC_STEP} = {this.Emitter.AsyncBlock.Step};"); this.WriteNewLine(); this.Write("continue;"); writer = this.SaveWriter(); this.Emitter.AsyncBlock.AddAsyncStep(); this.WriteAwaiters(this.ConditionalExpression.FalseExpression); oldValue = this.Emitter.ReplaceAwaiterByVar; oldAsyncExpressionHandling = this.Emitter.AsyncExpressionHandling; this.Emitter.ReplaceAwaiterByVar = true; this.Emitter.AsyncExpressionHandling = true; this.Write(taskResultVar + " = "); this.ConditionalExpression.FalseExpression.AcceptVisitor(this.Emitter); this.WriteSemiColon(); this.Emitter.ReplaceAwaiterByVar = oldValue; this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling; if (this.Emitter.AsyncBlock.Steps.Count > elseCount) { elseStep = this.Emitter.AsyncBlock.Steps.Last(); } if (this.RestoreWriter(writer) && !this.IsOnlyWhitespaceOnPenultimateLine(true)) { this.WriteNewLine(); } this.EndBlock(); this.WriteSpace(); if (this.Emitter.IsAsync && this.Emitter.AsyncBlock.Steps.Count > startCount) { if (this.Emitter.AsyncBlock.Steps.Count <= elseCount && !AbstractEmitterBlock.IsJumpStatementLast(this.Emitter.Output.ToString())) { this.WriteNewLine(); this.Write($"{JS.Vars.ASYNC_STEP} = {this.Emitter.AsyncBlock.Step};"); this.WriteNewLine(); this.Write("continue;"); } var nextStep = this.Emitter.AsyncBlock.AddAsyncStep(); if (trueStep != null) { trueStep.JumpToStep = nextStep.Step; } if (elseStep != null) { elseStep.JumpToStep = nextStep.Step; } } else if (this.Emitter.IsAsync) { this.WriteNewLine(); } if (this.Emitter.IsAsync) { this.Emitter.AsyncBlock.EmittedAsyncSteps = this.EmittedAsyncSteps; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Analyzer = Lucene.Net.Analysis.Analyzer; using StandardAnalyzer = Lucene.Net.Analysis.Standard.StandardAnalyzer; using Document = Lucene.Net.Documents.Document; using FilterIndexReader = Lucene.Net.Index.FilterIndexReader; using IndexReader = Lucene.Net.Index.IndexReader; using QueryParser = Lucene.Net.QueryParsers.QueryParser; using FSDirectory = Lucene.Net.Store.FSDirectory; using Version = Lucene.Net.Util.Version; using Collector = Lucene.Net.Search.Collector; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using Query = Lucene.Net.Search.Query; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using Scorer = Lucene.Net.Search.Scorer; using Searcher = Lucene.Net.Search.Searcher; using TopScoreDocCollector = Lucene.Net.Search.TopScoreDocCollector; namespace Lucene.Net.Demo { /// <summary>Simple command-line based search demo. </summary> public class SearchFiles { private class AnonymousClassCollector:Collector { private Scorer scorer; private int docBase; // simply print docId and score of every matching document public override void Collect(int doc) { System.Console.Out.WriteLine("doc=" + doc + docBase + " score=" + scorer.Score()); } public override bool AcceptsDocsOutOfOrder() { return true; } public override void SetNextReader(IndexReader reader, int docBase) { this.docBase = docBase; } public override void SetScorer(Scorer scorer) { this.scorer = scorer; } } /// <summary>Use the norms from one field for all fields. Norms are read into memory, /// using a byte of memory per document per searched field. This can cause /// search of large collections with a large number of fields to run out of /// memory. If all of the fields contain only a single token, then the norms /// are all identical, then single norm vector may be shared. /// </summary> private class OneNormsReader:FilterIndexReader { private System.String field; public OneNormsReader(IndexReader in_Renamed, System.String field):base(in_Renamed) { this.field = field; } public override byte[] Norms(System.String field) { return in_Renamed.Norms(this.field); } } private SearchFiles() { } /// <summary>Simple command-line based search demo. </summary> [STAThread] public static void Main(System.String[] args) { System.String usage = "Usage:\t" + typeof(SearchFiles) + "[-index dir] [-field f] [-repeat n] [-queries file] [-raw] [-norms field] [-paging hitsPerPage]"; usage += "\n\tSpecify 'false' for hitsPerPage to use streaming instead of paging search."; if (args.Length > 0 && ("-h".Equals(args[0]) || "-help".Equals(args[0]))) { System.Console.Out.WriteLine(usage); System.Environment.Exit(0); } System.String index = "index"; System.String field = "contents"; System.String queries = null; int repeat = 0; bool raw = false; System.String normsField = null; bool paging = true; int hitsPerPage = 10; for (int i = 0; i < args.Length; i++) { if ("-index".Equals(args[i])) { index = args[i + 1]; i++; } else if ("-field".Equals(args[i])) { field = args[i + 1]; i++; } else if ("-queries".Equals(args[i])) { queries = args[i + 1]; i++; } else if ("-repeat".Equals(args[i])) { repeat = System.Int32.Parse(args[i + 1]); i++; } else if ("-raw".Equals(args[i])) { raw = true; } else if ("-norms".Equals(args[i])) { normsField = args[i + 1]; i++; } else if ("-paging".Equals(args[i])) { if (args[i + 1].Equals("false")) { paging = false; } else { hitsPerPage = System.Int32.Parse(args[i + 1]); if (hitsPerPage == 0) { paging = false; } } i++; } } IndexReader reader = IndexReader.Open(FSDirectory.Open(new System.IO.FileInfo(index)), true); // only searching, so read-only=true if (normsField != null) reader = new OneNormsReader(reader, normsField); Searcher searcher = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); System.IO.StreamReader in_Renamed = null; if (queries != null) { in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(queries, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(queries, System.Text.Encoding.Default).CurrentEncoding); } else { in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(System.Console.OpenStandardInput(), System.Text.Encoding.GetEncoding("UTF-8")).BaseStream, new System.IO.StreamReader(System.Console.OpenStandardInput(), System.Text.Encoding.GetEncoding("UTF-8")).CurrentEncoding); } QueryParser parser = new QueryParser(field, analyzer); while (true) { if (queries == null) // prompt the user System.Console.Out.WriteLine("Enter query: "); System.String line = in_Renamed.ReadLine(); if (line == null || line.Length == - 1) break; line = line.Trim(); if (line.Length == 0) break; Query query = parser.Parse(line); System.Console.Out.WriteLine("Searching for: " + query.ToString(field)); if (repeat > 0) { // repeat & time as benchmark System.DateTime start = System.DateTime.Now; for (int i = 0; i < repeat; i++) { searcher.Search(query, null, 100); } System.DateTime end = System.DateTime.Now; System.Console.Out.WriteLine("Time: " + (end.Millisecond - start.Millisecond) + "ms"); } if (paging) { DoPagingSearch(in_Renamed, searcher, query, hitsPerPage, raw, queries == null); } else { DoStreamingSearch(searcher, query); } } reader.Close(); } /// <summary> This method uses a custom HitCollector implementation which simply prints out /// the docId and score of every matching document. /// /// This simulates the streaming search use case, where all hits are supposed to /// be processed, regardless of their relevance. /// </summary> public static void DoStreamingSearch(Searcher searcher, Query query) { Collector streamingHitCollector = new AnonymousClassCollector(); searcher.Search(query, streamingHitCollector); } /// <summary> This demonstrates a typical paging search scenario, where the search engine presents /// pages of size n to the user. The user can then go to the next page if interested in /// the next hits. /// /// When the query is executed for the first time, then only enough results are collected /// to fill 5 result pages. If the user wants to page beyond this limit, then the query /// is executed another time and all hits are collected. /// /// </summary> public static void DoPagingSearch(System.IO.StreamReader in_Renamed, Searcher searcher, Query query, int hitsPerPage, bool raw, bool interactive) { // Collect enough docs to show 5 pages TopScoreDocCollector collector = TopScoreDocCollector.create(5 * hitsPerPage, false); searcher.Search(query, collector); ScoreDoc[] hits = collector.TopDocs().scoreDocs; int numTotalHits = collector.GetTotalHits(); System.Console.Out.WriteLine(numTotalHits + " total matching documents"); int start = 0; int end = System.Math.Min(numTotalHits, hitsPerPage); while (true) { if (end > hits.Length) { System.Console.Out.WriteLine("Only results 1 - " + hits.Length + " of " + numTotalHits + " total matching documents collected."); System.Console.Out.WriteLine("Collect more (y/n) ?"); System.String line = in_Renamed.ReadLine(); if (line.Length == 0 || line[0] == 'n') { break; } collector = TopScoreDocCollector.create(numTotalHits, false); searcher.Search(query, collector); hits = collector.TopDocs().scoreDocs; } end = System.Math.Min(hits.Length, start + hitsPerPage); for (int i = start; i < end; i++) { if (raw) { // output raw format System.Console.Out.WriteLine("doc=" + hits[i].doc + " score=" + hits[i].score); continue; } Document doc = searcher.Doc(hits[i].doc); System.String path = doc.Get("path"); if (path != null) { System.Console.Out.WriteLine((i + 1) + ". " + path); System.String title = doc.Get("title"); if (title != null) { System.Console.Out.WriteLine(" Title: " + doc.Get("title")); } } else { System.Console.Out.WriteLine((i + 1) + ". " + "No path for this document"); } } if (!interactive) { break; } if (numTotalHits >= end) { bool quit = false; while (true) { System.Console.Out.Write("Press "); if (start - hitsPerPage >= 0) { System.Console.Out.Write("(p)revious page, "); } if (start + hitsPerPage < numTotalHits) { System.Console.Out.Write("(n)ext page, "); } System.Console.Out.WriteLine("(q)uit or enter number to jump to a page."); System.String line = in_Renamed.ReadLine(); if (line.Length == 0 || line[0] == 'q') { quit = true; break; } if (line[0] == 'p') { start = System.Math.Max(0, start - hitsPerPage); break; } else if (line[0] == 'n') { if (start + hitsPerPage < numTotalHits) { start += hitsPerPage; } break; } else { int page = System.Int32.Parse(line); if ((page - 1) * hitsPerPage < numTotalHits) { start = (page - 1) * hitsPerPage; break; } else { System.Console.Out.WriteLine("No such page"); } } } if (quit) break; end = System.Math.Min(numTotalHits, start + hitsPerPage); } } } } }
#region Foreign-License /* This class contains the implementation of the Jacl binary data object. Copyright (c) 1999 Christian Krone. Copyright (c) 1997 Sun Microsystems, Inc. Copyright (c) 2012 Sky Morey See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #endregion using System; namespace Tcl.Lang { /// <summary> This class implements the binary data object type in Tcl.</summary> public class TclByteArray : IInternalRep { /// <summary> The number of bytes used in the byte array. /// The following structure is the internal rep for a ByteArray object. /// Keeps track of how much memory has been used. This can be different from /// how much has been allocated for the byte array to enable growing and /// shrinking of the ByteArray object with fewer allocations. /// </summary> private int used; /// <summary> Internal representation of the binary data.</summary> private byte[] bytes; /// <summary> Create a new empty Tcl binary data.</summary> private TclByteArray() { used = 0; bytes = new byte[0]; } /// <summary> Create a new Tcl binary data.</summary> private TclByteArray(byte[] b) { used = b.Length; bytes = new byte[used]; Array.Copy(b, 0, bytes, 0, used); } /// <summary> Create a new Tcl binary data.</summary> private TclByteArray(byte[] b, int position, int length) { used = length; bytes = new byte[used]; Array.Copy(b, position, bytes, 0, used); } /// <summary> Create a new Tcl binary data.</summary> private TclByteArray(char[] c) { used = c.Length; bytes = new byte[used]; for (int ix = 0; ix < used; ix++) { bytes[ix] = (byte)c[ix]; } } /// <summary> Returns a duplicate of the current object. /// /// </summary> /// <param name="obj">the TclObject that contains this internalRep. /// </param> public IInternalRep Duplicate() { return new TclByteArray(bytes, 0, used); } /// <summary> Implement this no-op for the InternalRep interface.</summary> public void Dispose() { } /// <summary> Called to query the string representation of the Tcl object. This /// method is called only by TclObject.toString() when /// TclObject.stringRep is null. /// /// </summary> /// <returns> the string representation of the Tcl object. /// </returns> public override string ToString() { char[] c = new char[used]; for (int ix = 0; ix < used; ix++) { c[ix] = (char)(bytes[ix] & 0xff); } return new string(c); } /// <summary> Creates a new instance of a TclObject with a TclByteArray internal /// rep. /// /// </summary> /// <returns> the TclObject with the given byte array value. /// </returns> public static TclObject NewInstance(byte[] b, int position, int length) { return new TclObject(new TclByteArray(b, position, length)); } /// <summary> Creates a new instance of a TclObject with a TclByteArray internal /// rep. /// /// </summary> /// <returns> the TclObject with the given byte array value. /// </returns> public static TclObject NewInstance(byte[] b) { return new TclObject(new TclByteArray(b)); } /// <summary> Creates a new instance of a TclObject with an empty TclByteArray /// internal rep. /// /// </summary> /// <returns> the TclObject with the empty byte array value. /// </returns> public static TclObject NewInstance() { return new TclObject(new TclByteArray()); } /// <summary> Called to convert the other object's internal rep to a ByteArray. /// /// </summary> /// <param name="interp">current interpreter. /// </param> /// <param name="tobj">the TclObject to convert to use the ByteArray internal rep. /// </param> /// <exception cref=""> TclException if the object doesn't contain a valid ByteArray. /// </exception> internal static void setByteArrayFromAny(Interp interp, TclObject tobj) { IInternalRep rep = tobj.InternalRep; if (!(rep is TclByteArray)) { char[] c = tobj.ToString().ToCharArray(); tobj.InternalRep = new TclByteArray(c); } } /// <summary> /// This method changes the length of the byte array for this /// object. Once the caller has set the length of the array, it /// is acceptable to directly modify the bytes in the array up until /// Tcl_GetStringFromObj() has been called on this object. /// /// Results: /// The new byte array of the specified length. /// /// Side effects: /// Allocates enough memory for an array of bytes of the requested /// size. When growing the array, the old array is copied to the /// new array; new bytes are undefined. When shrinking, the /// old array is truncated to the specified length. /// </summary> public static byte[] SetLength(Interp interp, TclObject tobj, int length) { if (tobj.Shared) { throw new TclRuntimeError("TclByteArray.setLength() called with shared object"); } setByteArrayFromAny(interp, tobj); TclByteArray tbyteArray = (TclByteArray)tobj.InternalRep; if (length > tbyteArray.bytes.Length) { byte[] newBytes = new byte[length]; Array.Copy(tbyteArray.bytes, 0, newBytes, 0, tbyteArray.used); tbyteArray.bytes = newBytes; } tobj.invalidateStringRep(); tbyteArray.used = length; return tbyteArray.bytes; } /// <summary> Queries the length of the byte array. If tobj is not a byte array /// object, an attempt will be made to convert it to a byte array. /// /// </summary> /// <param name="interp">current interpreter. /// </param> /// <param name="tobj">the TclObject to use as a byte array. /// </param> /// <returns> the length of the byte array. /// </returns> /// <exception cref=""> TclException if tobj is not a valid byte array. /// </exception> public static int getLength(Interp interp, TclObject tobj) { setByteArrayFromAny(interp, tobj); TclByteArray tbyteArray = (TclByteArray)tobj.InternalRep; return tbyteArray.used; } /// <summary> Returns the bytes of a ByteArray object. If tobj is not a ByteArray /// object, an attempt will be made to convert it to a ByteArray. <p> /// /// </summary> /// <param name="interp">the current interpreter. /// </param> /// <param name="tobj">the byte array object. /// </param> /// <returns> a byte array. /// </returns> /// <exception cref=""> TclException if tobj is not a valid ByteArray. /// </exception> public static byte[] getBytes(Interp interp, TclObject tobj) { setByteArrayFromAny(interp, tobj); TclByteArray tbyteArray = (TclByteArray)tobj.InternalRep; return tbyteArray.bytes; } } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.3.12.3: Start resume simulation, relaible. COMPLETE /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(ClockTime))] public partial class StartResumeReliablePdu : SimulationManagementWithReliabilityFamilyPdu, IEquatable<StartResumeReliablePdu> { /// <summary> /// time in real world for this operation to happen /// </summary> private ClockTime _realWorldTime = new ClockTime(); /// <summary> /// time in simulation for the simulation to resume /// </summary> private ClockTime _simulationTime = new ClockTime(); /// <summary> /// level of reliability service used for this transaction /// </summary> private byte _requiredReliabilityService; /// <summary> /// padding /// </summary> private ushort _pad1; /// <summary> /// padding /// </summary> private byte _pad2; /// <summary> /// Request ID /// </summary> private uint _requestID; /// <summary> /// Initializes a new instance of the <see cref="StartResumeReliablePdu"/> class. /// </summary> public StartResumeReliablePdu() { PduType = (byte)53; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(StartResumeReliablePdu left, StartResumeReliablePdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(StartResumeReliablePdu left, StartResumeReliablePdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += this._realWorldTime.GetMarshalledSize(); // this._realWorldTime marshalSize += this._simulationTime.GetMarshalledSize(); // this._simulationTime marshalSize += 1; // this._requiredReliabilityService marshalSize += 2; // this._pad1 marshalSize += 1; // this._pad2 marshalSize += 4; // this._requestID return marshalSize; } /// <summary> /// Gets or sets the time in real world for this operation to happen /// </summary> [XmlElement(Type = typeof(ClockTime), ElementName = "realWorldTime")] public ClockTime RealWorldTime { get { return this._realWorldTime; } set { this._realWorldTime = value; } } /// <summary> /// Gets or sets the time in simulation for the simulation to resume /// </summary> [XmlElement(Type = typeof(ClockTime), ElementName = "simulationTime")] public ClockTime SimulationTime { get { return this._simulationTime; } set { this._simulationTime = value; } } /// <summary> /// Gets or sets the level of reliability service used for this transaction /// </summary> [XmlElement(Type = typeof(byte), ElementName = "requiredReliabilityService")] public byte RequiredReliabilityService { get { return this._requiredReliabilityService; } set { this._requiredReliabilityService = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "pad1")] public ushort Pad1 { get { return this._pad1; } set { this._pad1 = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(byte), ElementName = "pad2")] public byte Pad2 { get { return this._pad2; } set { this._pad2 = value; } } /// <summary> /// Gets or sets the Request ID /// </summary> [XmlElement(Type = typeof(uint), ElementName = "requestID")] public uint RequestID { get { return this._requestID; } set { this._requestID = value; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { this._realWorldTime.Marshal(dos); this._simulationTime.Marshal(dos); dos.WriteUnsignedByte((byte)this._requiredReliabilityService); dos.WriteUnsignedShort((ushort)this._pad1); dos.WriteUnsignedByte((byte)this._pad2); dos.WriteUnsignedInt((uint)this._requestID); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._realWorldTime.Unmarshal(dis); this._simulationTime.Unmarshal(dis); this._requiredReliabilityService = dis.ReadUnsignedByte(); this._pad1 = dis.ReadUnsignedShort(); this._pad2 = dis.ReadUnsignedByte(); this._requestID = dis.ReadUnsignedInt(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<StartResumeReliablePdu>"); base.Reflection(sb); try { sb.AppendLine("<realWorldTime>"); this._realWorldTime.Reflection(sb); sb.AppendLine("</realWorldTime>"); sb.AppendLine("<simulationTime>"); this._simulationTime.Reflection(sb); sb.AppendLine("</simulationTime>"); sb.AppendLine("<requiredReliabilityService type=\"byte\">" + this._requiredReliabilityService.ToString(CultureInfo.InvariantCulture) + "</requiredReliabilityService>"); sb.AppendLine("<pad1 type=\"ushort\">" + this._pad1.ToString(CultureInfo.InvariantCulture) + "</pad1>"); sb.AppendLine("<pad2 type=\"byte\">" + this._pad2.ToString(CultureInfo.InvariantCulture) + "</pad2>"); sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>"); sb.AppendLine("</StartResumeReliablePdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as StartResumeReliablePdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(StartResumeReliablePdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (!this._realWorldTime.Equals(obj._realWorldTime)) { ivarsEqual = false; } if (!this._simulationTime.Equals(obj._simulationTime)) { ivarsEqual = false; } if (this._requiredReliabilityService != obj._requiredReliabilityService) { ivarsEqual = false; } if (this._pad1 != obj._pad1) { ivarsEqual = false; } if (this._pad2 != obj._pad2) { ivarsEqual = false; } if (this._requestID != obj._requestID) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._realWorldTime.GetHashCode(); result = GenerateHash(result) ^ this._simulationTime.GetHashCode(); result = GenerateHash(result) ^ this._requiredReliabilityService.GetHashCode(); result = GenerateHash(result) ^ this._pad1.GetHashCode(); result = GenerateHash(result) ^ this._pad2.GetHashCode(); result = GenerateHash(result) ^ this._requestID.GetHashCode(); return result; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Esent; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.SolutionSize; using Microsoft.Isam.Esent.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Storage { /// <summary> /// A service that enables storing and retrieving of information associated with solutions, /// projects or documents across runtime sessions. /// </summary> internal partial class PersistentStorageService : IPersistentStorageService { /// <summary> /// threshold to start to use esent (50MB) /// </summary> private const int SolutionSizeThreshold = 50 * 1024 * 1024; internal static readonly IPersistentStorage NoOpPersistentStorageInstance = new NoOpPersistentStorage(); private readonly IOptionService _optionService; private readonly SolutionSizeTracker _solutionSizeTracker; private readonly object _lookupAccessLock; private readonly Dictionary<string, AbstractPersistentStorage> _lookup; private readonly bool _testing; private string _lastSolutionPath; private SolutionId _primarySolutionId; private AbstractPersistentStorage _primarySolutionStorage; public PersistentStorageService( IOptionService optionService, SolutionSizeTracker solutionSizeTracker) { _optionService = optionService; _solutionSizeTracker = solutionSizeTracker; _lookupAccessLock = new object(); _lookup = new Dictionary<string, AbstractPersistentStorage>(); _lastSolutionPath = null; _primarySolutionId = null; _primarySolutionStorage = null; } public PersistentStorageService(IOptionService optionService, bool testing) : this(optionService) { _testing = true; } public PersistentStorageService(IOptionService optionService) : this(optionService, null) { } public IPersistentStorage GetStorage(Solution solution) { if (!ShouldUseEsent(solution)) { return NoOpPersistentStorageInstance; } // can't use cached information if (!string.Equals(solution.FilePath, _lastSolutionPath, StringComparison.OrdinalIgnoreCase)) { // check whether the solution actually exist on disk if (!File.Exists(solution.FilePath)) { return NoOpPersistentStorageInstance; } } // cache current result. _lastSolutionPath = solution.FilePath; // get working folder path var workingFolderPath = GetWorkingFolderPath(solution); if (workingFolderPath == null) { // we don't have place to save esent file. don't use esent return NoOpPersistentStorageInstance; } return GetStorage(solution, workingFolderPath); } private IPersistentStorage GetStorage(Solution solution, string workingFolderPath) { lock (_lookupAccessLock) { // see whether we have something we can use AbstractPersistentStorage storage; if (_lookup.TryGetValue(solution.FilePath, out storage)) { // previous attempt to create esent storage failed. if (storage == null && !SolutionSizeAboveThreshold(solution)) { return NoOpPersistentStorageInstance; } // everything seems right, use what we have if (storage?.WorkingFolderPath == workingFolderPath) { storage.AddRefUnsafe(); return storage; } } // either this is the first time, or working folder path has changed. // remove existing one _lookup.Remove(solution.FilePath); var dbFile = EsentPersistentStorage.GetDatabaseFile(workingFolderPath); if (!File.Exists(dbFile) && !SolutionSizeAboveThreshold(solution)) { _lookup.Add(solution.FilePath, storage); return NoOpPersistentStorageInstance; } // try create new one storage = TryCreateEsentStorage(workingFolderPath, solution.FilePath); _lookup.Add(solution.FilePath, storage); if (storage != null) { RegisterPrimarySolutionStorageIfNeeded(solution, storage); storage.AddRefUnsafe(); return storage; } return NoOpPersistentStorageInstance; } } private bool ShouldUseEsent(Solution solution) { if (_testing) { return true; } // we only use esent for primary solution. (Ex, forked solution will not use esent) if (solution.BranchId != solution.Workspace.PrimaryBranchId || solution.FilePath == null) { return false; } return true; } private bool SolutionSizeAboveThreshold(Solution solution) { if (_testing) { return true; } if (_solutionSizeTracker == null) { return false; } var size = _solutionSizeTracker.GetSolutionSize(solution.Workspace, solution.Id); return size > SolutionSizeThreshold; } private void RegisterPrimarySolutionStorageIfNeeded(Solution solution, AbstractPersistentStorage storage) { if (_primarySolutionStorage != null || solution.Id != _primarySolutionId) { return; } // hold onto the primary solution when it is used the first time. _primarySolutionStorage = storage; storage.AddRefUnsafe(); } private string GetWorkingFolderPath(Solution solution) { if (_testing) { return Path.Combine(Path.GetDirectoryName(solution.FilePath), ".vs", Path.GetFileNameWithoutExtension(solution.FilePath)); } var locationService = solution.Workspace.Services.GetService<IPersistentStorageLocationService>(); return locationService?.GetStorageLocation(solution); } private AbstractPersistentStorage TryCreateEsentStorage(string workingFolderPath, string solutionPath) { AbstractPersistentStorage esentStorage; if (TryCreateEsentStorage(workingFolderPath, solutionPath, out esentStorage)) { return esentStorage; } // first attempt could fail if there was something wrong with existing esent db. // try one more time in case the first attempt fixed the problem. if (TryCreateEsentStorage(workingFolderPath, solutionPath, out esentStorage)) { return esentStorage; } // okay, can't recover, then use no op persistent service // so that things works old way (cache everything in memory) return null; } private bool TryCreateEsentStorage(string workingFolderPath, string solutionPath, out AbstractPersistentStorage esentStorage) { esentStorage = null; EsentPersistentStorage esent = null; try { esent = new EsentPersistentStorage(_optionService, workingFolderPath, solutionPath, this.Release); esent.Initialize(); esentStorage = esent; return true; } catch (EsentAccessDeniedException ex) { // esent db is already in use by someone. if (esent != null) { esent.Close(); } EsentLogger.LogException(ex); return false; } catch (Exception ex) { if (esent != null) { esent.Close(); } EsentLogger.LogException(ex); } try { if (esent != null) { Directory.Delete(esent.EsentDirectory, recursive: true); } } catch { // somehow, we couldn't delete the directory. } return false; } private void Release(AbstractPersistentStorage storage) { lock (_lookupAccessLock) { if (storage.ReleaseRefUnsafe()) { _lookup.Remove(storage.SolutionFilePath); storage.Close(); } } } public void RegisterPrimarySolution(SolutionId solutionId) { // don't create esent storage file right away. it will be // created when first C#/VB project is added lock (_lookupAccessLock) { Contract.ThrowIfTrue(_primarySolutionStorage != null); // just reset solutionId as long as there is no storage has created. _primarySolutionId = solutionId; } } public void UnregisterPrimarySolution(SolutionId solutionId, bool synchronousShutdown) { AbstractPersistentStorage storage = null; lock (_lookupAccessLock) { if (_primarySolutionId == null) { // primary solution is never registered or already unregistered Contract.ThrowIfTrue(_primarySolutionStorage != null); return; } Contract.ThrowIfFalse(_primarySolutionId == solutionId); _primarySolutionId = null; if (_primarySolutionStorage == null) { // primary solution is registered but no C#/VB project was added return; } storage = _primarySolutionStorage; _primarySolutionStorage = null; } if (storage != null) { if (synchronousShutdown) { // dispose storage outside of the lock storage.Dispose(); } else { // make it to shutdown asynchronously Task.Run(() => storage.Dispose()); } } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Windows.Controls.Primitives; // IItemContainerGenerator using System.Windows.Documents; using System.Windows.Media; using System.Windows.Markup; // IAddChild, ContentPropertyAttribute using System.Windows.Threading; using MS.Internal; using MS.Internal.Controls; using MS.Internal.KnownBoxes; using MS.Internal.PresentationFramework; using MS.Utility; namespace System.Windows.Controls { /// <summary> /// Base class for all layout panels. /// </summary> [Localizability(LocalizationCategory.Ignore)] [ContentProperty("Children")] public abstract class Panel : FrameworkElement, IAddChild { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Default DependencyObject constructor /// </summary> /// <remarks> /// Automatic determination of current Dispatcher. Use alternative constructor /// that accepts a Dispatcher for best performance. /// </remarks> protected Panel() : base() { _zConsonant = (int)ZIndexProperty.GetDefaultValue(DependencyObjectType); } #endregion //------------------------------------------------------------------- // // Public Methods // //------------------------------------------------------------------- #region Public Methods /// <summary> /// Fills in the background based on the Background property. /// </summary> protected override void OnRender(DrawingContext dc) { Brush background = Background; if (background != null) { // Using the Background brush, draw a rectangle that fills the // render bounds of the panel. Size renderSize = RenderSize; dc.DrawRectangle(background, null, new Rect(0.0, 0.0, renderSize.Width, renderSize.Height)); } } ///<summary> /// This method is called to Add the object as a child of the Panel. This method is used primarily /// by the parser. ///</summary> ///<param name="value"> /// The object to add as a child; it must be a UIElement. ///</param> /// <ExternalAPI/> void IAddChild.AddChild (Object value) { if (value == null) { throw new ArgumentNullException("value"); } if(IsItemsHost) { throw new InvalidOperationException(SR.Get(SRID.Panel_BoundPanel_NoChildren)); } UIElement uie = value as UIElement; if (uie == null) { throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(UIElement)), "value"); } Children.Add(uie); } ///<summary> /// This method is called by the parser when text appears under the tag in markup. /// As default Panels do not support text, calling this method has no effect. ///</summary> ///<param name="text"> /// Text to add as a child. ///</param> void IAddChild.AddText (string text) { XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this); } #endregion //------------------------------------------------------------------- // // Public Properties + Avalon Dependency ID's // //------------------------------------------------------------------- #region Public Properties /// <summary> /// The Background property defines the brush used to fill the area between borders. /// </summary> public Brush Background { get { return (Brush) GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// DependencyProperty for <see cref="Background" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(Brush), typeof(Panel), new FrameworkPropertyMetadata((Brush)null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender)); /// <summary> /// Returns enumerator to logical children. /// </summary> protected internal override IEnumerator LogicalChildren { get { if ((this.VisualChildrenCount == 0) || IsItemsHost) { // empty panel or a panel being used as the items // host has *no* logical children; give empty enumerator return EmptyEnumerator.Instance; } // otherwise, its logical children is its visual children return this.Children.GetEnumerator(); } } /// <summary> /// Returns a UIElementCollection of children for user to add/remove children manually /// Returns read-only collection if Panel is data-bound (no manual control of children is possible, /// the associated ItemsControl completely overrides children) /// Note: the derived Panel classes should never use this collection for /// internal purposes like in their MeasureOverride or ArrangeOverride. /// They should use InternalChildren instead, because InternalChildren /// is always present and either is a mirror of public Children collection (in case of Direct Panel) /// or is generated from data binding. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public UIElementCollection Children { get { //When we will change from UIElementCollection to IList<UIElement>, we might //consider returning a wrapper IList here which coudl be read-only for mutating methods //while INternalChildren could be R/W even in case of Generator attached. return InternalChildren; } } /// <summary> /// This method is used by TypeDescriptor to determine if this property should /// be serialized. /// </summary> // Should serialize property Children only if it is non empty [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeChildren() { if (!IsItemsHost) { if (Children != null && Children.Count > 0) { return true; } } return false; } /// <summary> /// The DependencyProperty for the IsItemsHost property. /// Flags: NotDataBindable /// Default Value: false /// </summary> public static readonly DependencyProperty IsItemsHostProperty = DependencyProperty.Register( "IsItemsHost", typeof(bool), typeof(Panel), new FrameworkPropertyMetadata( BooleanBoxes.FalseBox, // defaultValue FrameworkPropertyMetadataOptions.NotDataBindable, new PropertyChangedCallback(OnIsItemsHostChanged))); /// <summary> /// IsItemsHost is set to true to indicate that the panel /// is the container for UI generated for the items of an /// ItemsControl. It is typically set in a style for an ItemsControl. /// </summary> [Bindable(false), Category("Behavior")] public bool IsItemsHost { get { return (bool) GetValue(IsItemsHostProperty); } set { SetValue(IsItemsHostProperty, BooleanBoxes.Box(value)); } } private static void OnIsItemsHostChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Panel panel = (Panel) d; panel.OnIsItemsHostChanged((bool) e.OldValue, (bool) e.NewValue); } /// <summary> /// This method is invoked when the IsItemsHost property changes. /// </summary> /// <param name="oldIsItemsHost">The old value of the IsItemsHost property.</param> /// <param name="newIsItemsHost">The new value of the IsItemsHost property.</param> protected virtual void OnIsItemsHostChanged(bool oldIsItemsHost, bool newIsItemsHost) { // GetItemsOwner will check IsItemsHost first, so we don't have // to check that IsItemsHost == true before calling it. DependencyObject parent = ItemsControl.GetItemsOwnerInternal(this); ItemsControl itemsControl = parent as ItemsControl; Panel oldItemsHost = null; if (itemsControl != null) { // ItemsHost should be the "root" element which has // IsItemsHost = true on it. In the case of grouping, // IsItemsHost is true on all panels which are generating // content. Thus, we care only about the panel which // is generating content for the ItemsControl. IItemContainerGenerator generator = itemsControl.ItemContainerGenerator as IItemContainerGenerator; if (generator != null && generator == generator.GetItemContainerGeneratorForPanel(this)) { oldItemsHost = itemsControl.ItemsHost; itemsControl.ItemsHost = this; } } else { GroupItem groupItem = parent as GroupItem; if (groupItem != null) { IItemContainerGenerator generator = groupItem.Generator as IItemContainerGenerator; if (generator != null && generator == generator.GetItemContainerGeneratorForPanel(this)) { oldItemsHost = groupItem.ItemsHost; groupItem.ItemsHost = this; } } } if (oldItemsHost != null && oldItemsHost != this) { // when changing ItemsHost panels, disconnect the old one oldItemsHost.VerifyBoundState(); } VerifyBoundState(); } /// <summary> /// This is the public accessor for protected property LogicalOrientation. /// </summary> public Orientation LogicalOrientationPublic { get { return LogicalOrientation; } } /// <summary> /// Orientation of the panel if its layout is in one dimension. /// Otherwise HasLogicalOrientation is false and LogicalOrientation should be ignored /// </summary> protected internal virtual Orientation LogicalOrientation { get { return Orientation.Vertical; } } /// <summary> /// This is the public accessor for protected property HasLogicalOrientation. /// </summary> public bool HasLogicalOrientationPublic { get { return HasLogicalOrientation; } } /// <summary> /// HasLogicalOrientation is true in case the panel layout is only one dimension (Stack panel). /// </summary> protected internal virtual bool HasLogicalOrientation { get { return false; } } #endregion #region Protected Methods /// <summary> /// Returns a UIElementCollection of children - added by user or generated from data binding. /// Panel-derived classes should use this collection for all internal purposes, including /// MeasureOverride/ArrangeOverride overrides. /// </summary> protected internal UIElementCollection InternalChildren { get { VerifyBoundState(); if (IsItemsHost) { EnsureGenerator(); } else { if (_uiElementCollection == null) { // First access on a regular panel EnsureEmptyChildren(/* logicalParent = */ this); } } return _uiElementCollection; } } /// <summary> /// Gets the Visual children count. /// </summary> protected override int VisualChildrenCount { get { if (_uiElementCollection == null) { return 0; } else { return _uiElementCollection.Count; } } } /// <summary> /// Gets the Visual child at the specified index. /// </summary> protected override Visual GetVisualChild(int index) { if (_uiElementCollection == null) { throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } if (IsZStateDirty) { RecomputeZState(); } int visualIndex = _zLut != null ? _zLut[index] : index; return _uiElementCollection[visualIndex]; } /// <summary> /// Creates a new UIElementCollection. Panel-derived class can create its own version of /// UIElementCollection -derived class to add cached information to every child or to /// intercept any Add/Remove actions (for example, for incremental layout update) /// </summary> protected virtual UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent) { return new UIElementCollection(this, logicalParent); } /// <summary> /// The generator associated with this panel. /// </summary> internal IItemContainerGenerator Generator { get { return _itemContainerGenerator; } } #endregion #region Internal Properties // // Bool field used by VirtualizingStackPanel // internal bool VSP_IsVirtualizing { get { return GetBoolField(BoolField.IsVirtualizing); } set { SetBoolField(BoolField.IsVirtualizing, value); } } // // Bool field used by VirtualizingStackPanel // internal bool VSP_HasMeasured { get { return GetBoolField(BoolField.HasMeasured); } set { SetBoolField(BoolField.HasMeasured, value); } } // // Bool field used by VirtualizingStackPanel // internal bool VSP_MustDisableVirtualization { get { return GetBoolField(BoolField.MustDisableVirtualization); } set { SetBoolField(BoolField.MustDisableVirtualization, value); } } // // Bool field used by VirtualizingStackPanel // internal bool VSP_IsPixelBased { get { return GetBoolField(BoolField.IsPixelBased); } set { SetBoolField(BoolField.IsPixelBased, value); } } // // Bool field used by VirtualizingStackPanel // internal bool VSP_InRecyclingMode { get { return GetBoolField(BoolField.InRecyclingMode); } set { SetBoolField(BoolField.InRecyclingMode, value); } } // // Bool field used by VirtualizingStackPanel // internal bool VSP_MeasureCaches { get { return GetBoolField(BoolField.MeasureCaches); } set { SetBoolField(BoolField.MeasureCaches, value); } } #endregion #region Private Methods private bool VerifyBoundState() { // If the panel becomes "unbound" while attached to a generator, this // method detaches it and makes it really behave like "unbound." This // can happen because of a style change, a theme change, etc. It returns // the correct "bound" state, after the dust has settled. // // This is really a workaround for a more general problem that the panel // needs to release resources (an event handler) when it is "out of the tree." // Currently, there is no good notification for when this happens. bool isItemsHost = (ItemsControl.GetItemsOwnerInternal(this) != null); if (isItemsHost) { if (_itemContainerGenerator == null) { // Transitioning from being unbound to bound ClearChildren(); } return (_itemContainerGenerator != null); } else { if (_itemContainerGenerator != null) { // Transitioning from being bound to unbound DisconnectFromGenerator(); ClearChildren(); } return false; } } //"actually data-bound and using generator" This is true if Panel is //not only marked as IsItemsHost but actually has requested Generator to //generate items and thus "owns" those items. //In this case, Children collection becomes read-only //Cases when it is not true include "direct" usage - IsItemsHost=false and //usages when panel is data-bound but derived class avoid accessing InternalChildren or Children //and rather calls CreateUIElementCollection and then drives Generator itself. internal bool IsDataBound { get { return IsItemsHost && _itemContainerGenerator != null; } } /// <summary> Used by subclasses to decide whether to call through a profiling stub </summary> internal static bool IsAboutToGenerateContent(Panel panel) { return panel.IsItemsHost && panel._itemContainerGenerator == null; } private void ConnectToGenerator() { Debug.Assert(_itemContainerGenerator == null, "Attempted to connect to a generator when Panel._itemContainerGenerator is non-null."); ItemsControl itemsOwner = ItemsControl.GetItemsOwner(this); if (itemsOwner == null) { // This can happen if IsItemsHost=true, but the panel is not nested in an ItemsControl throw new InvalidOperationException(SR.Get(SRID.Panel_ItemsControlNotFound)); } IItemContainerGenerator itemsOwnerGenerator = itemsOwner.ItemContainerGenerator; if (itemsOwnerGenerator != null) { _itemContainerGenerator = itemsOwnerGenerator.GetItemContainerGeneratorForPanel(this); if (_itemContainerGenerator != null) { _itemContainerGenerator.ItemsChanged += new ItemsChangedEventHandler(OnItemsChanged); ((IItemContainerGenerator)_itemContainerGenerator).RemoveAll(); } } } private void DisconnectFromGenerator() { Debug.Assert(_itemContainerGenerator != null, "Attempted to disconnect from a generator when Panel._itemContainerGenerator is null."); _itemContainerGenerator.ItemsChanged -= new ItemsChangedEventHandler(OnItemsChanged); ((IItemContainerGenerator)_itemContainerGenerator).RemoveAll(); _itemContainerGenerator = null; } private void EnsureEmptyChildren(FrameworkElement logicalParent) { if ((_uiElementCollection == null) || (_uiElementCollection.LogicalParent != logicalParent)) { _uiElementCollection = CreateUIElementCollection(logicalParent); } else { ClearChildren(); } } internal void EnsureGenerator() { Debug.Assert(IsItemsHost, "Should be invoked only on an ItemsHost panel"); if (_itemContainerGenerator == null) { // First access on an items presenter panel ConnectToGenerator(); // Children of this panel should not have their logical parent reset EnsureEmptyChildren(/* logicalParent = */ null); GenerateChildren(); } } private void ClearChildren() { if (_itemContainerGenerator != null) { ((IItemContainerGenerator)_itemContainerGenerator).RemoveAll(); } if ((_uiElementCollection != null) && (_uiElementCollection.Count > 0)) { _uiElementCollection.ClearInternal(); OnClearChildrenInternal(); } } internal virtual void OnClearChildrenInternal() { } internal virtual void GenerateChildren() { // This method is typically called during layout, which suspends the dispatcher. // Firing an assert causes an exception "Dispatcher processing has been suspended, but messages are still being processed." // Besides, the asserted condition can actually arise in practice, and the // code responds harmlessly. //Debug.Assert(_itemContainerGenerator != null, "Encountered a null _itemContainerGenerator while being asked to generate children."); IItemContainerGenerator generator = (IItemContainerGenerator)_itemContainerGenerator; if (generator != null) { using (generator.StartAt(new GeneratorPosition(-1, 0), GeneratorDirection.Forward)) { UIElement child; while ((child = generator.GenerateNext() as UIElement) != null) { _uiElementCollection.AddInternal(child); generator.PrepareItemContainer(child); } } } } private void OnItemsChanged(object sender, ItemsChangedEventArgs args) { if (VerifyBoundState()) { Debug.Assert(_itemContainerGenerator != null, "Encountered a null _itemContainerGenerator while receiving an ItemsChanged from a generator."); bool affectsLayout = OnItemsChangedInternal(sender, args); if (affectsLayout) { InvalidateMeasure(); } } } // This method returns a bool to indicate if or not the panel layout is affected by this collection change internal virtual bool OnItemsChangedInternal(object sender, ItemsChangedEventArgs args) { switch (args.Action) { case NotifyCollectionChangedAction.Add: AddChildren(args.Position, args.ItemCount); break; case NotifyCollectionChangedAction.Remove: RemoveChildren(args.Position, args.ItemUICount); break; case NotifyCollectionChangedAction.Replace: ReplaceChildren(args.Position, args.ItemCount, args.ItemUICount); break; case NotifyCollectionChangedAction.Move: MoveChildren(args.OldPosition, args.Position, args.ItemUICount); break; case NotifyCollectionChangedAction.Reset: ResetChildren(); break; } return true; } private void AddChildren(GeneratorPosition pos, int itemCount) { Debug.Assert(_itemContainerGenerator != null, "Encountered a null _itemContainerGenerator while receiving an Add action from a generator."); IItemContainerGenerator generator = (IItemContainerGenerator)_itemContainerGenerator; using (generator.StartAt(pos, GeneratorDirection.Forward)) { for (int i = 0; i < itemCount; i++) { UIElement e = generator.GenerateNext() as UIElement; if(e != null) { _uiElementCollection.InsertInternal(pos.Index + 1 + i, e); generator.PrepareItemContainer(e); } else { _itemContainerGenerator.Verify(); } } } } private void RemoveChildren(GeneratorPosition pos, int containerCount) { // If anything is wrong, I think these collections should do parameter checking _uiElementCollection.RemoveRangeInternal(pos.Index, containerCount); } private void ReplaceChildren(GeneratorPosition pos, int itemCount, int containerCount) { Debug.Assert(itemCount == containerCount, "Panel expects Replace to affect only realized containers"); Debug.Assert(_itemContainerGenerator != null, "Encountered a null _itemContainerGenerator while receiving an Replace action from a generator."); IItemContainerGenerator generator = (IItemContainerGenerator)_itemContainerGenerator; using (generator.StartAt(pos, GeneratorDirection.Forward, true)) { for (int i = 0; i < itemCount; i++) { bool isNewlyRealized; UIElement e = generator.GenerateNext(out isNewlyRealized) as UIElement; Debug.Assert(e != null && !isNewlyRealized, "Panel expects Replace to affect only realized containers"); if(e != null && !isNewlyRealized) { _uiElementCollection.SetInternal(pos.Index + i, e); generator.PrepareItemContainer(e); } else { _itemContainerGenerator.Verify(); } } } } private void MoveChildren(GeneratorPosition fromPos, GeneratorPosition toPos, int containerCount) { if (fromPos == toPos) return; Debug.Assert(_itemContainerGenerator != null, "Encountered a null _itemContainerGenerator while receiving an Move action from a generator."); IItemContainerGenerator generator = (IItemContainerGenerator)_itemContainerGenerator; int toIndex = generator.IndexFromGeneratorPosition(toPos); UIElement[] elements = new UIElement[containerCount]; for (int i = 0; i < containerCount; i++) elements[i] = _uiElementCollection[fromPos.Index + i]; _uiElementCollection.RemoveRangeInternal(fromPos.Index, containerCount); for (int i = 0; i < containerCount; i++) { _uiElementCollection.InsertInternal(toIndex + i, elements[i]); } } private void ResetChildren() { EnsureEmptyChildren(null); GenerateChildren(); } private bool GetBoolField(BoolField field) { return (_boolFieldStore & field) != 0; } private void SetBoolField(BoolField field, bool value) { if (value) { _boolFieldStore |= field; } else { _boolFieldStore &= (~field); } } // // This property // 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject // 2. This is a performance optimization // internal override int EffectiveValuesInitialSize { get { return 9; } } #endregion //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields [System.Flags] private enum BoolField : byte { IsZStateDirty = 0x01, // "1" when Z state needs to be recomputed IsZStateDiverse = 0x02, // "1" when children have different ZIndexProperty values IsVirtualizing = 0x04, // Used by VirtualizingStackPanel HasMeasured = 0x08, // Used by VirtualizingStackPanel IsPixelBased = 0x10, // Used by VirtualizingStackPanel InRecyclingMode = 0x20, // Used by VirtualizingStackPanel MustDisableVirtualization = 0x40, // Used by VirtualizingStackPanel MeasureCaches = 0x80, // Used by VirtualizingStackPanel } private UIElementCollection _uiElementCollection; private ItemContainerGenerator _itemContainerGenerator; private BoolField _boolFieldStore; private const int c_zDefaultValue = 0; // default ZIndexProperty value private int _zConsonant; // iff (_boolFieldStore.IsZStateDiverse == 0) then this is the value all children have private int[] _zLut; // look up table for converting from logical to visual indices #endregion Private Fields #region ZIndex Support /// <summary> /// <see cref="Visual.OnVisualChildrenChanged"/> /// </summary> protected internal override void OnVisualChildrenChanged( DependencyObject visualAdded, DependencyObject visualRemoved) { if (!IsZStateDirty) { if (IsZStateDiverse) { // if children have different ZIndex values, // then _zLut have to be recomputed IsZStateDirty = true; } else if (visualAdded != null) { // if current children have consonant ZIndex values, // then _zLut have to be recomputed, only if the new // child makes z state diverse int zNew = (int)visualAdded.GetValue(ZIndexProperty); if (zNew != _zConsonant) { IsZStateDirty = true; } } } base.OnVisualChildrenChanged(visualAdded, visualRemoved); // Recompute the zLut array and invalidate children rendering order. if (IsZStateDirty) { RecomputeZState(); InvalidateZState(); } } /// <summary> /// ZIndex property is an attached property. Panel reads it to alter the order /// of children rendering. Children with greater values will be rendered on top of /// children with lesser values. /// In case of two children with the same ZIndex property value, order of rendering /// is determined by their order in Panel.Children collection. /// </summary> public static readonly DependencyProperty ZIndexProperty = DependencyProperty.RegisterAttached( "ZIndex", typeof(int), typeof(Panel), new FrameworkPropertyMetadata( c_zDefaultValue, new PropertyChangedCallback(OnZIndexPropertyChanged))); /// <summary> /// Helper for setting ZIndex property on a UIElement. /// </summary> /// <param name="element">UIElement to set ZIndex property on.</param> /// <param name="value">ZIndex property value.</param> public static void SetZIndex(UIElement element, int value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(ZIndexProperty, value); } /// <summary> /// Helper for reading ZIndex property from a UIElement. /// </summary> /// <param name="element">UIElement to read ZIndex property from.</param> /// <returns>ZIndex property value.</returns> public static int GetZIndex(UIElement element) { if (element == null) { throw new ArgumentNullException("element"); } return ((int)element.GetValue(ZIndexProperty)); } /// <summary> /// <see cref="PropertyMetadata.PropertyChangedCallback"/> /// </summary> private static void OnZIndexPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { int oldValue = (int)e.OldValue; int newValue = (int)e.NewValue; if (oldValue == newValue) return; UIElement child = d as UIElement; if (child == null) return; Panel panel = child.InternalVisualParent as Panel; if (panel == null) return; panel.InvalidateZState(); } /// <summary> /// Sets the Z state to be dirty /// </summary> internal void InvalidateZState() { if (!IsZStateDirty && _uiElementCollection != null) { InvalidateZOrder(); } IsZStateDirty = true; } private bool IsZStateDirty { get { return GetBoolField(BoolField.IsZStateDirty); } set { SetBoolField(BoolField.IsZStateDirty, value); } } private bool IsZStateDiverse { get { return GetBoolField(BoolField.IsZStateDiverse); } set { SetBoolField(BoolField.IsZStateDiverse, value); } } // Helper method to update this panel's state related to children rendering order handling private void RecomputeZState() { int count = (_uiElementCollection != null) ? _uiElementCollection.Count : 0; bool isDiverse = false; bool lutRequired = false; int zIndexDefaultValue = (int)ZIndexProperty.GetDefaultValue(DependencyObjectType); int consonant = zIndexDefaultValue; System.Collections.Generic.List<Int64> stableKeyValues = null; if (count > 0) { if (_uiElementCollection[0] != null) { consonant = (int)_uiElementCollection[0].GetValue(ZIndexProperty); } if (count > 1) { stableKeyValues = new System.Collections.Generic.List<Int64>(count); stableKeyValues.Add((Int64)consonant << 32); int prevZ = consonant; int i = 1; do { int z = _uiElementCollection[i] != null ? (int)_uiElementCollection[i].GetValue(ZIndexProperty) : zIndexDefaultValue; // this way of calculating values of stableKeyValues required to // 1) workaround the fact that Array.Sort is not stable (does not preserve the original // order of elements if the keys are equal) // 2) avoid O(N^2) performance of Array.Sort, which is QuickSort, which is known to become O(N^2) // on sorting N eqial keys stableKeyValues.Add(((Int64)z << 32) + i); // look-up-table is required iff z's are not monotonically increasing function of index. // in other words if stableKeyValues[i] >= stableKeyValues[i-1] then calculated look-up-table // is guaranteed to be degenerated... lutRequired |= z < prevZ; prevZ = z; isDiverse |= (z != consonant); } while (++i < count); } } if (lutRequired) { stableKeyValues.Sort(); if (_zLut == null || _zLut.Length != count) { _zLut = new int[count]; } for (int i = 0; i < count; ++i) { _zLut[i] = (int)(stableKeyValues[i] & 0xffffffff); } } else { _zLut = null; } IsZStateDiverse = isDiverse; _zConsonant = consonant; IsZStateDirty = false; } #endregion ZIndex Support } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Xml; namespace Memento.Core.Converter { internal static class HtmlCssParser { // ................................................................. // // Processing CSS Attributes // // ................................................................. internal static void GetElementPropertiesFromCssAttributes(XmlElement htmlElement, string elementName, CssStylesheet stylesheet, Hashtable localProperties, List<XmlElement> sourceContext) { string styleFromStylesheet = stylesheet.GetStyle(elementName, sourceContext); string styleInline = HtmlToXamlConverter.GetAttribute(htmlElement, "style"); // Combine styles from stylesheet and from inline attribute. // The order is important - the latter styles will override the former. string style = styleFromStylesheet != null ? styleFromStylesheet : null; if (styleInline != null) { style = style == null ? styleInline : (style + ";" + styleInline); } // Apply local style to current formatting properties if (style != null) { string[] styleValues = style.Split(';'); for (int i = 0; i < styleValues.Length; i++) { string[] styleNameValue; styleNameValue = styleValues[i].Split(':'); if (styleNameValue.Length == 2) { string styleName = styleNameValue[0].Trim().ToLower(); string styleValue = HtmlToXamlConverter.UnQuote(styleNameValue[1].Trim()).ToLower(); int nextIndex = 0; switch (styleName) { case "font": ParseCssFont(styleValue, localProperties); break; case "font-family": ParseCssFontFamily(styleValue, ref nextIndex, localProperties); break; case "font-size": ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); break; case "font-style": ParseCssFontStyle(styleValue, ref nextIndex, localProperties); break; case "font-weight": ParseCssFontWeight(styleValue, ref nextIndex, localProperties); break; case "font-variant": ParseCssFontVariant(styleValue, ref nextIndex, localProperties); break; case "line-height": ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); break; case "word-spacing": // Implement word-spacing conversion break; case "letter-spacing": // Implement letter-spacing conversion break; case "color": ParseCssColor(styleValue, ref nextIndex, localProperties, "color"); break; case "text-decoration": ParseCssTextDecoration(styleValue, ref nextIndex, localProperties); break; case "text-transform": ParseCssTextTransform(styleValue, ref nextIndex, localProperties); break; case "background-color": ParseCssColor(styleValue, ref nextIndex, localProperties, "background-color"); break; case "background": // TODO: need to parse composite background property ParseCssBackground(styleValue, ref nextIndex, localProperties); break; case "text-align": ParseCssTextAlign(styleValue, ref nextIndex, localProperties); break; case "vertical-align": ParseCssVerticalAlign(styleValue, ref nextIndex, localProperties); break; case "text-indent": ParseCssSize(styleValue, ref nextIndex, localProperties, "text-indent", /*mustBeNonNegative:*/false); break; case "width": case "height": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "margin": // top/right/bottom/left ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "margin-top": case "margin-right": case "margin-bottom": case "margin-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "padding": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "padding-top": case "padding-right": case "padding-bottom": case "padding-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "border": ParseCssBorder(styleValue, ref nextIndex, localProperties); break; case "border-style": case "border-width": case "border-color": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "border-top": case "border-right": case "border-left": case "border-bottom": // Parse css border style break; // NOTE: css names for elementary border styles have side indications in the middle (top/bottom/left/right) // In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method case "border-top-style": case "border-right-style": case "border-left-style": case "border-bottom-style": case "border-top-color": case "border-right-color": case "border-left-color": case "border-bottom-color": case "border-top-width": case "border-right-width": case "border-left-width": case "border-bottom-width": // Parse css border style break; case "display": // Implement display style conversion break; case "float": ParseCssFloat(styleValue, ref nextIndex, localProperties); break; case "clear": ParseCssClear(styleValue, ref nextIndex, localProperties); break; default: break; } } } } } // ................................................................. // // Parsing CSS - Lexical Helpers // // ................................................................. // Skips whitespaces in style values private static void ParseWhiteSpace(string styleValue, ref int nextIndex) { while (nextIndex < styleValue.Length && Char.IsWhiteSpace(styleValue[nextIndex])) { nextIndex++; } } // Checks if the following character matches to a given word and advances nextIndex // by the word's length in case of success. // Otherwise leaves nextIndex in place (except for possible whitespaces). // Returns true or false depending on success or failure of matching. private static bool ParseWord(string word, string styleValue, ref int nextIndex) { ParseWhiteSpace(styleValue, ref nextIndex); for (int i = 0; i < word.Length; i++) { if (!(nextIndex + i < styleValue.Length && word[i] == styleValue[nextIndex + i])) { return false; } } if (nextIndex + word.Length < styleValue.Length && Char.IsLetterOrDigit(styleValue[nextIndex + word.Length])) { return false; } nextIndex += word.Length; return true; } // CHecks whether the following character sequence matches to one of the given words, // and advances the nextIndex to matched word length. // Returns null in case if there is no match or the word matched. private static string ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex) { for (int i = 0; i < words.Length; i++) { if (ParseWord(words[i], styleValue, ref nextIndex)) { return words[i]; } } return null; } private static void ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex, Hashtable localProperties, string attributeName) { string attributeValue = ParseWordEnumeration(words, styleValue, ref nextIndex); if (attributeValue != null) { localProperties[attributeName] = attributeValue; } } private static string ParseCssSize(string styleValue, ref int nextIndex, bool mustBeNonNegative) { ParseWhiteSpace(styleValue, ref nextIndex); int startIndex = nextIndex; // Parse optional munis sign if (nextIndex < styleValue.Length && styleValue[nextIndex] == '-') { nextIndex++; } if (nextIndex < styleValue.Length && Char.IsDigit(styleValue[nextIndex])) { while (nextIndex < styleValue.Length && (Char.IsDigit(styleValue[nextIndex]) || styleValue[nextIndex] == '.')) { nextIndex++; } string number = styleValue.Substring(startIndex, nextIndex - startIndex); string unit = ParseWordEnumeration(_fontSizeUnits, styleValue, ref nextIndex); if (unit == null) { unit = "px"; // Assuming pixels by default } if (mustBeNonNegative && styleValue[startIndex] == '-') { return "0"; } else { return number + unit; } } return null; } private static void ParseCssSize(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName, bool mustBeNonNegative) { string length = ParseCssSize(styleValue, ref nextIndex, mustBeNonNegative); if (length != null) { localValues[propertyName] = length; } } private static readonly string[] _colors = new string[] { "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen", }; private static readonly string[] _systemColors = new string[] { "activeborder", "activecaption", "appworkspace", "background", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "captiontext", "graytext", "highlight", "highlighttext", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infobackground", "infotext", "menu", "menutext", "scrollbar", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "window", "windowframe", "windowtext", }; private static string ParseCssColor(string styleValue, ref int nextIndex) { // Implement color parsing // rgb(100%,53.5%,10%) // rgb(255,91,26) // #FF5B1A // black | silver | gray | ... | aqua // transparent - for background-color ParseWhiteSpace(styleValue, ref nextIndex); string color = null; if (nextIndex < styleValue.Length) { int startIndex = nextIndex; char character = styleValue[nextIndex]; if (character == '#') { nextIndex++; while (nextIndex < styleValue.Length) { character = Char.ToUpper(styleValue[nextIndex]); if (!('0' <= character && character <= '9' || 'A' <= character && character <= 'F')) { break; } nextIndex++; } if (nextIndex > startIndex + 1) { color = styleValue.Substring(startIndex, nextIndex - startIndex); } } else if (styleValue.Substring(nextIndex, 3).ToLower() == "rbg") { // Implement real rgb() color parsing while (nextIndex < styleValue.Length && styleValue[nextIndex] != ')') { nextIndex++; } if (nextIndex < styleValue.Length) { nextIndex++; // to skip ')' } color = "gray"; // return bogus color } else if (Char.IsLetter(character)) { color = ParseWordEnumeration(_colors, styleValue, ref nextIndex); if (color == null) { color = ParseWordEnumeration(_systemColors, styleValue, ref nextIndex); if (color != null) { // Implement smarter system color converions into real colors color = "black"; } } } } return color; } private static void ParseCssColor(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName) { string color = ParseCssColor(styleValue, ref nextIndex); if (color != null) { localValues[propertyName] = color; } } // ................................................................. // // Pasring CSS font Property // // ................................................................. // CSS has five font properties: font-family, font-style, font-variant, font-weight, font-size. // An aggregated "font" property lets you specify in one action all the five in combination // with additional line-height property. // // font-family: [<family-name>,]* [<family-name> | <generic-family>] // generic-family: serif | sans-serif | monospace | cursive | fantasy // The list of families sets priorities to choose fonts; // Quotes not allowed around generic-family names // font-style: normal | italic | oblique // font-variant: normal | small-caps // font-weight: normal | bold | bolder | lighter | 100 ... 900 | // Default is "normal", normal==400 // font-size: <absolute-size> | <relative-size> | <length> | <percentage> // absolute-size: xx-small | x-small | small | medium | large | x-large | xx-large // relative-size: larger | smaller // length: <point> | <pica> | <ex> | <em> | <points> | <millimeters> | <centimeters> | <inches> // Default: medium // font: [ <font-style> || <font-variant> || <font-weight ]? <font-size> [ / <line-height> ]? <font-family> private static readonly string[] _fontGenericFamilies = new string[] { "serif", "sans-serif", "monospace", "cursive", "fantasy" }; private static readonly string[] _fontStyles = new string[] { "normal", "italic", "oblique" }; private static readonly string[] _fontVariants = new string[] { "normal", "small-caps" }; private static readonly string[] _fontWeights = new string[] { "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" }; private static readonly string[] _fontAbsoluteSizes = new string[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" }; private static readonly string[] _fontRelativeSizes = new string[] { "larger", "smaller" }; private static readonly string[] _fontSizeUnits = new string[] { "px", "mm", "cm", "in", "pt", "pc", "em", "ex", "%" }; // Parses CSS string fontStyle representing a value for css font attribute private static void ParseCssFont(string styleValue, Hashtable localProperties) { int nextIndex = 0; ParseCssFontStyle(styleValue, ref nextIndex, localProperties); ParseCssFontVariant(styleValue, ref nextIndex, localProperties); ParseCssFontWeight(styleValue, ref nextIndex, localProperties); ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == '/') { nextIndex++; ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); } ParseCssFontFamily(styleValue, ref nextIndex, localProperties); } private static void ParseCssFontStyle(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontStyles, styleValue, ref nextIndex, localProperties, "font-style"); } private static void ParseCssFontVariant(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontVariants, styleValue, ref nextIndex, localProperties, "font-variant"); } private static void ParseCssFontWeight(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontWeights, styleValue, ref nextIndex, localProperties, "font-weight"); } private static void ParseCssFontFamily(string styleValue, ref int nextIndex, Hashtable localProperties) { string fontFamilyList = null; while (nextIndex < styleValue.Length) { // Try generic-family string fontFamily = ParseWordEnumeration(_fontGenericFamilies, styleValue, ref nextIndex); if (fontFamily == null) { // Try quoted font family name if (nextIndex < styleValue.Length && (styleValue[nextIndex] == '"' || styleValue[nextIndex] == '\'')) { char quote = styleValue[nextIndex]; nextIndex++; int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != quote) { nextIndex++; } fontFamily = '"' + styleValue.Substring(startIndex, nextIndex - startIndex) + '"'; } if (fontFamily == null) { // Try unquoted font family name int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != ',' && styleValue[nextIndex] != ';') { nextIndex++; } if (nextIndex > startIndex) { fontFamily = styleValue.Substring(startIndex, nextIndex - startIndex).Trim(); if (fontFamily.Length == 0) { fontFamily = null; } } } } ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == ',') { nextIndex++; } if (fontFamily != null) { // css font-family can contein a list of names. We only consider the first name from the list. Need a decision what to do with remaining names // fontFamilyList = (fontFamilyList == null) ? fontFamily : fontFamilyList + "," + fontFamily; if (fontFamilyList == null && fontFamily.Length > 0) { if (fontFamily[0] == '"' || fontFamily[0] == '\'') { // Unquote the font family name fontFamily = fontFamily.Substring(1, fontFamily.Length - 2); } else { // Convert generic css family name } fontFamilyList = fontFamily; } } else { break; } } if (fontFamilyList != null) { localProperties["font-family"] = fontFamilyList; } } // ................................................................. // // Pasring CSS list-style Property // // ................................................................. // list-style: [ <list-style-type> || <list-style-position> || <list-style-image> ] private static readonly string[] _listStyleTypes = new string[] { "disc", "circle", "square", "decimal", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha", "none" }; private static readonly string[] _listStylePositions = new string[] { "inside", "outside" }; private static void ParseCssListStyle(string styleValue, Hashtable localProperties) { int nextIndex = 0; while (nextIndex < styleValue.Length) { string listStyleType = ParseCssListStyleType(styleValue, ref nextIndex); if (listStyleType != null) { localProperties["list-style-type"] = listStyleType; } else { string listStylePosition = ParseCssListStylePosition(styleValue, ref nextIndex); if (listStylePosition != null) { localProperties["list-style-position"] = listStylePosition; } else { string listStyleImage = ParseCssListStyleImage(styleValue, ref nextIndex); if (listStyleImage != null) { localProperties["list-style-image"] = listStyleImage; } else { // TODO: Process unrecognized list style value break; } } } } } private static string ParseCssListStyleType(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_listStyleTypes, styleValue, ref nextIndex); } private static string ParseCssListStylePosition(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_listStylePositions, styleValue, ref nextIndex); } private static string ParseCssListStyleImage(string styleValue, ref int nextIndex) { // TODO: Implement URL parsing for images return null; } // ................................................................. // // Pasring CSS text-decorations Property // // ................................................................. private static readonly string[] _textDecorations = new string[] { "none", "underline", "overline", "line-through", "blink" }; private static void ParseCssTextDecoration(string styleValue, ref int nextIndex, Hashtable localProperties) { // Set default text-decorations:none; for (int i = 1; i < _textDecorations.Length; i++) { localProperties["text-decoration-" + _textDecorations[i]] = "false"; } // Parse list of decorations values while (nextIndex < styleValue.Length) { string decoration = ParseWordEnumeration(_textDecorations, styleValue, ref nextIndex); if (decoration == null || decoration == "none") { break; } localProperties["text-decoration-" + decoration] = "true"; } } // ................................................................. // // Pasring CSS text-transform Property // // ................................................................. private static readonly string[] _textTransforms = new string[] { "none", "capitalize", "uppercase", "lowercase" }; private static void ParseCssTextTransform(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textTransforms, styleValue, ref nextIndex, localProperties, "text-transform"); } // ................................................................. // // Pasring CSS text-align Property // // ................................................................. private static readonly string[] _textAligns = new string[] { "left", "right", "center", "justify" }; private static void ParseCssTextAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textAligns, styleValue, ref nextIndex, localProperties, "text-align"); } // ................................................................. // // Pasring CSS vertical-align Property // // ................................................................. private static readonly string[] _verticalAligns = new string[] { "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom" }; private static void ParseCssVerticalAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { // Parse percentage value for vertical-align style ParseWordEnumeration(_verticalAligns, styleValue, ref nextIndex, localProperties, "vertical-align"); } // ................................................................. // // Pasring CSS float Property // // ................................................................. private static readonly string[] _floats = new string[] { "left", "right", "none" }; private static void ParseCssFloat(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_floats, styleValue, ref nextIndex, localProperties, "float"); } // ................................................................. // // Pasring CSS clear Property // // ................................................................. private static readonly string[] _clears = new string[] { "none", "left", "right", "both" }; private static void ParseCssClear(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_clears, styleValue, ref nextIndex, localProperties, "clear"); } // ................................................................. // // Pasring CSS margin and padding Properties // // ................................................................. // Generic method for parsing any of four-values properties, such as margin, padding, border-width, border-style, border-color private static bool ParseCssRectangleProperty(string styleValue, ref int nextIndex, Hashtable localProperties, string propertyName) { // CSS Spec: // If only one value is set, then the value applies to all four sides; // If two or three values are set, then missinng value(s) are taken fromm the opposite side(s). // The order they are applied is: top/right/bottom/left Debug.Assert(propertyName == "margin" || propertyName == "padding" || propertyName == "border-width" || propertyName == "border-style" || propertyName == "border-color"); string value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-top"] = value; localProperties[propertyName + "-bottom"] = value; localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-bottom"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-left"] = value; } } } return true; } return false; } // ................................................................. // // Pasring CSS border Properties // // ................................................................. // border: [ <border-width> || <border-style> || <border-color> ] private static void ParseCssBorder(string styleValue, ref int nextIndex, Hashtable localProperties) { while ( ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-width") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-style") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-color")) { } } // ................................................................. // // Pasring CSS border-style Propertie // // ................................................................. private static readonly string[] _borderStyles = new string[] { "none", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset" }; private static string ParseCssBorderStyle(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_borderStyles, styleValue, ref nextIndex); } // ................................................................. // // What are these definitions doing here: // // ................................................................. private static string[] _blocks = new string[] { "block", "inline", "list-item", "none" }; // ................................................................. // // Pasring CSS Background Properties // // ................................................................. private static void ParseCssBackground(string styleValue, ref int nextIndex, Hashtable localValues) { // Implement parsing background attribute } } internal class CssStylesheet { // Constructor public CssStylesheet(XmlElement htmlElement) { if (htmlElement != null) { this.DiscoverStyleDefinitions(htmlElement); } } // Recursively traverses an html tree, discovers STYLE elements and creates a style definition table // for further cascading style application public void DiscoverStyleDefinitions(XmlElement htmlElement) { if (htmlElement.LocalName.ToLower() == "link") { return; // Add LINK elements processing for included stylesheets // <LINK href="http://sc.msn.com/global/css/ptnr/orange.css" type=text/css \r\nrel=stylesheet> } if (htmlElement.LocalName.ToLower() != "style") { // This is not a STYLE element. Recurse into it for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlElement) { this.DiscoverStyleDefinitions((XmlElement)htmlChildNode); } } return; } // Add style definitions from this style. // Collect all text from this style definition StringBuilder stylesheetBuffer = new StringBuilder(); for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlText || htmlChildNode is XmlComment) { stylesheetBuffer.Append(RemoveComments(htmlChildNode.Value)); } } // CssStylesheet has the following syntactical structure: // @import declaration; // selector { definition } // where "selector" is one of: ".classname", "tagname" // It can contain comments in the following form: /*...*/ int nextCharacterIndex = 0; while (nextCharacterIndex < stylesheetBuffer.Length) { // Extract selector int selectorStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '{') { // Skip declaration directive starting from @ if (stylesheetBuffer[nextCharacterIndex] == '@') { while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != ';') { nextCharacterIndex++; } selectorStart = nextCharacterIndex + 1; } nextCharacterIndex++; } if (nextCharacterIndex < stylesheetBuffer.Length) { // Extract definition int definitionStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '}') { nextCharacterIndex++; } // Define a style if (nextCharacterIndex - definitionStart > 2) { this.AddStyleDefinition( stylesheetBuffer.ToString(selectorStart, definitionStart - selectorStart), stylesheetBuffer.ToString(definitionStart + 1, nextCharacterIndex - definitionStart - 2)); } // Skip closing brace if (nextCharacterIndex < stylesheetBuffer.Length) { Debug.Assert(stylesheetBuffer[nextCharacterIndex] == '}'); nextCharacterIndex++; } } } } // Returns a string with all c-style comments replaced by spaces private string RemoveComments(string text) { int commentStart = text.IndexOf("/*"); if (commentStart < 0) { return text; } int commentEnd = text.IndexOf("*/", commentStart + 2); if (commentEnd < 0) { return text.Substring(0, commentStart); } return text.Substring(0, commentStart) + " " + RemoveComments(text.Substring(commentEnd + 2)); } public void AddStyleDefinition(string selector, string definition) { // Notrmalize parameter values selector = selector.Trim().ToLower(); definition = definition.Trim().ToLower(); if (selector.Length == 0 || definition.Length == 0) { return; } if (_styleDefinitions == null) { _styleDefinitions = new List<StyleDefinition>(); } string[] simpleSelectors = selector.Split(','); for (int i = 0; i < simpleSelectors.Length; i++) { string simpleSelector = simpleSelectors[i].Trim(); if (simpleSelector.Length > 0) { _styleDefinitions.Add(new StyleDefinition(simpleSelector, definition)); } } } public string GetStyle(string elementName, List<XmlElement> sourceContext) { Debug.Assert(sourceContext.Count > 0); Debug.Assert(elementName == sourceContext[sourceContext.Count - 1].LocalName); // Add id processing for style selectors if (_styleDefinitions != null) { for (int i = _styleDefinitions.Count - 1; i >= 0; i--) { string selector = _styleDefinitions[i].Selector; string[] selectorLevels = selector.Split(' '); int indexInSelector = selectorLevels.Length - 1; int indexInContext = sourceContext.Count - 1; string selectorLevel = selectorLevels[indexInSelector].Trim(); if (MatchSelectorLevel(selectorLevel, sourceContext[sourceContext.Count - 1])) { return _styleDefinitions[i].Definition; } } } return null; } private bool MatchSelectorLevel(string selectorLevel, XmlElement xmlElement) { if (selectorLevel.Length == 0) { return false; } int indexOfDot = selectorLevel.IndexOf('.'); int indexOfPound = selectorLevel.IndexOf('#'); string selectorClass = null; string selectorId = null; string selectorTag = null; if (indexOfDot >= 0) { if (indexOfDot > 0) { selectorTag = selectorLevel.Substring(0, indexOfDot); } selectorClass = selectorLevel.Substring(indexOfDot + 1); } else if (indexOfPound >= 0) { if (indexOfPound > 0) { selectorTag = selectorLevel.Substring(0, indexOfPound); } selectorId = selectorLevel.Substring(indexOfPound + 1); } else { selectorTag = selectorLevel; } if (selectorTag != null && selectorTag != xmlElement.LocalName) { return false; } if (selectorId != null && HtmlToXamlConverter.GetAttribute(xmlElement, "id") != selectorId) { return false; } if (selectorClass != null && HtmlToXamlConverter.GetAttribute(xmlElement, "class") != selectorClass) { return false; } return true; } private class StyleDefinition { public StyleDefinition(string selector, string definition) { this.Selector = selector; this.Definition = definition; } public string Selector; public string Definition; } private List<StyleDefinition> _styleDefinitions; } }
using System; using System.Collections.Generic; using System.IO; using Terraria.ID; using Terraria.ModLoader.Default; using Terraria.ModLoader.Exceptions; namespace Terraria.ModLoader.IO { public static class ItemIO { //replace netID writes in Terraria.Player.SavePlayer //in Terraria.IO.WorldFile.SaveChests include IsModItem for no-item check internal static void WriteVanillaID(Item item, BinaryWriter writer) { writer.Write(ItemLoader.IsModItem(item) ? 0 : item.netID); } public static TagCompound Save(Item item) { var tag = new TagCompound(); if (item.type <= 0) return tag; if (item.modItem == null) { tag.Set("mod", "Terraria"); tag.Set("id", item.netID); } else { tag.Set("mod", item.modItem.mod.Name); tag.Set("name", Main.itemName[item.type]); tag.Set("data", item.modItem.Save()); } if (item.prefix != 0) tag.Set("prefix", item.prefix); if (item.stack > 1) tag.Set("stack", item.stack); if (item.favorited) tag.Set("fav", true); tag.Set("globalData", SaveGlobals(item)); return tag; } public static void Load(Item item, TagCompound tag) { if (tag.Count == 0) { item.netDefaults(0); return; } string modName = tag.GetString("mod"); if (modName == "Terraria") { item.netDefaults(tag.GetInt("id")); if (tag.ContainsKey("legacyData")) LoadLegacyModData(item, tag.GetByteArray("legacyData"), tag.GetBool("hasGlobalSaving")); } else { int type = ModLoader.GetMod(modName)?.ItemType(tag.GetString("name")) ?? 0; if (type > 0) { item.netDefaults(type); if (tag.ContainsKey("legacyData")) LoadLegacyModData(item, tag.GetByteArray("legacyData"), tag.GetBool("hasGlobalSaving")); else item.modItem.Load(tag.GetCompound("data")); } else { item.netDefaults(ModLoader.GetMod("ModLoader").ItemType("MysteryItem")); ((MysteryItem)item.modItem).Setup(tag); } } item.Prefix(tag.GetByte("prefix")); item.stack = tag.Get<int?>("stack") ?? 1; item.favorited = tag.GetBool("fav"); if (!(item.modItem is MysteryItem)) LoadGlobals(item, tag.GetList<TagCompound>("globalData")); } public static Item Load(TagCompound tag) { var item = new Item(); Load(item, tag); return item; } internal static List<TagCompound> SaveGlobals(Item item) { if (item.modItem is MysteryItem) return null; //MysteryItems cannot have global data var list = new List<TagCompound>(); foreach (var globalItem in ItemLoader.globalItems) { if (!globalItem.NeedsSaving(item)) continue; list.Add(new TagCompound { ["mod"] = globalItem.mod.Name, ["name"] = globalItem.Name, ["data"] = globalItem.Save(item) }); } return list.Count > 0 ? list : null; } internal static void LoadGlobals(Item item, IList<TagCompound> list) { foreach (var tag in list) { var mod = ModLoader.GetMod(tag.GetString("mod")); var globalItem = mod?.GetGlobalItem(tag.GetString("name")); if (globalItem != null) { try { globalItem.Load(item, tag.GetCompound("data")); } catch (Exception e) { throw new CustomModDataException(mod, "Error in reading custom player data for " + mod.Name, e); } } else { item.GetModInfo<MysteryGlobalItemInfo>(ModLoader.GetMod("ModLoader")).data.Add(tag); } } } public static void Send(Item item, BinaryWriter writer, bool writeStack = false, bool writeFavourite = false) { writer.Write((short)item.netID); writer.Write(item.prefix); if (writeStack) writer.Write((short)item.stack); if (writeFavourite) writer.Write(item.favorited); SendModData(item, writer); } public static void Receive(Item item, BinaryReader reader, bool readStack = false, bool readFavorite = false) { item.netDefaults(reader.ReadInt16()); item.Prefix(reader.ReadByte()); if (readStack) item.stack = reader.ReadInt16(); if (readFavorite) item.favorited = reader.ReadBoolean(); ReceiveModData(item, reader); } public static Item Receive(BinaryReader reader, bool readStack = false, bool readFavorite = false) { var item = new Item(); Receive(item, reader, readStack, readFavorite); return item; } public static void SendModData(Item item, BinaryWriter writer) { writer.SafeWrite(w => item.modItem?.NetSend(w)); foreach (var globalItem in ItemLoader.NetGlobals) writer.SafeWrite(w => globalItem.NetSend(item, w)); } public static void ReceiveModData(Item item, BinaryReader reader) { try { reader.SafeRead(r => item.modItem?.NetRecieve(r)); } catch (IOException) { //TODO inform modder/user } foreach (var globalItem in ItemLoader.NetGlobals) { try { reader.SafeRead(r => globalItem.NetReceive(item, r)); } catch (IOException) { //TODO inform modder/user } } } public static void LoadLegacy(Item item, BinaryReader reader, bool readStack = false, bool readFavorite = false) { string modName = reader.ReadString(); bool hasGlobalSaving = false; if (modName.Length == 0) { hasGlobalSaving = true; modName = reader.ReadString(); } if (modName == "Terraria") { item.netDefaults(reader.ReadInt32()); LoadLegacyModData(item, LegacyModData(item.type, reader, hasGlobalSaving), hasGlobalSaving); } else { string itemName = reader.ReadString(); int type = ModLoader.GetMod(modName)?.ItemType(itemName) ?? 0; byte[] data = LegacyModData(type == 0 ? int.MaxValue : type, reader, hasGlobalSaving); if (type != 0) { item.netDefaults(type); LoadLegacyModData(item, data, hasGlobalSaving); } else { item.netDefaults(ModLoader.GetMod("ModLoader").ItemType("MysteryItem")); var tag = new TagCompound { ["mod"] = modName, ["name"] = itemName, ["hasGlobalSaving"] = hasGlobalSaving, ["legacyData"] = data }; ((MysteryItem)item.modItem).Setup(tag); } } item.Prefix(reader.ReadByte()); if (readStack) item.stack = reader.ReadInt32(); if (readFavorite) item.favorited = reader.ReadBoolean(); } internal static byte[] LegacyModData(int type, BinaryReader reader, bool hasGlobalSaving = true) { using (MemoryStream memoryStream = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(memoryStream)) { if (type >= ItemID.Count) { ushort length = reader.ReadUInt16(); writer.Write(length); writer.Write(reader.ReadBytes(length)); } if (hasGlobalSaving) { ushort count = reader.ReadUInt16(); writer.Write(count); for (int k = 0; k < count; k++) { writer.Write(reader.ReadString()); writer.Write(reader.ReadString()); ushort length = reader.ReadUInt16(); writer.Write(length); writer.Write(reader.ReadBytes(length)); } } } return memoryStream.ToArray(); } } internal static void LoadLegacyModData(Item item, byte[] data, bool hasGlobalSaving = true) { using (BinaryReader reader = new BinaryReader(new MemoryStream(data))) { if (ItemLoader.IsModItem(item)) { byte[] modData = reader.ReadBytes(reader.ReadUInt16()); if (modData.Length > 0) { using (BinaryReader customReader = new BinaryReader(new MemoryStream(modData))) { try { item.modItem.LoadLegacy(customReader); } catch (Exception e) { throw new CustomModDataException(item.modItem.mod, "Error in reading custom item data for " + item.modItem.mod.Name, e); } } } } if (hasGlobalSaving) { int count = reader.ReadUInt16(); for (int k = 0; k < count; k++) { string modName = reader.ReadString(); string globalName = reader.ReadString(); byte[] globalData = reader.ReadBytes(reader.ReadUInt16()); GlobalItem globalItem = ModLoader.GetMod(modName)?.GetGlobalItem(globalName); //could support legacy global data in mystery globals but eh... if (globalItem != null && globalData.Length > 0) { using (BinaryReader customReader = new BinaryReader(new MemoryStream(globalData))) { try { globalItem.LoadLegacy(item, customReader); } catch (Exception e) { throw new CustomModDataException(globalItem.mod, "Error in reading custom global item data for " + globalItem.mod.Name, e); } } } } } } } public static void LoadLegacyInventory(Item[] inv, BinaryReader reader, bool readStack = false, bool readFavorite = false) { int count = reader.ReadUInt16(); for (int k = 0; k < count; k++) { LoadLegacy(inv[reader.ReadUInt16()], reader, readStack, readFavorite); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class GridUserServicesConnector : IGridUserService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public GridUserServicesConnector() { } public GridUserServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public GridUserServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig gridConfig = source.Configs["GridUserService"]; if (gridConfig == null) { m_log.Error("[GRID USER CONNECTOR]: GridUserService missing from OpenSim.ini"); throw new Exception("GridUser connector init error"); } string serviceURI = gridConfig.GetString("GridUserServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[GRID USER CONNECTOR]: No Server URI named in section GridUserService"); throw new Exception("GridUser connector init error"); } m_ServerURI = serviceURI; } #region IGridUserService public GridUserInfo LoggedIn(string userID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "loggedin"; sendData["UserID"] = userID; return Get(sendData); } public bool LoggedOut(string userID, UUID sessionID, UUID region, Vector3 position, Vector3 lookat) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "loggedout"; return Set(sendData, userID, region, position, lookat); } public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "sethome"; return Set(sendData, userID, regionID, position, lookAt); } public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 position, Vector3 lookAt) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "setposition"; return Set(sendData, userID, regionID, position, lookAt); } public GridUserInfo GetGridUserInfo(string userID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getgriduserinfo"; sendData["UserID"] = userID; return Get(sendData); } #endregion protected bool Set(Dictionary<string, object> sendData, string userID, UUID regionID, Vector3 position, Vector3 lookAt) { sendData["UserID"] = userID; sendData["RegionID"] = regionID.ToString(); sendData["Position"] = position.ToString(); sendData["LookAt"] = lookAt.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/griduser"; // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition reply data does not contain result field"); } else m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition received empty reply"); } catch (Exception e) { m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server at {0}: {1}", uri, e.Message); } return false; } protected GridUserInfo Get(Dictionary<string, object> sendData) { string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/griduser"; // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); GridUserInfo guinfo = null; if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) guinfo = Create((Dictionary<string, object>)replyData["result"]); } return guinfo; } else m_log.DebugFormat("[GRID USER CONNECTOR]: Get received empty reply"); } catch (Exception e) { m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server at {0}: {1}", uri, e.Message); } return null; } public GridUserInfo[] GetGridUserInfo(string[] userIDs) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getgriduserinfos"; sendData["AgentIDs"] = new List<string>(userIDs); string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/griduser"; //m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[GRID USER CONNECTOR]: GetGridUserInfo received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server at {0}: {1}", uri, e.Message); } List<GridUserInfo> rinfos = new List<GridUserInfo>(); Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { if (replyData.ContainsKey("result") && (replyData["result"].ToString() == "null" || replyData["result"].ToString() == "Failure")) { return new GridUserInfo[0]; } Dictionary<string, object>.ValueCollection pinfosList = replyData.Values; //m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count); foreach (object griduser in pinfosList) { if (griduser is Dictionary<string, object>) { GridUserInfo pinfo = Create((Dictionary<string, object>)griduser); rinfos.Add(pinfo); } else m_log.DebugFormat("[GRID USER CONNECTOR]: GetGridUserInfo received invalid response type {0}", griduser.GetType()); } } else m_log.DebugFormat("[GRID USER CONNECTOR]: GetGridUserInfo received null response"); return rinfos.ToArray(); } protected virtual GridUserInfo Create(Dictionary<string, object> griduser) { return new GridUserInfo(griduser); } } }
#pragma warning disable using System.Collections.Generic; using XPT.Games.Generic.Entities; using XPT.Games.Generic.Maps; using XPT.Games.Yserbius; using XPT.Games.Yserbius.Entities; namespace XPT.Games.Yserbius.Maps { class YserMap19 : YsMap { public override int MapIndex => 19; protected override int RandomEncounterChance => 10; protected override int RandomEncounterExtraCount => 1; public YserMap19() { MapEvent01 = FnTELEPORT_01; MapEvent02 = FnTELEMESS_02; MapEvent03 = FnFOUNBLES_03; MapEvent04 = FnQUESTENC_04; MapEvent05 = FnLKPKDORZ_05; MapEvent06 = FnSTRDOOR_06; MapEvent0B = FnAVEMNSTR_0B; MapEvent0C = FnSTRMNSTR_0C; MapEvent0E = FnNPCCHATA_0E; MapEvent0F = FnNPCCHATB_0F; } // === Strings ================================================ private const string String03FC = "There is a teleport in the west wall."; private const string String0422 = "You sip from the Fountain of Restoration, but nothing happens."; private const string String0461 = "You find the Fountain of Restoration and sip from it. You feel your Health greatly improve."; private const string String04BD = "Monsters attack you."; private const string String04D2 = "Among a horde of Nightmares and Cockatrices you spot armor and other items on the floor."; private const string String052B = "The door opens easily when you use the Lava Key."; private const string String055C = "This door cannot be unlocked without the Lava Key."; private const string String058F = "You manage to force the door open."; private const string String05B2 = "The door is stuck."; private const string String05C5 = "You encounter a Human Thief."; private const string String05E2 = "Find the Fountain of Tranquility if you are battle weary. Find it - if you can."; private const string String0632 = "The Human Thief cringes in terror and wraps herself up in a tight ball."; private const string String067A = "You encounter an Elf Barbarian."; private const string String069A = "A halfling thief told me of a wondrous world of four seasons deep in the heart of the dungeon. Of course, I did not believe him. Thieves are such liars."; private const string String0733 = "The Elf Barbarian dismisses you as useless baggage and heads off to find true heroes."; // === Functions ================================================ private void FnTELEPORT_01(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x05, 0x02, 0x00, 0x33, type); L001D: return; // RETURN; } private void FnTELEMESS_02(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String03FC); // There is a teleport in the west wall. L0010: return; // RETURN; } private void FnFOUNBLES_03(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagPitBottomFountainRestoration), 0x0001); L0017: if (JumpNotEqual) goto L0035; L0019: ShowPortrait(player, 0x0042); L0026: ShowMessage(player, doMsgs, String0422); // You sip from the Fountain of Restoration, but nothing happens. L0033: goto L0080; L0035: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagPitBottomFountainRestoration, 0x01); L004A: ShowPortrait(player, 0x0042); L0057: dx = GetMaxHits(player) - GetCurrentHits(player); L0069: HealPlayer(player, (ushort)dx); L0073: ShowMessage(player, doMsgs, String0461); // You find the Fountain of Restoration and sip from it. You feel your Health greatly improve. L0080: return; // RETURN; } private void FnQUESTENC_04(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = HasItem(player, 0x81); L0011: if (JumpEqual) goto L0043; L0013: AddTreasure(player, 0x01F4, 0x00, 0x00, 0xBD, 0xA5, 0xCD); L0034: ShowMessage(player, doMsgs, String04BD); // Monsters attack you. L0041: goto L0071; L0043: AddTreasure(player, 0x03E8, 0x00, 0x00, 0xA2, 0xD0, 0x81); L0064: ShowMessage(player, doMsgs, String04D2); // Among a horde of Nightmares and Cockatrices you spot armor and other items on the floor. L0071: Compare(PartyCount(player), 0x0001); L007C: if (JumpNotEqual) goto L00B7; L007E: AddEncounter(player, 0x01, 0x26); L0090: AddEncounter(player, 0x02, 0x26); L00A2: AddEncounter(player, 0x06, 0x23); L00B4: goto L01E4; L00B7: Compare(PartyCount(player), 0x0002); L00C2: if (JumpNotEqual) goto L010F; L00C4: AddEncounter(player, 0x01, 0x27); L00D6: AddEncounter(player, 0x02, 0x27); L00E8: AddEncounter(player, 0x05, 0x24); L00FA: AddEncounter(player, 0x06, 0x24); L010C: goto L01E4; L010F: Compare(PartyCount(player), 0x0003); L011A: if (JumpNotEqual) goto L0178; L011C: AddEncounter(player, 0x01, 0x26); L012E: AddEncounter(player, 0x02, 0x27); L0140: AddEncounter(player, 0x03, 0x28); L0152: AddEncounter(player, 0x04, 0x23); L0164: AddEncounter(player, 0x05, 0x24); L0176: goto L01E4; L0178: AddEncounter(player, 0x01, 0x23); L018A: AddEncounter(player, 0x02, 0x26); L019C: AddEncounter(player, 0x03, 0x24); L01AE: AddEncounter(player, 0x04, 0x27); L01C0: AddEncounter(player, 0x05, 0x25); L01D2: AddEncounter(player, 0x06, 0x28); L01E4: return; // RETURN; } private void FnLKPKDORZ_05(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = HasUsedItem(player, type, ref doMsgs, YsIndexes.ItemLavaKey, YsIndexes.ItemLavaKey); L0016: if (JumpEqual) goto L0063; L0018: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01); L0036: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player)); L0054: ShowMessage(player, doMsgs, String052B); // The door opens easily when you use the Lava Key. L0061: goto L008D; L0063: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00); L0080: ShowMessage(player, doMsgs, String055C); // This door cannot be unlocked without the Lava Key. L008D: return; // RETURN; } private void FnSTRDOOR_06(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(CheckStrength(player), 0x000E); L0012: if (JumpBelow) goto L005F; L0014: ShowMessage(player, doMsgs, String058F); // You manage to force the door open. L0021: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player)); L003F: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01); L005D: goto L0089; L005F: ShowMessage(player, doMsgs, String05B2); // The door is stuck. L006C: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00); L0089: return; // RETURN; } private void FnAVEMNSTR_0B(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(PartyCount(player), 0x0001); L000E: if (JumpNotEqual) goto L0025; L0010: AddEncounter(player, 0x02, 0x1B); L0022: goto L012E; L0025: Compare(PartyCount(player), 0x0002); L0030: if (JumpNotEqual) goto L006B; L0032: AddEncounter(player, 0x01, 0x1C); L0044: AddEncounter(player, 0x02, 0x19); L0056: AddEncounter(player, 0x03, 0x18); L0068: goto L012E; L006B: Compare(PartyCount(player), 0x0003); L0076: if (JumpNotEqual) goto L00C2; L0078: AddEncounter(player, 0x01, 0x1B); L008A: AddEncounter(player, 0x02, 0x1C); L009C: AddEncounter(player, 0x03, 0x1A); L00AE: AddEncounter(player, 0x04, 0x19); L00C0: goto L012E; L00C2: AddEncounter(player, 0x01, 0x1A); L00D4: AddEncounter(player, 0x02, 0x1C); L00E6: AddEncounter(player, 0x03, 0x19); L00F8: AddEncounter(player, 0x04, 0x1B); L010A: AddEncounter(player, 0x05, 0x1D); L011C: AddEncounter(player, 0x06, 0x1A); L012E: return; // RETURN; } private void FnSTRMNSTR_0C(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(PartyCount(player), 0x0001); L000E: if (JumpNotEqual) goto L0037; L0010: AddEncounter(player, 0x01, 0x1E); L0022: AddEncounter(player, 0x02, 0x20); L0034: goto L0152; L0037: Compare(PartyCount(player), 0x0002); L0042: if (JumpNotEqual) goto L007D; L0044: AddEncounter(player, 0x01, 0x1E); L0056: AddEncounter(player, 0x02, 0x20); L0068: AddEncounter(player, 0x03, 0x20); L007A: goto L0152; L007D: Compare(PartyCount(player), 0x0003); L0088: if (JumpNotEqual) goto L00E6; L008A: AddEncounter(player, 0x01, 0x1E); L009C: AddEncounter(player, 0x02, 0x1E); L00AE: AddEncounter(player, 0x03, 0x20); L00C0: AddEncounter(player, 0x04, 0x20); L00D2: AddEncounter(player, 0x05, 0x1F); L00E4: goto L0152; L00E6: AddEncounter(player, 0x01, 0x1E); L00F8: AddEncounter(player, 0x02, 0x1E); L010A: AddEncounter(player, 0x03, 0x1F); L011C: AddEncounter(player, 0x04, 0x1F); L012E: AddEncounter(player, 0x05, 0x20); L0140: AddEncounter(player, 0x06, 0x20); L0152: return; // RETURN; } private void FnNPCCHATA_0E(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String05C5); // You encounter a Human Thief. L0010: ShowPortrait(player, 0x0022); L001D: Compare(GetRandom(0x000F), 0x000C); L002D: if (JumpAbove) goto L003E; L002F: ShowMessage(player, doMsgs, String05E2); // Find the Fountain of Tranquility if you are battle weary. Find it - if you can. L003C: goto L004B; L003E: ShowMessage(player, doMsgs, String0632); // The Human Thief cringes in terror and wraps herself up in a tight ball. L004B: return; // RETURN; } private void FnNPCCHATB_0F(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String067A); // You encounter an Elf Barbarian. L0010: ShowPortrait(player, 0x0018); L001D: Compare(GetRandom(0x000F), 0x0004); L002D: if (JumpAbove) goto L003E; L002F: ShowMessage(player, doMsgs, String069A); // A halfling thief told me of a wondrous world of four seasons deep in the heart of the dungeon. Of course, I did not believe him. Thieves are such liars. L003C: goto L004B; L003E: ShowMessage(player, doMsgs, String0733); // The Elf Barbarian dismisses you as useless baggage and heads off to find true heroes. L004B: return; // RETURN; } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonPlayer.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // Represents a player, identified by actorID (a.k.a. ActorNumber). // Caches properties of a player. // </summary> // <author>[email protected]</author> // ---------------------------------------------------------------------------- using UnityEngine; using Hashtable = ExitGames.Client.Photon.Hashtable; /// <summary> /// Summarizes a "player" within a room, identified (in that room) by actorID. /// </summary> /// <remarks> /// Each player has an actorId (or ID), valid for that room. It's -1 until it's assigned by server. /// Each client can set it's player's custom properties with SetCustomProperties, even before being in a room. /// They are synced when joining a room. /// </remarks> /// \ingroup publicApi public class PhotonPlayer { /// <summary>This player's actorID</summary> public int ID { get { return this.actorID; } } /// <summary>Identifier of this player in current room.</summary> private int actorID = -1; private string nameField = ""; /// <summary>Nickname of this player.</summary> public string name { get { return this.nameField; } set { if (!isLocal) { Debug.LogError("Error: Cannot change the name of a remote player!"); return; } this.nameField = value; } } /// <summary>Only one player is controlled by each client. Others are not local.</summary> public readonly bool isLocal = false; /// <summary> /// The player with the lowest actorID is the master and could be used for special tasks. /// </summary> public bool isMasterClient { get { return (PhotonNetwork.networkingPeer.mMasterClient == this); } } /// <summary>Read-only cache for custom properties of player. Set via Player.SetCustomProperties.</summary> /// <remarks> /// Don't modify the content of this Hashtable. Use SetCustomProperties and the /// properties of this class to modify values. When you use those, the client will /// sync values with the server. /// </remarks> public Hashtable customProperties { get; private set; } /// <summary>Creates a Hashtable with all properties (custom and "well known" ones).</summary> /// <remarks>If used more often, this should be cached.</remarks> public Hashtable allProperties { get { Hashtable allProps = new Hashtable(); allProps.Merge(this.customProperties); allProps[ActorProperties.PlayerName] = this.name; return allProps; } } /// <summary> /// Creates a PhotonPlayer instance. /// </summary> /// <param name="isLocal">If this is the local peer's player (or a remote one).</param> /// <param name="actorID">ID or ActorNumber of this player in the current room (a shortcut to identify each player in room)</param> /// <param name="name">Name of the player (a "well known property").</param> public PhotonPlayer(bool isLocal, int actorID, string name) { this.customProperties = new Hashtable(); this.isLocal = isLocal; this.actorID = actorID; this.nameField = name; } /// <summary> /// Internally used to create players from event Join /// </summary> internal protected PhotonPlayer(bool isLocal, int actorID, Hashtable properties) { this.customProperties = new Hashtable(); this.isLocal = isLocal; this.actorID = actorID; this.InternalCacheProperties(properties); } /// <summary> /// Caches custom properties for this player. /// </summary> internal void InternalCacheProperties(Hashtable properties) { if (properties == null || properties.Count == 0 || this.customProperties.Equals(properties)) { return; } if (properties.ContainsKey(ActorProperties.PlayerName)) { this.nameField = (string)properties[ActorProperties.PlayerName]; } this.customProperties.MergeStringKeys(properties); this.customProperties.StripKeysWithNullValues(); } /// <summary> /// Gives the name. /// </summary> public override string ToString() { return (this.name == null) ? string.Empty : this.name; // +" " + SupportClass.HashtableToString(this.CustomProperties); } /// <summary> /// Makes PhotonPlayer comparable /// </summary> public override bool Equals(object p) { PhotonPlayer pp = p as PhotonPlayer; return (pp != null && this.GetHashCode() == pp.GetHashCode()); } public override int GetHashCode() { return this.ID; } /// <summary> /// Used internally, to update this client's playerID when assigned. /// </summary> internal void InternalChangeLocalID(int newID) { if (!this.isLocal) { Debug.LogError("ERROR You should never change PhotonPlayer IDs!"); return; } this.actorID = newID; } /// <summary> /// Updates and synchronizes the named properties of this Player with the values of propertiesToSet. /// </summary> /// <remarks> /// Any player's properties are available in a Room only and only until the player disconnect or leaves. /// Access any player's properties by: Player.CustomProperties (read-only!) but don't modify that hashtable. /// /// New properties are added, existing values are updated. /// Other values will not be changed, so only provide values that changed or are new. /// To delete a named (custom) property of this player, use null as value. /// Only string-typed keys are applied (everything else is ignored). /// /// Local cache is updated immediately, other players are updated through Photon with a fitting operation. /// To reduce network traffic, set only values that actually changed. /// </remarks> /// <param name="propertiesToSet">Hashtable of props to udpate, set and sync. See description.</param> public void SetCustomProperties(Hashtable propertiesToSet) { if (propertiesToSet == null) { return; } // merge (delete null-values) this.customProperties.MergeStringKeys(propertiesToSet); // includes a Equals check (simplifying things) this.customProperties.StripKeysWithNullValues(); // send (sync) these new values Hashtable customProps = propertiesToSet.StripToStringKeys() as Hashtable; if (this.actorID > 0) { PhotonNetwork.networkingPeer.OpSetCustomPropertiesOfActor(this.actorID, customProps, true, 0); } NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerPropertiesChanged, this, propertiesToSet); } /// <summary> /// Try to get a specific player by id. /// </summary> /// <param name="ID">ActorID</param> /// <returns>The player with matching actorID or null, if the actorID is not in use.</returns> public static PhotonPlayer Find(int ID) { for (int index = 0; index < PhotonNetwork.playerList.Length; index++) { PhotonPlayer player = PhotonNetwork.playerList[index]; if (player.ID == ID) { return player; } } return null; } }
/* * Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ using org.javarosa.core.data; using org.javarosa.core.model; using org.javarosa.core.model.data; using org.javarosa.core.model.data.helper; using org.javarosa.core.model.utils; using System; using System.Collections; using System.Text; using System.Xml; namespace org.javarosa.xform.util { /** * The XFormAnswerDataSerializer takes in AnswerData objects, and provides * an XForms compliant (String or Element) representation of that AnswerData. * * By default, this serializer can properly operate on StringData, DateData * SelectMultiData, and SelectOneData AnswerData objects. This list can be * extended by registering appropriate XForm serializing AnswerDataSerializers * with this class. * * @author Acellam Guy , Clayton Sims * */ public class XFormAnswerDataSerializer : IAnswerDataSerializer { public const String DELIMITER = " "; ArrayList additionalSerializers = new ArrayList(); public void registerAnswerSerializer(IAnswerDataSerializer ads) { additionalSerializers.Add(ads); } public Boolean canSerialize(IAnswerData data) { if (data is StringData || data is DateData || data is TimeData || data is SelectMultiData || data is SelectOneData || data is IntegerData || data is DecimalData || data is PointerAnswerData || data is MultiPointerAnswerData || data is GeoPointData || data is LongData || data is DateTimeData || data is UncastData) { return true; } else { return false; } } /** * @param data The AnswerDataObject to be serialized * @return A String which contains the given answer */ public Object serializeAnswerData(UncastData data) { return data.String; } /** * @param data The AnswerDataObject to be serialized * @return A String which contains the given answer */ public Object serializeAnswerData(StringData data) { return (String)data.Value; } /** * @param data The AnswerDataObject to be serialized * @return A String which contains a date in xsd:date * formatting */ public Object serializeAnswerData(DateData data) { DateTime dt = ((DateTime)data.Value); return DateUtils.formatDate(ref dt, DateUtils.FORMAT_ISO8601); } /** * @param data The AnswerDataObject to be serialized * @return A String which contains a date in xsd:date * formatting */ public Object serializeAnswerData(DateTimeData data) { DateTime dt = (DateTime)data.Value; return DateUtils.formatDateTime(ref dt, DateUtils.FORMAT_ISO8601); } /** * @param data The AnswerDataObject to be serialized * @return A String which contains a date in xsd:time * formatting */ public Object serializeAnswerData(TimeData data) { DateTime dt = (DateTime)data.Value; return DateUtils.formatTime(ref dt, DateUtils.FORMAT_ISO8601); } /** * @param data The AnswerDataObject to be serialized * @return A String which contains a reference to the * data */ public Object serializeAnswerData(PointerAnswerData data) { //Note: In order to override this default behavior, a //new serializer should be used, and then registered //with this serializer IDataPointer pointer = (IDataPointer)data.getValue(); return pointer.DisplayText; } /** * @param data The AnswerDataObject to be serialized * @return A String which contains a reference to the * data */ public Object serializeAnswerData(MultiPointerAnswerData data) { //Note: In order to override this default behavior, a //new serializer should be used, and then registered //with this serializer IDataPointer[] pointers = (IDataPointer[])data.Value; if (pointers.Length == 1) { return pointers[0].DisplayText; } XmlDocument doc = new XmlDocument(); XmlElement parent = doc.CreateElement("serializeAnswerData"); for (int i = 0; i < pointers.Length; ++i) { XmlElement datael = doc.CreateElement("data"); XmlText xtext = doc.CreateTextNode(pointers[i].DisplayText); datael.AppendChild(xtext); parent.AppendChild(datael); } return parent; } /** * @param data The AnswerDataObject to be serialized * @return A string containing the xforms compliant format * for a <select> tag, a string containing a list of answers * separated by space characters. */ public Object serializeAnswerData(SelectMultiData data) { ArrayList selections = (ArrayList)data.Value; IEnumerator en = selections.GetEnumerator(); StringBuilder selectString = new StringBuilder(); while (en.MoveNext()) { Selection selection = (Selection)en.Current; if (selectString.Length > 0) selectString.Append(DELIMITER); selectString.Append(selection.Value); } //As Crazy, and stupid, as it sounds, this is the XForms specification //for storing multiple selections. return selectString.ToString(); } /** * @param data The AnswerDataObject to be serialized * @return A String which contains the value of a selection */ public Object serializeAnswerData(SelectOneData data) { return ((Selection)data.Value).Value; } public Object serializeAnswerData(IntegerData data) { return ((int)data.Value).ToString(); } public Object serializeAnswerData(LongData data) { return ((long)data.Value).ToString(); } public Object serializeAnswerData(DecimalData data) { return ((Double)data.Value).ToString(); } public Object serializeAnswerData(GeoPointData data) { return data.DisplayText; } public Object serializeAnswerData(BooleanData data) { if (((Boolean)data.Value)) { return "1"; } else { return "0"; } } public Object serializeAnswerData(IAnswerData data, int dataType) { // First, we want to go through the additional serializers, as they should // take priority to the default serializations IEnumerator en = additionalSerializers.GetEnumerator(); while (en.MoveNext()) { IAnswerDataSerializer serializer = (IAnswerDataSerializer)en.Current; if (serializer.canSerialize(data)) { return serializer.serializeAnswerData(data, dataType); } } //Defaults Object result = serializeAnswerData(data); return result; } public Object serializeAnswerData(IAnswerData data) { if (data is StringData) { return serializeAnswerData((StringData)data); } else if (data is SelectMultiData) { return serializeAnswerData((SelectMultiData)data); } else if (data is SelectOneData) { return serializeAnswerData((SelectOneData)data); } else if (data is IntegerData) { return serializeAnswerData((IntegerData)data); } else if (data is LongData) { return serializeAnswerData((LongData)data); } else if (data is DecimalData) { return serializeAnswerData((DecimalData)data); } else if (data is DateData) { return serializeAnswerData((DateData)data); } else if (data is TimeData) { return serializeAnswerData((TimeData)data); } else if (data is PointerAnswerData) { return serializeAnswerData((PointerAnswerData)data); } else if (data is MultiPointerAnswerData) { return serializeAnswerData((MultiPointerAnswerData)data); } else if (data is GeoPointData) { return serializeAnswerData((GeoPointData)data); } else if (data is DateTimeData) { return serializeAnswerData((DateTimeData)data); } else if (data is BooleanData) { return serializeAnswerData((BooleanData)data); } else if (data is UncastData) { return serializeAnswerData((UncastData)data); } return null; } /* * (non-Javadoc) * @see org.javarosa.core.model.IAnswerDataSerializer#containsExternalData(org.javarosa.core.model.data.IAnswerData) */ public Boolean containsExternalData(IAnswerData data) { //First check for registered serializers to identify whether //they override this one. IEnumerator en = additionalSerializers.GetEnumerator(); while (en.MoveNext()) { IAnswerDataSerializer serializer = (IAnswerDataSerializer)en.Current; Boolean contains = serializer.containsExternalData(data); if (contains != null) { return contains; } } if (data is PointerAnswerData || data is MultiPointerAnswerData) { return true; } return false; } public IDataPointer[] retrieveExternalDataPointer(IAnswerData data) { IEnumerator en = additionalSerializers.GetEnumerator(); while (en.MoveNext()) { IAnswerDataSerializer serializer = (IAnswerDataSerializer)en.Current; Boolean contains = serializer.containsExternalData(data); if (contains != null) { return serializer.retrieveExternalDataPointer(data); } } if (data is PointerAnswerData) { IDataPointer[] pointer = new IDataPointer[1]; pointer[0] = (IDataPointer)((PointerAnswerData)data).getValue(); return pointer; } else if (data is MultiPointerAnswerData) { return (IDataPointer[])((MultiPointerAnswerData)data).Value; } //This shouldn't have been called. return null; } } }
using System; using System.Collections; using Server; using Server.Network; using Server.Items; using Server.Mobiles; using Server.Prompts; using Server.Targeting; using Server.Engines.XmlSpawner2; // // XmlPlayerQuestGump // namespace Server.Gumps { public class XmlPlayerQuestGump : Gump { private PlayerMobile m_From; private IXmlQuest m_QuestItem; public override void OnResponse( Server.Network.NetState sender, RelayInfo info ) { if(info == null || sender == null || sender.Mobile == null) return; // read the text entries for the search criteria TextRelay tr = info.GetTextEntry( 100 ); // quest name if(tr != null) m_QuestItem.Name = tr.Text.Trim(); tr = info.GetTextEntry( 102 ); // title if(tr != null) m_QuestItem.TitleString = tr.Text.Trim(); tr = info.GetTextEntry( 103 ); // notestring if(tr != null) m_QuestItem.NoteString = tr.Text; tr = info.GetTextEntry( 200 ); // objectives if(tr != null) m_QuestItem.Objective1 = tr.Text.Trim(); tr = info.GetTextEntry( 201 ); if(tr != null) m_QuestItem.Objective2 = tr.Text.Trim(); tr = info.GetTextEntry( 202 ); if(tr != null) m_QuestItem.Objective3 = tr.Text.Trim(); tr = info.GetTextEntry( 203 ); if (tr != null) m_QuestItem.Objective4 = tr.Text.Trim(); tr = info.GetTextEntry( 204 ); if(tr != null) m_QuestItem.Objective5 = tr.Text.Trim(); tr = info.GetTextEntry( 205 ); if(tr != null && tr.Text != null && tr.Text.Length > 0) // descriptions m_QuestItem.Description1 = tr.Text.Trim(); else m_QuestItem.Description1 = null; tr = info.GetTextEntry( 206 ); if(tr != null && tr.Text != null && tr.Text.Length > 0) m_QuestItem.Description2 = tr.Text.Trim(); else m_QuestItem.Description2 = null; tr = info.GetTextEntry( 207 ); if(tr != null && tr.Text != null && tr.Text.Length > 0) m_QuestItem.Description3 = tr.Text.Trim(); else m_QuestItem.Description3 = null; tr = info.GetTextEntry( 208 ); if(tr != null && tr.Text != null && tr.Text.Length > 0) m_QuestItem.Description4 = tr.Text.Trim(); else m_QuestItem.Description4 = null; tr = info.GetTextEntry( 209 ); if(tr != null && tr.Text != null && tr.Text.Length > 0) m_QuestItem.Description5 = tr.Text.Trim(); else m_QuestItem.Description5 = null; tr = info.GetTextEntry( 210 ); // expiration if(tr != null && tr.Text != null && tr.Text.Length > 0){ try{m_QuestItem.Expiration = double.Parse(tr.Text.Trim());} catch{} } // check all of the check boxes m_QuestItem.PartyEnabled = info.IsSwitched(300); m_QuestItem.CanSeeReward = info.IsSwitched(301); // refresh the time created m_QuestItem.TimeCreated = DateTime.Now; switch ( info.ButtonID ) { case 0: // Okay { break; } case 1: // Select Reward { sender.Mobile.Target = new RewardTarget(m_QuestItem); break; } case 2: // Select Reward Return { sender.Mobile.Target = new ReturnTarget(m_QuestItem); break; } } } public XmlPlayerQuestGump( PlayerMobile from, IXmlQuest questitem ) : base( 12, 140 ) { from.CloseGump( typeof( XmlPlayerQuestGump ) ); if(from == null || from.Deleted || questitem == null || questitem.Deleted) return; m_From = from; m_QuestItem = questitem; int width = 600; //width = 516; X = (624 - width) / 2; AddPage( 0 ); AddBackground( 10, 10, width, 439, 5054 ); AddImageTiled( 18, 20, width - 17, 420, 2624 ); AddAlphaRegion( 18, 20, width - 17, 420 ); AddImage( 5, 5, 10460 ); AddImage( width - 15, 5, 10460 ); AddImage( 5, 424, 10460 ); AddImage( width - 15, 424, 10460 ); // add the Quest Title AddLabel( width/2 - 50, 15, 0x384, "Player Quest Maker" ); int y = 35; // add the Quest Name AddLabel( 28, y, 0x384, "Quest Name" ); string name = questitem.Name; if(name != null) { name = name.Substring(4); } AddImageTiled( 26, y + 20, 232, 20, 0xBBC ); AddTextEntry( 26, y + 20, 250, 20, 0, 100, name ); // add the Quest Title AddLabel( 328, y, 0x384, "Quest Title" ); AddImageTiled( 306, y + 20, 232, 20, 0xBBC ); AddTextEntry( 306, y + 20, 230, 20, 0, 102, questitem.TitleString ); y += 50; // add the Quest Text AddLabel( 28, y, 0x384, "Quest Text" ); AddImageTiled( 26, y + 20, 532, 80, 0xBBC ); AddTextEntry( 26, y + 20, 530, 80, 0, 103, questitem.NoteString ); y += 110; // add the Quest Expiration AddLabel( 28, y, 0x384, "Expiration" ); AddLabel( 98, y + 20, 0x384, "Hours" ); AddImageTiled( 26, y + 20, 52, 20, 0xBBC ); AddTextEntry( 26, y + 20, 50, 20, 0, 210, questitem.Expiration.ToString() ); y += 50; // add the Quest Objectives AddLabel( 28, y, 0x384, "Quest Objectives" ); AddImageTiled( 26, y + 20, 252, 19, 0xBBC ); AddTextEntry( 26, y + 20, 250, 19, 0, 200, questitem.Objective1 ); AddImageTiled( 26, y + 40, 252, 19, 0xBBC ); AddTextEntry( 26, y + 40, 250, 19, 0, 201, questitem.Objective2 ); AddImageTiled( 26, y + 60, 252, 19, 0xBBC ); AddTextEntry( 26, y + 60, 250, 19, 0, 202, questitem.Objective3 ); AddImageTiled( 26, y + 80, 252, 19, 0xBBC ); AddTextEntry( 26, y + 80, 250, 19, 0, 203, questitem.Objective4 ); AddImageTiled( 26, y + 100, 252, 19, 0xBBC ); AddTextEntry( 26, y + 100, 250, 19, 0, 204, questitem.Objective5 ); // add the Quest Objectives AddLabel( 328, y, 0x384, "Objective Descriptions" ); AddImageTiled( 306, y + 20, 252, 19, 0xBBC ); AddTextEntry( 306, y + 20, 250, 19, 0, 205, questitem.Description1 ); AddImageTiled( 306, y + 40, 252, 19, 0xBBC ); AddTextEntry( 306, y + 40, 250, 19, 0, 206, questitem.Description2 ); AddImageTiled( 306, y + 60, 252, 19, 0xBBC ); AddTextEntry( 306, y + 60, 250, 19, 0, 207, questitem.Description3 ); AddImageTiled( 306, y + 80, 252, 19, 0xBBC ); AddTextEntry( 306, y + 80, 250, 19, 0, 208, questitem.Description4 ); AddImageTiled( 306, y + 100, 252, 19, 0xBBC ); AddTextEntry( 306, y + 100, 250, 19, 0, 209, questitem.Description5 ); y += 130; // party enable toggle AddCheck( 25, y, 0xD2, 0xD3, questitem.PartyEnabled, 300); AddLabel( 48, y, 0x384, "PartyEnabled" ); y += 20; // can see toggle AddCheck( 25, y, 0xD2, 0xD3, questitem.CanSeeReward, 301); AddLabel( 48, y, 0x384, "CanSeeReward" ); // select reward button AddButton( 225, y+3, 2103, 2103, 1, GumpButtonType.Reply, 0 ); AddLabel( 245, y, 0x384, "Select Reward" ); // select reward button AddButton( 375, y+3, 2103, 2103, 2, GumpButtonType.Reply, 0 ); AddLabel( 395, y, 0x384, "Select Return Container" ); AddButton( 45, 416, 2130, 2129, 0, GumpButtonType.Reply, 0 ); // Okay button //AddButton( 375 - xoffset, 416, 4017, 4018, 0, GumpButtonType.Reply, 0 ); //AddHtmlLocalized( 410 - xoffset, 416, 120, 20, 1011441, LabelColor, false, false ); // EXIT } private class RewardTarget : Target { IXmlQuest m_QuestItem; public RewardTarget(IXmlQuest questitem) : base ( 30, true, TargetFlags.None ) { m_QuestItem = questitem; } protected override void OnTarget( Mobile from, object targeted ) { if(m_QuestItem == null || m_QuestItem.Deleted) return; // first check to see if you are too far from the return container. This is to avoid exploits involving targeting a container // then using the return reward feature as a free transport of items back to that container if(m_QuestItem.ReturnContainer != null && !m_QuestItem.ReturnContainer.Deleted) { Point3D returnloc; if(m_QuestItem.ReturnContainer.Parent == null) { returnloc = m_QuestItem.ReturnContainer.Location; } else if(m_QuestItem.ReturnContainer.RootParent != null) { returnloc = ((IEntity)m_QuestItem.ReturnContainer.RootParent).Location; } else { from.SendMessage("Invalid container location"); return; } if(!Utility.InRange( returnloc, from.Location, 10)) { // out of range from.SendMessage("Too far away from the reward return container"); return; } } // try to add the item as the reward item if(m_QuestItem.PlayerMade && (from != null) && !from.Deleted && (from is PlayerMobile) && (from == m_QuestItem.Creator) && (from == m_QuestItem.Owner) && (targeted is Item) && !(targeted is IXmlQuest)) { Item i = targeted as Item; // make sure the target item is in the oweners backpack if(i != null && !i.Deleted && i.RootParent == m_QuestItem.Owner) { m_QuestItem.RewardItem = i; m_QuestItem.AutoReward = true; } else { from.SendMessage("Targeted item must be in the owners pack"); } } } } private class ReturnTarget : Target { IXmlQuest m_QuestItem; public ReturnTarget(IXmlQuest questitem) : base ( 30, true, TargetFlags.None ) { m_QuestItem = questitem; } protected override void OnTarget( Mobile from, object targeted ) { if(m_QuestItem == null || m_QuestItem.Deleted) return; // try to add the item as the reward item if(m_QuestItem.PlayerMade && (from != null) && !from.Deleted && (from is PlayerMobile) && (from == m_QuestItem.Creator) && (from == m_QuestItem.Owner) && targeted is Container) { Container i = targeted as Container; // make sure the target item is in the oweners backpack if(i != null && !i.Deleted ) { m_QuestItem.ReturnContainer = i; from.SendMessage("Reward return container set"); } else { from.SendMessage("Targeted item must be a valid container"); } } } } } }
//------------------------------------------------------------------------------ // <copyright file="Logging.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Collections; using System.IO; using System.Threading; using System.Diagnostics; using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Globalization; using Microsoft.Win32; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; [FriendAccessAllowed] internal class Logging { #if MONO_FEATURE_LOGGING private static volatile bool s_LoggingEnabled = true; #else private static volatile bool s_LoggingEnabled = true; #endif private static volatile bool s_LoggingInitialized; private static volatile bool s_AppDomainShutdown; private const int DefaultMaxDumpSize = 1024; private const bool DefaultUseProtocolTextOnly = false; private const string AttributeNameMaxSize = "maxdatasize"; private const string AttributeNameTraceMode = "tracemode"; private static readonly string[] SupportedAttributes = new string[] { AttributeNameMaxSize, AttributeNameTraceMode }; private const string AttributeValueProtocolOnly = "protocolonly"; //private const string AttributeValueIncludeHex = "includehex"; private const string TraceSourceWebName = "System.Net"; private const string TraceSourceHttpListenerName = "System.Net.HttpListener"; private const string TraceSourceSocketsName = "System.Net.Sockets"; private const string TraceSourceWebSocketsName = "System.Net.WebSockets"; private const string TraceSourceCacheName = "System.Net.Cache"; private const string TraceSourceHttpName = "System.Net.Http"; private static TraceSource s_WebTraceSource; private static TraceSource s_HttpListenerTraceSource; private static TraceSource s_SocketsTraceSource; private static TraceSource s_WebSocketsTraceSource; private static TraceSource s_CacheTraceSource; private static TraceSource s_TraceSourceHttpName; private Logging() { } 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; } } [FriendAccessAllowed] internal static bool On { get { if (!s_LoggingInitialized) { InitializeLogging(); } return s_LoggingEnabled; } } internal static bool IsVerbose(TraceSource traceSource) { return ValidateSettings(traceSource, TraceEventType.Verbose); } internal static TraceSource Web { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_WebTraceSource; } } [FriendAccessAllowed] internal static TraceSource Http { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_TraceSourceHttpName; } } internal static TraceSource HttpListener { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_HttpListenerTraceSource; } } internal static TraceSource Sockets { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_SocketsTraceSource; } } internal static TraceSource RequestCache { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_CacheTraceSource; } } internal static TraceSource WebSockets { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_WebSocketsTraceSource; } } private static bool GetUseProtocolTextSetting(TraceSource traceSource) { bool useProtocolTextOnly = DefaultUseProtocolTextOnly; #if MONO_FEATURE_LOGGING if (traceSource.Attributes[AttributeNameTraceMode] == AttributeValueProtocolOnly) { useProtocolTextOnly = true; } #endif return useProtocolTextOnly; } private static int GetMaxDumpSizeSetting(TraceSource traceSource) { int maxDumpSize = DefaultMaxDumpSize; #if MONO_FEATURE_LOGGING if (traceSource.Attributes.ContainsKey(AttributeNameMaxSize)) { try { maxDumpSize = Int32.Parse(traceSource.Attributes[AttributeNameMaxSize], NumberFormatInfo.InvariantInfo); } catch (Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } traceSource.Attributes[AttributeNameMaxSize] = maxDumpSize.ToString(NumberFormatInfo.InvariantInfo); } } #endif return maxDumpSize; } /// <devdoc> /// <para>Sets up internal config settings for logging. (MUST be called under critsec) </para> /// </devdoc> private static void InitializeLogging() { #if MONO_FEATURE_LOGGING lock(InternalSyncObject) { if (!s_LoggingInitialized) { bool loggingEnabled = false; s_WebTraceSource = new NclTraceSource(TraceSourceWebName); s_HttpListenerTraceSource = new NclTraceSource(TraceSourceHttpListenerName); s_SocketsTraceSource = new NclTraceSource(TraceSourceSocketsName); s_WebSocketsTraceSource = new NclTraceSource(TraceSourceWebSocketsName); s_CacheTraceSource = new NclTraceSource(TraceSourceCacheName); s_TraceSourceHttpName = new NclTraceSource(TraceSourceHttpName); GlobalLog.Print("Initalizating tracing"); try { loggingEnabled = (s_WebTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_HttpListenerTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_SocketsTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_WebSocketsTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_CacheTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_TraceSourceHttpName.Switch.ShouldTrace(TraceEventType.Critical)); } catch (SecurityException) { // These may throw if the caller does not have permission to hook up trace listeners. // We treat this case as though logging were disabled. Close(); loggingEnabled = false; } if (loggingEnabled) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); currentDomain.DomainUnload += new EventHandler(AppDomainUnloadEvent); currentDomain.ProcessExit += new EventHandler(ProcessExitEvent); } s_LoggingEnabled = loggingEnabled; s_LoggingInitialized = true; } } #endif } [SuppressMessage("Microsoft.Security","CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Logging functions must work in partial trust mode")] private static void Close() { #if MONO_FEATURE_LOGGING if (s_WebTraceSource != null) s_WebTraceSource.Close(); if (s_HttpListenerTraceSource != null) s_HttpListenerTraceSource.Close(); if (s_SocketsTraceSource != null) s_SocketsTraceSource.Close(); if (s_WebSocketsTraceSource != null) s_WebSocketsTraceSource.Close(); if (s_CacheTraceSource != null) s_CacheTraceSource.Close(); if (s_TraceSourceHttpName != null) s_TraceSourceHttpName.Close(); #endif } /// <devdoc> /// <para>Logs any unhandled exception through this event handler</para> /// </devdoc> private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception) args.ExceptionObject; Exception(Web, sender, "UnhandledExceptionHandler", e); } private static void ProcessExitEvent(object sender, EventArgs e) { Close(); s_AppDomainShutdown = true; } /// <devdoc> /// <para>Called when the system is shutting down, used to prevent additional logging post-shutdown</para> /// </devdoc> private static void AppDomainUnloadEvent(object sender, EventArgs e) { Close(); s_AppDomainShutdown = true; } /// <devdoc> /// <para>Confirms logging is enabled, given current logging settings</para> /// </devdoc> private static bool ValidateSettings(TraceSource traceSource, TraceEventType traceLevel) { #if MONO_FEATURE_LOGGING if (!s_LoggingEnabled) { return false; } if (!s_LoggingInitialized) { InitializeLogging(); } if (traceSource == null || !traceSource.Switch.ShouldTrace(traceLevel)) { return false; } if (s_AppDomainShutdown) { return false; } return true; #else return false; #endif } /// <devdoc> /// <para>Converts an object to a normalized string that can be printed /// takes System.Net.ObjectNamedFoo and coverts to ObjectNamedFoo, /// except IPAddress, IPEndPoint, and Uri, which return ToString() /// </para> /// </devdoc> private static string GetObjectName(object obj) { if (obj is Uri || obj is System.Net.IPAddress || obj is System.Net.IPEndPoint) { return obj.ToString(); } else { return obj.GetType().Name; } } internal static uint GetThreadId() { #if MONO uint threadId = (uint)Thread.CurrentThread.ManagedThreadId; #else uint threadId = UnsafeNclNativeMethods.GetCurrentThreadId(); #endif if (threadId == 0) { threadId = (uint)Thread.CurrentThread.GetHashCode(); } return threadId; } internal static void PrintLine(TraceSource traceSource, TraceEventType eventType, int id, string msg) { #if MONO_FEATURE_LOGGING string logHeader = "["+GetThreadId().ToString("d4", CultureInfo.InvariantCulture)+"] " ; traceSource.TraceEvent(eventType, id, logHeader + msg); #endif } /// <devdoc> /// <para>Indicates that two objects are getting used with one another</para> /// </devdoc> [FriendAccessAllowed] internal static void Associate(TraceSource traceSource, object objA, object objB) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } string lineA = GetObjectName(objA) + "#" + ValidationHelper.HashString(objA); string lineB = GetObjectName(objB) + "#" + ValidationHelper.HashString(objB); PrintLine(traceSource, TraceEventType.Information, 0, "Associating " + lineA + " with " + lineB); } /// <devdoc> /// <para>Logs entrance to a function</para> /// </devdoc> [FriendAccessAllowed] internal static void Enter(TraceSource traceSource, object obj, string method, string param) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Enter(traceSource, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj), method, param); } /// <devdoc> /// <para>Logs entrance to a function</para> /// </devdoc> [FriendAccessAllowed] internal static void Enter(TraceSource traceSource, object obj, string method, object paramObject) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Enter(traceSource, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj), method, paramObject); } /// <devdoc> /// <para>Logs entrance to a function</para> /// </devdoc> internal static void Enter(TraceSource traceSource, string obj, string method, string param) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Enter(traceSource, obj +"::"+method+"("+param+")"); } /// <devdoc> /// <para>Logs entrance to a function</para> /// </devdoc> internal static void Enter(TraceSource traceSource, string obj, string method, object paramObject) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } string paramObjectValue = ""; if (paramObject != null) { paramObjectValue = GetObjectName(paramObject) + "#" + ValidationHelper.HashString(paramObject); } Enter(traceSource, obj +"::"+method+"("+paramObjectValue+")"); } /// <devdoc> /// <para>Logs entrance to a function, indents and points that out</para> /// </devdoc> internal static void Enter(TraceSource traceSource, string method, string parameters) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Enter(traceSource, method+"("+parameters+")"); } /// <devdoc> /// <para>Logs entrance to a function, indents and points that out</para> /// </devdoc> internal static void Enter(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } // Trace.CorrelationManager.StartLogicalOperation(); PrintLine(traceSource, TraceEventType.Verbose, 0, msg); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> [FriendAccessAllowed] internal static void Exit(TraceSource traceSource, object obj, string method, object retObject) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } string retValue = ""; if (retObject != null) { retValue = GetObjectName(retObject)+ "#" + ValidationHelper.HashString(retObject); } Exit(traceSource, obj, method, retValue); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> internal static void Exit(TraceSource traceSource, string obj, string method, object retObject) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } string retValue = ""; if (retObject != null) { retValue = GetObjectName(retObject) + "#" + ValidationHelper.HashString(retObject); } Exit(traceSource, obj, method, retValue); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> [FriendAccessAllowed] internal static void Exit(TraceSource traceSource, object obj, string method, string retValue) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Exit(traceSource, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj), method, retValue); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> internal static void Exit(TraceSource traceSource, string obj, string method, string retValue) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } if (!ValidationHelper.IsBlankString(retValue)) { retValue = "\t-> " + retValue; } Exit(traceSource, obj+"::"+method+"() "+retValue); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> internal static void Exit(TraceSource traceSource, string method, string parameters) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Exit(traceSource, method+"() "+parameters); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> internal static void Exit(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } PrintLine(traceSource, TraceEventType.Verbose, 0, "Exiting "+msg); // Trace.CorrelationManager.StopLogicalOperation(); } /// <devdoc> /// <para>Logs Exception, restores indenting</para> /// </devdoc> [FriendAccessAllowed] internal static void Exception(TraceSource traceSource, object obj, string method, Exception e) { if (!ValidateSettings(traceSource, TraceEventType.Error)) { return; } string infoLine = SR.GetString(SR.net_log_exception, GetObjectLogHash(obj), method, e.Message); if (!ValidationHelper.IsBlankString(e.StackTrace)) { infoLine += "\r\n" + e.StackTrace; } PrintLine(traceSource, TraceEventType.Error, 0, infoLine); } /// <devdoc> /// <para>Logs an Info line</para> /// </devdoc> internal static void PrintInfo(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } PrintLine(traceSource, TraceEventType.Information, 0, msg); } /// <devdoc> /// <para>Logs an Info line</para> /// </devdoc> [FriendAccessAllowed] internal static void PrintInfo(TraceSource traceSource, object obj, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } PrintLine(traceSource, TraceEventType.Information, 0, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +" - "+msg); } /// <devdoc> /// <para>Logs an Info line</para> /// </devdoc> internal static void PrintInfo(TraceSource traceSource, object obj, string method, string param) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } PrintLine(traceSource, TraceEventType.Information, 0, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +"::"+method+"("+param+")"); } /// <devdoc> /// <para>Logs a Warning line</para> /// </devdoc> [FriendAccessAllowed] internal static void PrintWarning(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Warning)) { return; } PrintLine(traceSource, TraceEventType.Warning, 0, msg); } /// <devdoc> /// <para>Logs a Warning line</para> /// </devdoc> internal static void PrintWarning(TraceSource traceSource, object obj, string method, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Warning)) { return; } PrintLine(traceSource, TraceEventType.Warning, 0, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +"::"+method+"() - "+msg); } /// <devdoc> /// <para>Logs an Error line</para> /// </devdoc> [FriendAccessAllowed] internal static void PrintError(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Error)) { return; } PrintLine(traceSource, TraceEventType.Error, 0, msg); } /// <devdoc> /// <para>Logs an Error line</para> /// </devdoc> [FriendAccessAllowed] internal static void PrintError(TraceSource traceSource, object obj, string method, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Error)) { return; } PrintLine(traceSource, TraceEventType.Error, 0, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +"::"+method+"() - "+msg); } [FriendAccessAllowed] internal static string GetObjectLogHash(object obj) { return GetObjectName(obj) + "#" + ValidationHelper.HashString(obj); } /// <devdoc> /// <para>Marhsalls a buffer ptr to an array and then dumps the byte array to the log</para> /// </devdoc> internal static void Dump(TraceSource traceSource, object obj, string method, IntPtr bufferPtr, int length) { if (!ValidateSettings(traceSource, TraceEventType.Verbose) || bufferPtr == IntPtr.Zero || length < 0) { return; } byte [] buffer = new byte[length]; Marshal.Copy(bufferPtr, buffer, 0, length); Dump(traceSource, obj, method, buffer, 0, length); } /// <devdoc> /// <para>Dumps a byte array to the log</para> /// </devdoc> internal static void Dump(TraceSource traceSource, object obj, string method, byte[] buffer, int offset, int length) { if (!ValidateSettings(traceSource, TraceEventType.Verbose)) { return; } if (buffer == null) { PrintLine(traceSource, TraceEventType.Verbose, 0, "(null)"); return; } if (offset > buffer.Length) { PrintLine(traceSource, TraceEventType.Verbose, 0, "(offset out of range)"); return; } PrintLine(traceSource, TraceEventType.Verbose, 0, "Data from "+GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +"::"+method); int maxDumpSize = GetMaxDumpSizeSetting(traceSource); if (length > maxDumpSize) { PrintLine(traceSource, TraceEventType.Verbose, 0, "(printing " + maxDumpSize.ToString(NumberFormatInfo.InvariantInfo) + " out of " + length.ToString(NumberFormatInfo.InvariantInfo) + ")"); length = maxDumpSize; } if ((length < 0) || (length > buffer.Length - offset)) { length = buffer.Length - offset; } #if MONO_FEATURE_WEB_STACK if (GetUseProtocolTextSetting(traceSource)) { string output = "<<" + WebHeaderCollection.HeaderEncoding.GetString(buffer, offset, length) + ">>"; PrintLine(traceSource, TraceEventType.Verbose, 0, output); return; } #endif do { int n = Math.Min(length, 16); string disp = String.Format(CultureInfo.CurrentCulture, "{0:X8} : ", offset); for (int i = 0; i < n; ++i) { disp += String.Format(CultureInfo.CurrentCulture, "{0:X2}", buffer[offset + i]) + ((i == 7) ? '-' : ' '); } for (int i = n; i < 16; ++i) { disp += " "; } disp += ": "; for (int i = 0; i < n; ++i) { disp += ((buffer[offset + i] < 0x20) || (buffer[offset + i] > 0x7e)) ? '.' : (char)(buffer[offset + i]); } PrintLine(traceSource, TraceEventType.Verbose, 0, disp); offset += n; length -= n; } while (length > 0); } #if MONO_FEATURE_LOGGING private class NclTraceSource : TraceSource { internal NclTraceSource(string name) : base(name) { } protected internal override string[] GetSupportedAttributes() { return Logging.SupportedAttributes; } } #endif } }
using System; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Windows.Input; using Android.Runtime; using Android.Support.V7.Widget; using Android.Views; using Com.H6ah4i.Android.Widget.Advrecyclerview.Expandable; using Com.H6ah4i.Android.Widget.Advrecyclerview.Swipeable; using Com.H6ah4i.Android.Widget.Advrecyclerview.Swipeable.Action; using Com.H6ah4i.Android.Widget.Advrecyclerview.Utils; using MvvmCross.AdvancedRecyclerView.Data; using MvvmCross.AdvancedRecyclerView.Data.EventArguments; using MvvmCross.AdvancedRecyclerView.Data.ItemUniqueIdProvider; using MvvmCross.AdvancedRecyclerView.Extensions; using MvvmCross.AdvancedRecyclerView.Swipe.ResultActions; using MvvmCross.AdvancedRecyclerView.Swipe.ResultActions.ItemManager; using MvvmCross.AdvancedRecyclerView.Swipe.State; using MvvmCross.AdvancedRecyclerView.TemplateSelectors; using MvvmCross.AdvancedRecyclerView.Utils; using MvvmCross.AdvancedRecyclerView.ViewHolders; using MvvmCross.Binding.Extensions; using MvvmCross.Droid.Support.V7.RecyclerView; using MvvmCross.Droid.Support.V7.RecyclerView.ItemTemplates; using MvvmCross.Exceptions; using MvvmCross.Logging; using MvvmCross.Platforms.Android.Binding.BindingContext; using Object = Java.Lang.Object; namespace MvvmCross.AdvancedRecyclerView.Adapters.Expandable { public class MvxExpandableItemAdapter : AbstractExpandableItemAdapter, IExpandableSwipeableItemAdapter, IMvxAdvancedRecyclerViewAdapter { private readonly Lazy<DefaultSwipeableTemplate> _lazyDefaultSwipeableTemplate = new Lazy<DefaultSwipeableTemplate>(); private readonly MvxGroupedItemsSourceProvider _expandableGroupedItemsSourceProvider; private IEnumerable itemsSource; private MvxSwipeableTemplate groupedSwipeableTemplate; private MvxSwipeableTemplate childSwipeableTemplate; public MvxExpandableItemAdapter() : this(MvxAndroidBindingContextHelpers.Current()) { } public MvxExpandableItemAdapter(IMvxAndroidBindingContext androidBindingContext) { BindingContext = androidBindingContext; SetHasStableIds(true); _expandableGroupedItemsSourceProvider = new MvxGroupedItemsSourceProvider(); _expandableGroupedItemsSourceProvider.Source.CollectionChanged += SourceOnCollectionChanged; _expandableGroupedItemsSourceProvider.ChildItemsAdded += SourceItemChildChanged; _expandableGroupedItemsSourceProvider.ChildItemsRemoved += SourceItemChildChanged; _expandableGroupedItemsSourceProvider.ChildItemsCollectionCleared += (group) => base.NotifyDataSetChanged(); _expandableGroupedItemsSourceProvider.ItemsMovedOrReplaced += () => base.NotifyDataSetChanged(); GroupSwipeItemPinnedStateController = new SwipeItemPinnedStateControllerProvider() { UniqueIdProvider = new GroupMvxItemUniqueIdProvider(this) }; ChildSwipeItemPinnedStateController = new SwipeItemPinnedStateControllerProvider() { UniqueIdProvider = new GroupChildMvxItemUniqueIdProvider(this) }; } protected MvxExpandableItemAdapter(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } IntPtr pointerToSetHasStableId = IntPtr.Zero; IntPtr class_ref = IntPtr.Zero; [Register("setHasStableIds", "(Z)V", "")] public unsafe void SetHasStableIds(bool hasStableIds) { if (pointerToSetHasStableId == IntPtr.Zero) { class_ref = JNIEnv.FindClass(typeof(RecyclerView.Adapter)); pointerToSetHasStableId = JNIEnv.GetMethodID(class_ref, "setHasStableIds", "(Z)V"); } try { JValue* __args = stackalloc JValue[1]; __args[0] = new JValue(hasStableIds); JNIEnv.CallVoidMethod(this.Handle, pointerToSetHasStableId, __args); } finally { } } protected IMvxAndroidBindingContext BindingContext { get; } public IMvxTemplateSelector TemplateSelector { get; set; } private ObservableCollection<object> GroupedItems => _expandableGroupedItemsSourceProvider.Source; public IEnumerable ItemsSource { get => itemsSource; set { if (ReferenceEquals(itemsSource, value)) return; itemsSource = value; _expandableGroupedItemsSourceProvider.Initialize(itemsSource, ExpandableDataConverter); NotifyDataSetChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } public MvxExpandableDataConverter ExpandableDataConverter { get; set; } public MvxGroupExpandController GroupExpandController { get; internal set; } = new DefaultMvxGroupExpandController(); public override int GroupCount => GroupedItems.Count(); public ICommand GroupItemClickCommand { get; set; } public ICommand GroupItemLongClickCommand { get; set; } public ICommand ChildItemClickCommand { get; set; } public ICommand ChildItemLongClickCommand { get; set; } void SourceItemChildChanged(Data.MvxGroupedData gropedData, IEnumerable newItems) { base.NotifyDataSetChanged(); } private void SourceOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { NotifyDataSetChanged(notifyCollectionChangedEventArgs); } public virtual void NotifyDataSetChanged(NotifyCollectionChangedEventArgs e) { try { NotifyDataSetChanged(); return; } catch (Exception exception) { Mvx.Resolve<IMvxLog>().Log(MvxLogLevel.Warn, () => $"Exception masked during Adapter RealNotifyDataSetChanged {exception.ToLongString()}. Are you trying to update your collection from a background task? See http://goo.gl/0nW0L6" ); } } public override bool OnCheckCanExpandOrCollapseGroup(Object holder, int groupPosition, int x, int y, bool expand) { var groupItemDetails = new MvxGroupDetails { Holder = holder as RecyclerView.ViewHolder, Item = GroupedItems.ElementAt(groupPosition) as MvxGroupedData, GroupIndex = groupPosition }; if (expand) return GroupExpandController.CanExpandGroup(groupItemDetails); return GroupExpandController.CanCollapseGroup(groupItemDetails); } public override Object OnCreateChildViewHolder(ViewGroup parent, int viewType) { var itemBindingContext = new MvxAndroidBindingContext(parent.Context, BindingContext.LayoutInflaterHolder); var viewHolder = new MvxExpandableRecyclerViewHolder( InflateViewForHolder(TemplateSelector.GetItemLayoutId(viewType), parent, viewType, itemBindingContext), ChildSwipeableTemplate.SwipeContainerViewGroupId, ChildSwipeableTemplate.UnderSwipeContainerViewGroupId, itemBindingContext) { }; viewHolder.Click += (e, a) => { if (ChildItemClickCommand?.CanExecute(viewHolder.DataContext) ?? false) ChildItemClickCommand.Execute(viewHolder.DataContext); }; viewHolder.LongClick += (e, a) => { if (ChildItemLongClickCommand?.CanExecute(viewHolder.DataContext) ?? false) ChildItemLongClickCommand.Execute(viewHolder.DataContext); }; return viewHolder; } public override Object OnCreateGroupViewHolder(ViewGroup parent, int viewType) { var itemBindingContext = new MvxAndroidBindingContext(parent.Context, BindingContext.LayoutInflaterHolder); var viewHolder = new MvxExpandableRecyclerViewHolder( InflateViewForHolder(TemplateSelector.GetItemLayoutId(viewType), parent, viewType, itemBindingContext), GroupSwipeableTemplate.SwipeContainerViewGroupId, GroupSwipeableTemplate.UnderSwipeContainerViewGroupId, itemBindingContext) { }; viewHolder.Click += (e, a) => { if (GroupItemClickCommand?.CanExecute(viewHolder.DataContext) ?? false) GroupItemClickCommand.Execute(viewHolder.DataContext); }; viewHolder.LongClick += (e, a) => { if (GroupItemLongClickCommand?.CanExecute(viewHolder.DataContext) ?? false) GroupItemLongClickCommand.Execute(viewHolder.DataContext); }; return viewHolder; } public override bool OnHookGroupCollapse(int p0, bool p1) => GroupExpandController.OnHookGroupCollapse(new MvxHookGroupExpandCollapseArgs { DataContext = GetItemAt(p0), GroupPosition = p0, RequestedByUser = p1 }); public override bool OnHookGroupExpand(int p0, bool p1) => GroupExpandController.OnHookGroupExpand(new MvxHookGroupExpandCollapseArgs { DataContext = GetItemAt(p0), GroupPosition = p0, RequestedByUser = p1 }); protected virtual View InflateViewForHolder(int layoutId, ViewGroup parent, int viewType, IMvxAndroidBindingContext bindingContext) { return bindingContext.BindingInflate(layoutId, parent, false); } public override void OnBindChildViewHolder(Object viewHolder, int groupPosition, int childPosition, int viewType) { var dataContext = GetItemAt(groupPosition, childPosition); var advancedRecyclerViewHolder = viewHolder as MvxAdvancedRecyclerViewHolder; advancedRecyclerViewHolder.DataContext = dataContext; OnChildItemBound(new MvxExpandableItemAdapterBoundedArgs { ViewHolder = viewHolder as MvxExpandableRecyclerViewHolder, DataContext = dataContext }); if (ChildSwipeableTemplate != null) { advancedRecyclerViewHolder.MaxLeftSwipeAmount = ChildSwipeableTemplate.GetMaxLeftSwipeAmount(dataContext, advancedRecyclerViewHolder); advancedRecyclerViewHolder.MaxRightSwipeAmount = ChildSwipeableTemplate.GetMaxRightSwipeAmount(dataContext, advancedRecyclerViewHolder); advancedRecyclerViewHolder.MaxDownSwipeAmount = ChildSwipeableTemplate.GetMaxDownSwipeAmount(dataContext, advancedRecyclerViewHolder); advancedRecyclerViewHolder.MaxUpSwipeAmount = ChildSwipeableTemplate.GetMaxUpSwipeAmount(dataContext, advancedRecyclerViewHolder); ChildSwipeableTemplate.SetupUnderSwipeBackground(advancedRecyclerViewHolder); ChildSwipeableTemplate.SetupSlideAmount(advancedRecyclerViewHolder, ChildSwipeItemPinnedStateController); } } public override void OnBindGroupViewHolder(Object viewHolder, int groupPosition, int viewType) { var dataContext = GetItemAt(groupPosition); var advancedRecyclerViewHolder = viewHolder as MvxAdvancedRecyclerViewHolder; advancedRecyclerViewHolder.DataContext = dataContext; OnGroupItemBound(new MvxExpandableItemAdapterBoundedArgs { ViewHolder = viewHolder as MvxExpandableRecyclerViewHolder, DataContext = dataContext }); if (GroupSwipeableTemplate != null) { advancedRecyclerViewHolder.MaxLeftSwipeAmount = GroupSwipeableTemplate.GetMaxLeftSwipeAmount(dataContext, advancedRecyclerViewHolder); advancedRecyclerViewHolder.MaxRightSwipeAmount = GroupSwipeableTemplate.GetMaxRightSwipeAmount(dataContext, advancedRecyclerViewHolder); advancedRecyclerViewHolder.MaxDownSwipeAmount = GroupSwipeableTemplate.GetMaxDownSwipeAmount(dataContext, advancedRecyclerViewHolder); advancedRecyclerViewHolder.MaxUpSwipeAmount = GroupSwipeableTemplate.GetMaxUpSwipeAmount(dataContext, advancedRecyclerViewHolder); GroupSwipeableTemplate.SetupUnderSwipeBackground(advancedRecyclerViewHolder); GroupSwipeableTemplate.SetupSlideAmount(advancedRecyclerViewHolder, GroupSwipeItemPinnedStateController); } } public override int GetChildCount(int p0) { if (GroupedItems.Count() <= p0) return 0; return (GroupedItems.ElementAt(p0) as MvxGroupedData).GroupItems.Count(); } public override long GetChildId(int p0, int p1) { var childItem = GetItemAt(p0, p1); return ExpandableDataConverter.GetItemUniqueId(childItem); } public override long GetGroupId(int p0) { var mvxGroupedData = GetItemAt(p0); return ExpandableDataConverter.GetItemUniqueId(mvxGroupedData); } public override bool GetInitialGroupExpandedState (int groupPosition) { return GroupExpandController.GetInitialGroupExpandedState (groupPosition); } public MvxGroupedData GetItemAt(int groupIndex) => GroupedItems.ElementAt(groupIndex) as MvxGroupedData; public object GetItemAt(int groupIndex, int childIndex) => GetItemAt(groupIndex).GroupItems.ElementAt(childIndex); public event Action<MvxExpandableItemAdapterBoundedArgs> GroupItemBound; public event Action<MvxExpandableItemAdapterBoundedArgs> ChildItemBound; public override int GetGroupItemViewType(int p0) => TemplateSelector.GetItemViewType(GetItemAt(p0)); public override int GetChildItemViewType(int p0, int p1) => TemplateSelector.GetItemViewType(GetItemAt(p0, p1)); protected virtual void OnGroupItemBound(MvxExpandableItemAdapterBoundedArgs obj) { GroupItemBound?.Invoke(obj); } protected virtual void OnChildItemBound(MvxExpandableItemAdapterBoundedArgs obj) { ChildItemBound?.Invoke(obj); } public MvxSwipeableTemplate GroupSwipeableTemplate { get => groupedSwipeableTemplate ?? _lazyDefaultSwipeableTemplate.Value; set => groupedSwipeableTemplate = value; } public MvxSwipeableTemplate ChildSwipeableTemplate { get => childSwipeableTemplate ?? _lazyDefaultSwipeableTemplate.Value; set => childSwipeableTemplate = value; } public MvxSwipeResultActionFactory GroupSwipeResultActionFactory => GroupSwipeableTemplate?.SwipeResultActionFactory ?? new MvxSwipeResultActionFactory(); public MvxSwipeResultActionFactory ChildSwipeResultActionFactory => ChildSwipeableTemplate?.SwipeResultActionFactory ?? new MvxSwipeResultActionFactory(); public SwipeItemPinnedStateControllerProvider GroupSwipeItemPinnedStateController { get; } public SwipeItemPinnedStateControllerProvider ChildSwipeItemPinnedStateController { get; } public int OnGetChildItemSwipeReactionType(Object p0, int p1, int p2, int x, int y) { var viewHolder = p0 as MvxExpandableRecyclerViewHolder; return viewHolder.SwipeableContainerView.HitTest(x, y) ? ChildSwipeableTemplate.GetSwipeReactionType(viewHolder.DataContext, viewHolder) : SwipeableItemConstants.ReactionCanNotSwipeAny; } public int OnGetGroupItemSwipeReactionType(Object p0, int p1, int x, int y) { var viewHolder = p0 as MvxExpandableRecyclerViewHolder; return viewHolder.SwipeableContainerView.HitTest(x, y) ? GroupSwipeableTemplate.GetSwipeReactionType(viewHolder.DataContext, viewHolder) : SwipeableItemConstants.ReactionCanNotSwipeAny; } public void OnSetChildItemSwipeBackground(Object p0, int position, int childPosition, int type) { var advancedViewHolder = p0 as MvxAdvancedRecyclerViewHolder; var args = new MvxChildSwipeBackgroundSetEventARgs() { ViewHolder = advancedViewHolder, Position = position, ChildPosition = childPosition, Type = type }; ChildItemSwipeBackgroundSet?.Invoke(args); ChildSwipeableTemplate?.OnSwipeBackgroundSet(args); } public void OnSetGroupItemSwipeBackground(Object p0, int position, int type) { var advancedViewHolder = p0 as MvxAdvancedRecyclerViewHolder; var args = new MvxGroupSwipeBackgroundSetEventArgs() { ViewHolder = advancedViewHolder, Position = position, Type = type }; GroupItemSwipeBackgroundSet?.Invoke(args); GroupSwipeableTemplate?.OnSwipeBackgroundSet(args); } public void OnSwipeChildItemStarted(Object p0, int p1, int p2) { this.NotifyDataSetChanged(); } public void OnSwipeGroupItemStarted(Object p0, int p1) { this.NotifyDataSetChanged(); } public SwipeResultAction OnSwipeChildItem(Object p0, int groupPosition, int childPosition, int result) { switch (result) { case SwipeableItemConstants.ResultSwipedDown: return ChildSwipeResultActionFactory.GetSwipeDownResultAction(new ExpandableGroupChildSwipeResultActionItemManager(this, groupPosition, childPosition)); case SwipeableItemConstants.ResultSwipedLeft: return ChildSwipeResultActionFactory.GetSwipeLeftResultAction(new ExpandableGroupChildSwipeResultActionItemManager(this, groupPosition, childPosition)); case SwipeableItemConstants.ResultSwipedRight: return ChildSwipeResultActionFactory.GetSwipeRightResultAction(new ExpandableGroupChildSwipeResultActionItemManager(this, groupPosition, childPosition)); case SwipeableItemConstants.ResultSwipedUp: return ChildSwipeResultActionFactory.GetSwipeUpResultAction(new ExpandableGroupChildSwipeResultActionItemManager(this, groupPosition, childPosition)); default: return groupPosition != RecyclerView.NoPosition && childPosition != RecyclerView.NoPosition ? ChildSwipeResultActionFactory.GetUnpinSwipeResultAction(new ExpandableGroupChildSwipeResultActionItemManager(this, groupPosition, childPosition)) : new SwipeResultActionDoNothing(); } } public SwipeResultAction OnSwipeGroupItem(Object p0, int groupPosition, int result) { switch (result) { case SwipeableItemConstants.ResultSwipedDown: return GroupSwipeResultActionFactory.GetSwipeDownResultAction(new ExpandableGroupSwipeResultActionItemManager(this, groupPosition)); case SwipeableItemConstants.ResultSwipedLeft: return GroupSwipeResultActionFactory.GetSwipeLeftResultAction(new ExpandableGroupSwipeResultActionItemManager(this, groupPosition)); case SwipeableItemConstants.ResultSwipedRight: return GroupSwipeResultActionFactory.GetSwipeRightResultAction(new ExpandableGroupSwipeResultActionItemManager(this, groupPosition)); case SwipeableItemConstants.ResultSwipedUp: return GroupSwipeResultActionFactory.GetSwipeUpResultAction(new ExpandableGroupSwipeResultActionItemManager(this, groupPosition)); default: return groupPosition != RecyclerView.NoPosition ? GroupSwipeResultActionFactory.GetUnpinSwipeResultAction(new ExpandableGroupSwipeResultActionItemManager(this, groupPosition)) : new SwipeResultActionDoNothing(); } } public event Action<MvxGroupSwipeBackgroundSetEventArgs> GroupItemSwipeBackgroundSet; public event Action<MvxChildSwipeBackgroundSetEventARgs> ChildItemSwipeBackgroundSet; } }
namespace MHDiff { using System; using System.Collections; using System.Text; using System.Text.RegularExpressions; /// <summary> /// This Class implements the Difference Algorithm published in /// "An O(ND) Difference Algorithm and its Variations" by Eugene Myers /// Algorithmica Vol. 1 No. 2, 1986, p 251. /// /// There are many C, Java, Lisp implementations public available but they all seem to come /// from the same source (diffutils) that is under the (unfree) GNU public License /// and cannot be reused as a sourcecode for a commercial application. /// There are very old C implementations that use other (worse) algorithms. /// Microsoft also published sourcecode of a diff-tool (windiff) that uses some tree data. /// Also, a direct transfer from a C source to C# is not easy because there is a lot of pointer /// arithmetic in the typical C solutions and i need a managed solution. /// These are the reasons why I implemented the original published algorithm from the scratch and /// make it avaliable without the GNU license limitations. /// I do not need a high performance diff tool because it is used only sometimes. /// I will do some performace tweaking when needed. /// /// The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents /// each line is converted into a (hash) number. See DiffText(). /// /// Some chages to the original algorithm: /// The original algorithm was described using a recursive approach and comparing zero indexed arrays. /// Extracting sub-arrays and rejoining them is very performance and memory intensive so the same /// (readonly) data arrays are passed arround together with their lower and upper bounds. /// This circumstance makes the LCS and SMS functions more complicate. /// I added some code to the LCS function to get a fast response on sub-arrays that are identical, /// completely deleted or inserted. /// /// The result from a comparisation is stored in 2 arrays that flag for modified (deleted or inserted) /// lines in the 2 data arrays. These bits are then analysed to produce a array of Item objects. /// /// Further possible optimizations: /// (first rule: don't do it; second: don't do it yet) /// The arrays DataA and DataB are passed as parameters, but are never changed after the creation /// so they can be members of the class to avoid the paramter overhead. /// In SMS is a lot of boundary arithmetic in the for-D and for-k loops that can be done by increment /// and decrement of local variables. /// The DownVector and UpVector arrays are alywas created and destroyed each time the SMS gets called. /// It is possible to reuse tehm when transfering them to members of the class. /// See TODO: hints. /// /// diff.cs: A port of the algorythm to C# /// Copyright (c) by Matthias Hertel, http://www.mathertel.de /// This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx /// /// Changes: /// 2002.09.20 There was a "hang" in some situations. /// Now I undestand a little bit more of the SMS algorithm. /// There have been overlapping boxes; that where analyzed partial differently. /// One return-point is enough. /// A assertion was added in CreateDiffs when in debug-mode, that counts the number of equal (no modified) lines in both arrays. /// They must be identical. /// /// 2003.02.07 Out of bounds error in the Up/Down vector arrays in some situations. /// The two vetors are now accessed using different offsets that are adjusted using the start k-Line. /// A test case is added. /// /// 2006.03.05 Some documentation and a direct Diff entry point. /// /// 2006.03.08 Refactored the API to static methods on the Diff class to make usage simpler. /// 2006.03.10 using the standard Debug class for self-test now. /// compile with: csc /target:exe /out:diffTest.exe /d:DEBUG /d:TRACE /d:SELFTEST Diff.cs /// 2007.01.06 license agreement changed to a BSD style license. /// 2007.06.03 added the Optimize method. /// 2007.09.23 UpVector and DownVector optimization by Jan Stoklasa (). /// 2008.05.31 Adjusted the testing code that failed because of the Optimize method (not a bug in the diff algorithm). /// 2008.10.08 Fixing a test case and adding a new test case. /// </summary> public class Diff { /// <summary>details of one difference.</summary> public struct Item { /// <summary>Start Line number in Data A.</summary> public int StartA; /// <summary>Start Line number in Data B.</summary> public int StartB; /// <summary>Number of changes in Data A.</summary> public int deletedA; /// <summary>Number of changes in Data B.</summary> public int insertedB; } // Item /// <summary> /// Shortest Middle Snake Return Data /// </summary> private struct SMSRD { internal int x, y; // internal int u, v; // 2002.09.20: no need for 2 points } #region self-Test #if (SELFTEST) /// <summary> /// start a self- / box-test for some diff cases and report to the debug output. /// </summary> /// <param name="args">not used</param> /// <returns>always 0</returns> public static int Main(string[] args) { StringBuilder ret = new StringBuilder(); string a, b; System.Diagnostics.ConsoleTraceListener ctl = new System.Diagnostics.ConsoleTraceListener(false); System.Diagnostics.Debug.Listeners.Add(ctl); System.Console.WriteLine("Diff Self Test..."); // test all changes a = "a,b,c,d,e,f,g,h,i,j,k,l".Replace(',', '\n'); b = "0,1,2,3,4,5,6,7,8,9".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "12.10.0.0*", "all-changes test failed."); System.Diagnostics.Debug.WriteLine("all-changes test passed."); // test all same a = "a,b,c,d,e,f,g,h,i,j,k,l".Replace(',', '\n'); b = a; System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "", "all-same test failed."); System.Diagnostics.Debug.WriteLine("all-same test passed."); // test snake a = "a,b,c,d,e,f".Replace(',', '\n'); b = "b,c,d,e,f,x".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "1.0.0.0*0.1.6.5*", "snake test failed."); System.Diagnostics.Debug.WriteLine("snake test passed."); // 2002.09.20 - repro a = "c1,a,c2,b,c,d,e,g,h,i,j,c3,k,l".Replace(',', '\n'); b = "C1,a,C2,b,c,d,e,I1,e,g,h,i,j,C3,k,I2,l".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "1.1.0.0*1.1.2.2*0.2.7.7*1.1.11.13*0.1.13.15*", "repro20020920 test failed."); System.Diagnostics.Debug.WriteLine("repro20020920 test passed."); // 2003.02.07 - repro a = "F".Replace(',', '\n'); b = "0,F,1,2,3,4,5,6,7".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "0.1.0.0*0.7.1.2*", "repro20030207 test failed."); System.Diagnostics.Debug.WriteLine("repro20030207 test passed."); // Muegel - repro a = "HELLO\nWORLD"; b = "\n\nhello\n\n\n\nworld\n"; System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "2.8.0.0*", "repro20030409 test failed."); System.Diagnostics.Debug.WriteLine("repro20030409 test passed."); // test some differences a = "a,b,-,c,d,e,f,f".Replace(',', '\n'); b = "a,b,x,c,e,f".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "1.1.2.2*1.0.4.4*1.0.7.6*", "some-changes test failed."); System.Diagnostics.Debug.WriteLine("some-changes test passed."); // test one change within long chain of repeats a = "a,a,a,a,a,a,a,a,a,a".Replace(',', '\n'); b = "a,a,a,a,-,a,a,a,a,a".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "0.1.4.4*1.0.9.10*", "long chain of repeats test failed."); System.Diagnostics.Debug.WriteLine("End."); System.Diagnostics.Debug.Flush(); return (0); } public static string TestHelper(Item []f) { StringBuilder ret = new StringBuilder(); for (int n = 0; n < f.Length; n++) { ret.Append(f[n].deletedA.ToString() + "." + f[n].insertedB.ToString() + "." + f[n].StartA.ToString() + "." + f[n].StartB.ToString() + "*"); } // Debug.Write(5, "TestHelper", ret.ToString()); return (ret.ToString()); } #endif #endregion /// <summary> /// Find the difference in 2 texts, comparing by textlines. /// </summary> /// <param name="TextA">A-version of the text (usualy the old one)</param> /// <param name="TextB">B-version of the text (usualy the new one)</param> /// <returns>Returns a array of Items that describe the differences.</returns> public static Item[] DiffText(string TextA, string TextB) { return (DiffText(TextA, TextB, false, false, false)); } // DiffText /// <summary> /// Find the difference in 2 text documents, comparing by textlines. /// The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents /// each line is converted into a (hash) number. This hash-value is computed by storing all /// textlines into a common hashtable so i can find dublicates in there, and generating a /// new number each time a new textline is inserted. /// </summary> /// <param name="TextA">A-version of the text (usualy the old one)</param> /// <param name="TextB">B-version of the text (usualy the new one)</param> /// <param name="trimSpace">When set to true, all leading and trailing whitespace characters are stripped out before the comparation is done.</param> /// <param name="ignoreSpace">When set to true, all whitespace characters are converted to a single space character before the comparation is done.</param> /// <param name="ignoreCase">When set to true, all characters are converted to their lowercase equivivalence before the comparation is done.</param> /// <returns>Returns a array of Items that describe the differences.</returns> public static Item[] DiffText(string TextA, string TextB, bool trimSpace, bool ignoreSpace, bool ignoreCase) { var r = DiffTextAB(TextA, TextB, trimSpace, ignoreSpace, ignoreCase); return CreateDiffs(r.Item2, r.Item2); } public static Tuple<DiffData, DiffData> DiffTextAB(string TextA, string TextB, bool trimSpace, bool ignoreSpace, bool ignoreCase) { // prepare the input-text and convert to comparable numbers. Hashtable h = new Hashtable(TextA.Length + TextB.Length); // The A-Version of the data (original data) to be compared. DiffData DataA = new DiffData(DiffCodes(TextA, h, trimSpace, ignoreSpace, ignoreCase)); // The B-Version of the data (modified data) to be compared. DiffData DataB = new DiffData(DiffCodes(TextB, h, trimSpace, ignoreSpace, ignoreCase)); h = null; // free up hashtable memory (maybe) int MAX = DataA.Length + DataB.Length + 1; /// vector for the (0,0) to (x,y) search int[] DownVector = new int[2 * MAX + 2]; /// vector for the (u,v) to (N,M) search int[] UpVector = new int[2 * MAX + 2]; LCS(DataA, 0, DataA.Length, DataB, 0, DataB.Length, DownVector, UpVector); Optimize(DataA); Optimize(DataB); return new Tuple<DiffData, DiffData>(DataA, DataB); } // DiffText /// <summary> /// If a sequence of modified lines starts with a line that contains the same content /// as the line that appends the changes, the difference sequence is modified so that the /// appended line and not the starting line is marked as modified. /// This leads to more readable diff sequences when comparing text files. /// </summary> /// <param name="Data">A Diff data buffer containing the identified changes.</param> private static void Optimize(DiffData Data) { int StartPos, EndPos; StartPos = 0; while (StartPos < Data.Length) { while ((StartPos < Data.Length) && (Data.modified[StartPos] == false)) StartPos++; EndPos = StartPos; while ((EndPos < Data.Length) && (Data.modified[EndPos] == true)) EndPos++; if ((EndPos < Data.Length) && (Data.data[StartPos] == Data.data[EndPos])) { Data.modified[StartPos] = false; Data.modified[EndPos] = true; } else { StartPos = EndPos; } // if } // while } // Optimize /// <summary> /// Find the difference in 2 arrays of integers. /// </summary> /// <param name="ArrayA">A-version of the numbers (usualy the old one)</param> /// <param name="ArrayB">B-version of the numbers (usualy the new one)</param> /// <returns>Returns a array of Items that describe the differences.</returns> public static Item[] DiffInt(int[] ArrayA, int[] ArrayB) { // The A-Version of the data (original data) to be compared. DiffData DataA = new DiffData(ArrayA); // The B-Version of the data (modified data) to be compared. DiffData DataB = new DiffData(ArrayB); int MAX = DataA.Length + DataB.Length + 1; /// vector for the (0,0) to (x,y) search int[] DownVector = new int[2 * MAX + 2]; /// vector for the (u,v) to (N,M) search int[] UpVector = new int[2 * MAX + 2]; LCS(DataA, 0, DataA.Length, DataB, 0, DataB.Length, DownVector, UpVector); return CreateDiffs(DataA, DataB); } // Diff /// <summary> /// This function converts all textlines of the text into unique numbers for every unique textline /// so further work can work only with simple numbers. /// </summary> /// <param name="aText">the input text</param> /// <param name="h">This extern initialized hashtable is used for storing all ever used textlines.</param> /// <param name="trimSpace">ignore leading and trailing space characters</param> /// <returns>a array of integers.</returns> private static int[] DiffCodes(string aText, Hashtable h, bool trimSpace, bool ignoreSpace, bool ignoreCase) { // get all codes of the text string[] Lines; int[] Codes; int lastUsedCode = h.Count; object aCode; string s; // strip off all cr, only use lf as textline separator. aText = aText.Replace("\r", ""); Lines = aText.Split('\n'); Codes = new int[Lines.Length]; for (int i = 0; i < Lines.Length; ++i) { s = Lines[i]; if (trimSpace) s = s.Trim(); if (ignoreSpace) { s = Regex.Replace(s, "\\s+", " "); // TODO: optimization: faster blank removal. } if (ignoreCase) s = s.ToLower(); aCode = h[s]; if (aCode == null) { lastUsedCode++; h[s] = lastUsedCode; Codes[i] = lastUsedCode; } else { Codes[i] = (int)aCode; } // if } // for return (Codes); } // DiffCodes /// <summary> /// This is the algorithm to find the Shortest Middle Snake (SMS). /// </summary> /// <param name="DataA">sequence A</param> /// <param name="LowerA">lower bound of the actual range in DataA</param> /// <param name="UpperA">upper bound of the actual range in DataA (exclusive)</param> /// <param name="DataB">sequence B</param> /// <param name="LowerB">lower bound of the actual range in DataB</param> /// <param name="UpperB">upper bound of the actual range in DataB (exclusive)</param> /// <param name="DownVector">a vector for the (0,0) to (x,y) search. Passed as a parameter for speed reasons.</param> /// <param name="UpVector">a vector for the (u,v) to (N,M) search. Passed as a parameter for speed reasons.</param> /// <returns>a MiddleSnakeData record containing x,y and u,v</returns> private static SMSRD SMS(DiffData DataA, int LowerA, int UpperA, DiffData DataB, int LowerB, int UpperB, int[] DownVector, int[] UpVector) { SMSRD ret; int MAX = DataA.Length + DataB.Length + 1; int DownK = LowerA - LowerB; // the k-line to start the forward search int UpK = UpperA - UpperB; // the k-line to start the reverse search int Delta = (UpperA - LowerA) - (UpperB - LowerB); bool oddDelta = (Delta & 1) != 0; // The vectors in the publication accepts negative indexes. the vectors implemented here are 0-based // and are access using a specific offset: UpOffset UpVector and DownOffset for DownVektor int DownOffset = MAX - DownK; int UpOffset = MAX - UpK; int MaxD = ((UpperA - LowerA + UpperB - LowerB) / 2) + 1; // Debug.Write(2, "SMS", String.Format("Search the box: A[{0}-{1}] to B[{2}-{3}]", LowerA, UpperA, LowerB, UpperB)); // init vectors DownVector[DownOffset + DownK + 1] = LowerA; UpVector[UpOffset + UpK - 1] = UpperA; for (int D = 0; D <= MaxD; D++) { // Extend the forward path. for (int k = DownK - D; k <= DownK + D; k += 2) { // Debug.Write(0, "SMS", "extend forward path " + k.ToString()); // find the only or better starting point int x, y; if (k == DownK - D) { x = DownVector[DownOffset + k + 1]; // down } else { x = DownVector[DownOffset + k - 1] + 1; // a step to the right if ((k < DownK + D) && (DownVector[DownOffset + k + 1] >= x)) x = DownVector[DownOffset + k + 1]; // down } y = x - k; // find the end of the furthest reaching forward D-path in diagonal k. while ((x < UpperA) && (y < UpperB) && (DataA.data[x] == DataB.data[y])) { x++; y++; } DownVector[DownOffset + k] = x; // overlap ? if (oddDelta && (UpK - D < k) && (k < UpK + D)) { if (UpVector[UpOffset + k] <= DownVector[DownOffset + k]) { ret.x = DownVector[DownOffset + k]; ret.y = DownVector[DownOffset + k] - k; // ret.u = UpVector[UpOffset + k]; // 2002.09.20: no need for 2 points // ret.v = UpVector[UpOffset + k] - k; return (ret); } // if } // if } // for k // Extend the reverse path. for (int k = UpK - D; k <= UpK + D; k += 2) { // Debug.Write(0, "SMS", "extend reverse path " + k.ToString()); // find the only or better starting point int x, y; if (k == UpK + D) { x = UpVector[UpOffset + k - 1]; // up } else { x = UpVector[UpOffset + k + 1] - 1; // left if ((k > UpK - D) && (UpVector[UpOffset + k - 1] < x)) x = UpVector[UpOffset + k - 1]; // up } // if y = x - k; while ((x > LowerA) && (y > LowerB) && (DataA.data[x - 1] == DataB.data[y - 1])) { x--; y--; // diagonal } UpVector[UpOffset + k] = x; // overlap ? if (!oddDelta && (DownK - D <= k) && (k <= DownK + D)) { if (UpVector[UpOffset + k] <= DownVector[DownOffset + k]) { ret.x = DownVector[DownOffset + k]; ret.y = DownVector[DownOffset + k] - k; // ret.u = UpVector[UpOffset + k]; // 2002.09.20: no need for 2 points // ret.v = UpVector[UpOffset + k] - k; return (ret); } // if } // if } // for k } // for D throw new ApplicationException("the algorithm should never come here."); } // SMS /// <summary> /// This is the divide-and-conquer implementation of the longes common-subsequence (LCS) /// algorithm. /// The published algorithm passes recursively parts of the A and B sequences. /// To avoid copying these arrays the lower and upper bounds are passed while the sequences stay constant. /// </summary> /// <param name="DataA">sequence A</param> /// <param name="LowerA">lower bound of the actual range in DataA</param> /// <param name="UpperA">upper bound of the actual range in DataA (exclusive)</param> /// <param name="DataB">sequence B</param> /// <param name="LowerB">lower bound of the actual range in DataB</param> /// <param name="UpperB">upper bound of the actual range in DataB (exclusive)</param> /// <param name="DownVector">a vector for the (0,0) to (x,y) search. Passed as a parameter for speed reasons.</param> /// <param name="UpVector">a vector for the (u,v) to (N,M) search. Passed as a parameter for speed reasons.</param> private static void LCS(DiffData DataA, int LowerA, int UpperA, DiffData DataB, int LowerB, int UpperB, int[] DownVector, int[] UpVector) { // Debug.Write(2, "LCS", String.Format("Analyse the box: A[{0}-{1}] to B[{2}-{3}]", LowerA, UpperA, LowerB, UpperB)); // Fast walkthrough equal lines at the start while (LowerA < UpperA && LowerB < UpperB && DataA.data[LowerA] == DataB.data[LowerB]) { LowerA++; LowerB++; } // Fast walkthrough equal lines at the end while (LowerA < UpperA && LowerB < UpperB && DataA.data[UpperA - 1] == DataB.data[UpperB - 1]) { --UpperA; --UpperB; } if (LowerA == UpperA) { // mark as inserted lines. while (LowerB < UpperB) DataB.modified[LowerB++] = true; } else if (LowerB == UpperB) { // mark as deleted lines. while (LowerA < UpperA) DataA.modified[LowerA++] = true; } else { // Find the middle snakea and length of an optimal path for A and B SMSRD smsrd = SMS(DataA, LowerA, UpperA, DataB, LowerB, UpperB, DownVector, UpVector); // Debug.Write(2, "MiddleSnakeData", String.Format("{0},{1}", smsrd.x, smsrd.y)); // The path is from LowerX to (x,y) and (x,y) to UpperX LCS(DataA, LowerA, smsrd.x, DataB, LowerB, smsrd.y, DownVector, UpVector); LCS(DataA, smsrd.x, UpperA, DataB, smsrd.y, UpperB, DownVector, UpVector); // 2002.09.20: no need for 2 points } } // LCS() /// <summary>Scan the tables of which lines are inserted and deleted, /// producing an edit script in forward order. /// </summary> /// dynamic array private static Item[] CreateDiffs(DiffData DataA, DiffData DataB) { ArrayList a = new ArrayList(); Item aItem; Item[] result; int StartA, StartB; int LineA, LineB; LineA = 0; LineB = 0; while (LineA < DataA.Length || LineB < DataB.Length) { if ((LineA < DataA.Length) && (!DataA.modified[LineA]) && (LineB < DataB.Length) && (!DataB.modified[LineB])) { // equal lines LineA++; LineB++; } else { // maybe deleted and/or inserted lines StartA = LineA; StartB = LineB; while (LineA < DataA.Length && (LineB >= DataB.Length || DataA.modified[LineA])) // while (LineA < DataA.Length && DataA.modified[LineA]) LineA++; while (LineB < DataB.Length && (LineA >= DataA.Length || DataB.modified[LineB])) // while (LineB < DataB.Length && DataB.modified[LineB]) LineB++; if ((StartA < LineA) || (StartB < LineB)) { // store a new difference-item aItem = new Item(); aItem.StartA = StartA; aItem.StartB = StartB; aItem.deletedA = LineA - StartA; aItem.insertedB = LineB - StartB; a.Add(aItem); } // if } // if } // while result = new Item[a.Count]; a.CopyTo(result); return (result); } } // class Diff /// <summary>Data on one input file being compared. /// </summary> public class DiffData { /// <summary>Number of elements (lines).</summary> public int Length { get; internal set; } /// <summary>Buffer of numbers that will be compared.</summary> internal int[] data; /// <summary> /// Array of booleans that flag for modified data. /// This is the result of the diff. /// This means deletedA in the first Data or inserted in the second Data. /// </summary> internal bool[] modified; /// <summary> /// Initialize the Diff-Data buffer. /// </summary> /// <param name="data">reference to the buffer</param> internal DiffData(int[] initData) { data = initData; Length = initData.Length; modified = new bool[Length + 2]; } // DiffData } // class DiffData } // namespace
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="AdGroupCriterionServiceClient"/> instances.</summary> public sealed partial class AdGroupCriterionServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupCriterionServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupCriterionServiceSettings"/>.</returns> public static AdGroupCriterionServiceSettings GetDefault() => new AdGroupCriterionServiceSettings(); /// <summary> /// Constructs a new <see cref="AdGroupCriterionServiceSettings"/> object with default settings. /// </summary> public AdGroupCriterionServiceSettings() { } private AdGroupCriterionServiceSettings(AdGroupCriterionServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetAdGroupCriterionSettings = existing.GetAdGroupCriterionSettings; MutateAdGroupCriteriaSettings = existing.MutateAdGroupCriteriaSettings; OnCopy(existing); } partial void OnCopy(AdGroupCriterionServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupCriterionServiceClient.GetAdGroupCriterion</c> and /// <c>AdGroupCriterionServiceClient.GetAdGroupCriterionAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetAdGroupCriterionSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupCriterionServiceClient.MutateAdGroupCriteria</c> and /// <c>AdGroupCriterionServiceClient.MutateAdGroupCriteriaAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateAdGroupCriteriaSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AdGroupCriterionServiceSettings"/> object.</returns> public AdGroupCriterionServiceSettings Clone() => new AdGroupCriterionServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupCriterionServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AdGroupCriterionServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupCriterionServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupCriterionServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupCriterionServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupCriterionServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupCriterionServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupCriterionServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupCriterionServiceClient Build() { AdGroupCriterionServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupCriterionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupCriterionServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupCriterionServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupCriterionServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupCriterionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupCriterionServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupCriterionServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupCriterionServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupCriterionServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AdGroupCriterionService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ad group criteria. /// </remarks> public abstract partial class AdGroupCriterionServiceClient { /// <summary> /// The default endpoint for the AdGroupCriterionService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AdGroupCriterionService scopes.</summary> /// <remarks> /// The default AdGroupCriterionService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AdGroupCriterionServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupCriterionServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupCriterionServiceClient"/>.</returns> public static stt::Task<AdGroupCriterionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupCriterionServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupCriterionServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupCriterionServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupCriterionServiceClient"/>.</returns> public static AdGroupCriterionServiceClient Create() => new AdGroupCriterionServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupCriterionServiceClient"/> 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="AdGroupCriterionServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupCriterionServiceClient"/>.</returns> internal static AdGroupCriterionServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupCriterionServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupCriterionService.AdGroupCriterionServiceClient grpcClient = new AdGroupCriterionService.AdGroupCriterionServiceClient(callInvoker); return new AdGroupCriterionServiceClientImpl(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 AdGroupCriterionService client</summary> public virtual AdGroupCriterionService.AdGroupCriterionServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupCriterion GetAdGroupCriterion(GetAdGroupCriterionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(GetAdGroupCriterionRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(GetAdGroupCriterionRequest request, st::CancellationToken cancellationToken) => GetAdGroupCriterionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupCriterion GetAdGroupCriterion(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupCriterion(new GetAdGroupCriterionRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupCriterionAsync(new GetAdGroupCriterionRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(string resourceName, st::CancellationToken cancellationToken) => GetAdGroupCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupCriterion GetAdGroupCriterion(gagvr::AdGroupCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupCriterion(new GetAdGroupCriterionRequest { ResourceNameAsAdGroupCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(gagvr::AdGroupCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupCriterionAsync(new GetAdGroupCriterionRequest { ResourceNameAsAdGroupCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the criterion to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(gagvr::AdGroupCriterionName resourceName, st::CancellationToken cancellationToken) => GetAdGroupCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupCriterionError]() /// [AdxError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [BiddingError]() /// [BiddingStrategyError]() /// [CollectionSizeError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MultiplierError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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 MutateAdGroupCriteriaResponse MutateAdGroupCriteria(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupCriterionError]() /// [AdxError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [BiddingError]() /// [BiddingStrategyError]() /// [CollectionSizeError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MultiplierError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupCriterionError]() /// [AdxError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [BiddingError]() /// [BiddingStrategyError]() /// [CollectionSizeError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MultiplierError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(MutateAdGroupCriteriaRequest request, st::CancellationToken cancellationToken) => MutateAdGroupCriteriaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupCriterionError]() /// [AdxError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [BiddingError]() /// [BiddingStrategyError]() /// [CollectionSizeError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MultiplierError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose criteria are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual criteria. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupCriteriaResponse MutateAdGroupCriteria(string customerId, scg::IEnumerable<AdGroupCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupCriteria(new MutateAdGroupCriteriaRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupCriterionError]() /// [AdxError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [BiddingError]() /// [BiddingStrategyError]() /// [CollectionSizeError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MultiplierError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose criteria are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual criteria. /// </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<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(string customerId, scg::IEnumerable<AdGroupCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupCriteriaAsync(new MutateAdGroupCriteriaRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupCriterionError]() /// [AdxError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [BiddingError]() /// [BiddingStrategyError]() /// [CollectionSizeError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MultiplierError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose criteria are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual criteria. /// </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<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(string customerId, scg::IEnumerable<AdGroupCriterionOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupCriteriaAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupCriterionService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ad group criteria. /// </remarks> public sealed partial class AdGroupCriterionServiceClientImpl : AdGroupCriterionServiceClient { private readonly gaxgrpc::ApiCall<GetAdGroupCriterionRequest, gagvr::AdGroupCriterion> _callGetAdGroupCriterion; private readonly gaxgrpc::ApiCall<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> _callMutateAdGroupCriteria; /// <summary> /// Constructs a client wrapper for the AdGroupCriterionService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="AdGroupCriterionServiceSettings"/> used within this client. /// </param> public AdGroupCriterionServiceClientImpl(AdGroupCriterionService.AdGroupCriterionServiceClient grpcClient, AdGroupCriterionServiceSettings settings) { GrpcClient = grpcClient; AdGroupCriterionServiceSettings effectiveSettings = settings ?? AdGroupCriterionServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetAdGroupCriterion = clientHelper.BuildApiCall<GetAdGroupCriterionRequest, gagvr::AdGroupCriterion>(grpcClient.GetAdGroupCriterionAsync, grpcClient.GetAdGroupCriterion, effectiveSettings.GetAdGroupCriterionSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetAdGroupCriterion); Modify_GetAdGroupCriterionApiCall(ref _callGetAdGroupCriterion); _callMutateAdGroupCriteria = clientHelper.BuildApiCall<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse>(grpcClient.MutateAdGroupCriteriaAsync, grpcClient.MutateAdGroupCriteria, effectiveSettings.MutateAdGroupCriteriaSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupCriteria); Modify_MutateAdGroupCriteriaApiCall(ref _callMutateAdGroupCriteria); 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_GetAdGroupCriterionApiCall(ref gaxgrpc::ApiCall<GetAdGroupCriterionRequest, gagvr::AdGroupCriterion> call); partial void Modify_MutateAdGroupCriteriaApiCall(ref gaxgrpc::ApiCall<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> call); partial void OnConstruction(AdGroupCriterionService.AdGroupCriterionServiceClient grpcClient, AdGroupCriterionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupCriterionService client</summary> public override AdGroupCriterionService.AdGroupCriterionServiceClient GrpcClient { get; } partial void Modify_GetAdGroupCriterionRequest(ref GetAdGroupCriterionRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateAdGroupCriteriaRequest(ref MutateAdGroupCriteriaRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::AdGroupCriterion GetAdGroupCriterion(GetAdGroupCriterionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupCriterionRequest(ref request, ref callSettings); return _callGetAdGroupCriterion.Sync(request, callSettings); } /// <summary> /// Returns the requested criterion in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::AdGroupCriterion> GetAdGroupCriterionAsync(GetAdGroupCriterionRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupCriterionRequest(ref request, ref callSettings); return _callGetAdGroupCriterion.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupCriterionError]() /// [AdxError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [BiddingError]() /// [BiddingStrategyError]() /// [CollectionSizeError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MultiplierError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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 MutateAdGroupCriteriaResponse MutateAdGroupCriteria(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupCriteriaRequest(ref request, ref callSettings); return _callMutateAdGroupCriteria.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes criteria. Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupCriterionError]() /// [AdxError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [BiddingError]() /// [BiddingStrategyError]() /// [CollectionSizeError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MultiplierError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [PolicyViolationError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupCriteriaRequest(ref request, ref callSettings); return _callMutateAdGroupCriteria.Async(request, callSettings); } } }
using System; namespace Eto.Drawing { /// <summary> /// Color representation in the HSL color model /// </summary> /// <remarks> /// This allows you to manage a color in the HSL cylindrical model. /// /// This is a helper class to handle HSL colors. Whenever a color is used it must be /// converted to a <see cref="Color"/> struct first, either by using <see cref="ColorHSL.ToColor"/> /// or the implicit conversion. /// </remarks> /// <copyright>(c) 2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public struct ColorHSL : IEquatable<ColorHSL> { /// <summary> /// Gets or sets the alpha (0-1) /// </summary> public float A { get; set; } /// <summary> /// Gets or sets the hue (0-360) /// </summary> public float H { get; set; } /// <summary> /// Gets or sets the saturation (0-1) /// </summary> public float S { get; set; } /// <summary> /// Gets or sets the luminance (0-1) /// </summary> public float L { get; set; } /// <summary> /// Calculates the 'distance' of two HSL colors /// </summary> /// <remarks> /// This is useful for comparing two different color values to determine if they are similar. /// /// The HSL comparison algorithm, while not essentially accurate, gives a good representation of like-colours /// to the human eye. This method of calculating distance is preferred over the other methods (RGB, CMYK, HSB) /// </remarks> /// <param name="value1">First color to compare</param> /// <param name="value2">Second color to compare</param> /// <returns>The overall distance/difference between the two colours. A lower value indicates a closer match</returns> public static float Distance (ColorHSL value1, ColorHSL value2) { return (float)Math.Sqrt (Math.Pow ((value1.H - value2.H) / 360f, 2) + Math.Pow (value1.S - value2.S, 2) + Math.Pow (value1.L - value2.L, 2)); } /// <summary> /// Initializes a new instance of the ColorHSL class /// </summary> /// <param name="hue">Hue component (0-360)</param> /// <param name="saturation">Saturation component (0-1)</param> /// <param name="luminance">Luminace component (0-1)</param> /// <param name="alpha">Alpha component (0-1)</param> public ColorHSL (float hue, float saturation, float luminance, float alpha = 1f) : this() { H = hue; S = saturation; L = luminance; A = alpha; } /// <summary> /// Initializes a new instance of the ColorHSL class with converted HSL values from a <see cref="Color"/> /// </summary> /// <param name="color">RGB color to convert to HSL</param> public ColorHSL (Color color) : this() { float h = 0; float s = 0; float l; // normalize red, green, blue values float r = color.R; float g = color.G; float b = color.B; float max = Math.Max (r, Math.Max (g, b)); float min = Math.Min (r, Math.Min (g, b)); // hue if (max == min) { h = 0; // undefined } else if (max == r && g >= b) { h = 60f * (g - b) / (max - min); } else if (max == r && g < b) { h = 60f * (g - b) / (max - min) + 360f; } else if (max == g) { h = 60f * (b - r) / (max - min) + 120f; } else if (max == b) { h = 60f * (r - g) / (max - min) + 240f; } // luminance l = (max + min) / 2f; // saturation if (l == 0 || max == min) { s = 0; } else if (0 < l && l <= 0.5) { s = (max - min) / (max + min); } else if (l > 0.5) { s = (max - min) / (2 - (max + min)); //(max-min > 0)? } H = h; S = s; L = l; A = color.A; } /// <summary> /// Converts this HSL color to a RGB <see cref="Color"/> value /// </summary> /// <returns>A new instance of an RGB <see cref="Color"/> converted from HSL</returns> public Color ToColor () { if (S == 0) { // achromatic color (gray scale) return new Color(L, L, L, A); } else { float q = (L < 0.5f) ? (L * (1f + S)) : (L + S - (L * S)); float p = (2f * L) - q; float Hk = H / 360f; var T = new float[3]; T[0] = Hk + (1f / 3f); // Tr T[1] = Hk; // Tb T[2] = Hk - (1f / 3f); // Tg for (int i = 0; i < 3; i++) { if (T[i] < 0) T[i] += 1f; if (T[i] > 1) T[i] -= 1f; if ((T[i] * 6f) < 1) { T[i] = p + ((q - p) * 6f * T[i]); } else if ((T[i] * 2f) < 1) { //(1.0/6.0)<=T[i] && T[i]<0.5 T[i] = q; } else if ((T[i] * 3f) < 2) { // 0.5<=T[i] && T[i]<(2.0/3.0) T[i] = p + (q - p) * ((2f / 3f) - T[i]) * 6f; } else T[i] = p; } return new Color (T[0], T[1], T[2], A); } } /// <summary> /// Compares two <see cref="ColorHSL"/> objects for equality /// </summary> /// <param name="color1">First color to compare</param> /// <param name="color2">Second color to compare</param> /// <returns>True if the objects are equal, false otherwise</returns> public static bool operator == (ColorHSL color1, ColorHSL color2) { return color1.H == color2.H && color1.S == color2.S && color1.L == color2.L && color1.A == color2.A; } /// <summary> /// Compares two <see cref="ColorHSL"/> objects for equality /// </summary> /// <param name="color1">First color to compare</param> /// <param name="color2">Second color to compare</param> /// <returns>True if the objects are equal, false otherwise</returns> public static bool operator != (ColorHSL color1, ColorHSL color2) { return !(color1 == color2); } /// <summary> /// Implicitly converts a <see cref="ColorHSL"/> to an RGB <see cref="Color"/> /// </summary> /// <param name="hsl">HSL Color to convert</param> /// <returns>An RGB color converted from the specified <paramref name="hsl"/> color</returns> public static implicit operator Color (ColorHSL hsl) { return hsl.ToColor (); } /// <summary> /// Implicitly converts from a <see cref="Color"/> to a ColorHSL /// </summary> /// <param name="color">RGB color value to convert</param> /// <returns>A new instance of a ColorHSL that represents the RGB <paramref name="color"/> value</returns> public static implicit operator ColorHSL (Color color) { return new ColorHSL (color); } /// <summary> /// Compares the given object for equality with this object /// </summary> /// <param name="obj">Object to compare with</param> /// <returns>True if the object is equal to this instance, false otherwise</returns> public override bool Equals (object obj) { return obj is ColorHSL && this == (ColorHSL)obj; } /// <summary> /// Gets the hash code for this object /// </summary> /// <returns>Hash code for this object</returns> public override int GetHashCode () { return H.GetHashCode () ^ S.GetHashCode () ^ L.GetHashCode () ^ A.GetHashCode (); } /// <summary> /// Compares the given object for equality with this object /// </summary> /// <param name="other">Object to compare with</param> /// <returns>True if the object is equal to this instance, false otherwise</returns> public bool Equals (ColorHSL other) { return other == this; } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Collections.ObjectModel; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { [TestFixture] public class ChildrenFindingTest : DriverTestFixture { [Test] public void FindElementByXPath() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("form2")); IWebElement child = element.FindElement(By.XPath("select")); Assert.AreEqual(child.GetAttribute("id"), "2"); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void FindElementByXPathWhenNoMatch() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("form2")); element.FindElement(By.XPath("select/x")); } [Test] public void FindElementsByXPath() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("form2")); ReadOnlyCollection<IWebElement> children = element.FindElements(By.XPath("select/option")); Assert.AreEqual(children.Count, 8); Assert.AreEqual(children[0].Text, "One"); Assert.AreEqual(children[1].Text, "Two"); } [Test] public void FindElementsByXPathWhenNoMatch() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("form2")); ReadOnlyCollection<IWebElement> children = element.FindElements(By.XPath("select/x")); Assert.AreEqual(0, children.Count); } [Test] [IgnoreBrowser(Browser.IE, "Multiple items of ID 1 exist in the page, returns subelements of *all* of them, not the one we selected. See issue 278.")] [IgnoreBrowser(Browser.HtmlUnit, "Multiple items of ID 1 exist in the page, returns subelements of *all* of them, not the one we selected. See issue 278.")] public void FindElementsByXPathWithMultipleParentElementsOfSameId() { driver.Url = nestedPage; IWebElement select = driver.FindElement(By.Id("1")); ReadOnlyCollection<IWebElement> elements = select.FindElements(By.XPath("//option")); Assert.AreEqual(4, elements.Count); } [Test] [IgnoreBrowser(Browser.IE, "Issue 278.")] [IgnoreBrowser(Browser.HtmlUnit, "Issue 278.")] public void FindsSubElementNotTopLevelElementWhenLookingUpSubElementByXPath() { driver.Url = simpleTestPage; IWebElement parent = driver.FindElement(By.Id("containsSomeDiv")); IWebElement child = parent.FindElement(By.XPath("//div[@name='someDiv']")); Assert.IsFalse(child.Text.Contains("Top level"), "Child should not contain text Top level"); Assert.IsTrue(child.Text.Contains("Nested"), "Child should contain text Nested"); } [Test] public void FindElementByName() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("form2")); IWebElement child = element.FindElement(By.Name("selectomatic")); Assert.AreEqual(child.GetAttribute("id"), "2"); } [Test] public void FindElementsByName() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("form2")); ReadOnlyCollection<IWebElement> children = element.FindElements(By.Name("selectomatic")); Assert.AreEqual(children.Count, 2); } [Test] public void FindElementById() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("form2")); IWebElement child = element.FindElement(By.Id("2")); Assert.AreEqual(child.GetAttribute("name"), "selectomatic"); } [Test] public void FindElementByIdWhenMultipleMatchesExist() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Id("test_id_div")); IWebElement child = element.FindElement(By.Id("test_id")); Assert.AreEqual(child.Text, "inside"); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void FindElementByIdWhenNoMatchInContext() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Id("test_id_div")); element.FindElement(By.Id("test_id_out")); } [Test] public void FindElementsById() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("form2")); ReadOnlyCollection<IWebElement> children = element.FindElements(By.Id("2")); Assert.AreEqual(children.Count, 2); } [Test] public void FindElementByLinkText() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("div1")); IWebElement child = element.FindElement(By.LinkText("hello world")); Assert.AreEqual(child.GetAttribute("name"), "link1"); } [Test] public void FindElementsByLinkTest() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("div1")); ReadOnlyCollection<IWebElement> elements = element.FindElements(By.LinkText("hello world")); Assert.AreEqual(2, elements.Count); Assert.AreEqual(elements[0].GetAttribute("name"), "link1"); Assert.AreEqual(elements[1].GetAttribute("name"), "link2"); } [Test] public void FindElementsByLinkText() { driver.Url = nestedPage; IWebElement element = driver.FindElement(By.Name("div1")); ReadOnlyCollection<IWebElement> children = element.FindElements(By.LinkText("hello world")); Assert.AreEqual(children.Count, 2); } [Test] public void ShouldFindChildElementsByClassName() { driver.Url = nestedPage; IWebElement parent = driver.FindElement(By.Name("classes")); IWebElement element = parent.FindElement(By.ClassName("one")); Assert.AreEqual("Find me", element.Text); } [Test] public void ShouldFindChildrenByClassName() { driver.Url = nestedPage; IWebElement parent = driver.FindElement(By.Name("classes")); ReadOnlyCollection<IWebElement> elements = parent.FindElements(By.ClassName("one")); Assert.AreEqual(2, elements.Count); } [Test] public void ShouldFindChildElementsByTagName() { driver.Url = nestedPage; IWebElement parent = driver.FindElement(By.Name("div1")); IWebElement element = parent.FindElement(By.TagName("a")); Assert.AreEqual("link1", element.GetAttribute("name")); } [Test] public void ShouldFindChildrenByTagName() { driver.Url = nestedPage; IWebElement parent = driver.FindElement(By.Name("div1")); ReadOnlyCollection<IWebElement> elements = parent.FindElements(By.TagName("a")); Assert.AreEqual(2, elements.Count); } [Test] [Category("Javascript")] public void ShouldBeAbleToFindAnElementByCssSelector() { driver.Url = nestedPage; if (!SupportsSelectorApi()) { Assert.Ignore("Skipping test: selector API not supported"); } IWebElement parent = driver.FindElement(By.Name("form2")); IWebElement element = parent.FindElement(By.CssSelector("*[name=\"selectomatic\"]")); Assert.AreEqual("2", element.GetAttribute("id")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Chrome, "Chrome doesn't handle the many-pages situation well")] public void ShouldBeAbleToFindAnElementsByCssSelector() { driver.Url = nestedPage; if (!SupportsSelectorApi()) { Assert.Ignore("Skipping test: selector API not supported"); } IWebElement parent = driver.FindElement(By.Name("form2")); ReadOnlyCollection<IWebElement> elements = parent.FindElements(By.CssSelector("*[name=\"selectomatic\"]")); Assert.AreEqual(2, elements.Count); } private bool SupportsSelectorApi() { IJavaScriptExecutor javascriptDriver = driver as IJavaScriptExecutor; IFindsByCssSelector cssSelectorDriver = driver as IFindsByCssSelector; return (cssSelectorDriver != null) && (javascriptDriver != null) && ((bool)javascriptDriver.ExecuteScript("return document['querySelector'] !== undefined;")); } } }
// <copyright file="Environment.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using GlobalSystem = System; namespace IX.System; /// <summary> /// Concrete implementation of the abstraction over the <see cref="GlobalSystem.Environment" /> class. This class /// cannot be inherited. /// </summary> /// <seealso cref="IX.System.IEnvironment" /> [PublicAPI] public sealed class Environment : IEnvironment { /// <summary> /// Gets the processor count. /// </summary> /// <value> /// The processor count. /// </value> public int ProcessorCount => GlobalSystem.Environment.ProcessorCount; /// <summary> /// Gets a value indicating whether the current machine has only a single processor. /// </summary> public bool IsSingleProcessor => GlobalSystem.Environment.ProcessorCount == 1; #if NET50_OR_GREATER /// <summary> /// Gets the unique identifier for the current process. /// </summary> /// <value> /// The process identifier. /// </value> public int ProcessId => GlobalSystem.Environment.ProcessId; #endif /// <summary> /// Gets a value indicating whether or not the current process is a 64-bit process. /// </summary> /// <value> /// <c>true</c> if the current process is 64-bit; otherwise, <c>false</c>. /// </value> public bool Is64BitProcess => GlobalSystem.Environment.Is64BitProcess; /// <summary> /// Gets a value indicating whether the operating system the current process is running on is 64-bit. /// </summary> /// <value> /// <c>true</c> if the OS is 64-bit; otherwise, <c>false</c>. /// </value> public bool Is64BitOperatingSystem => GlobalSystem.Environment.Is64BitOperatingSystem; /// <summary> /// Gets the special character(s) that represent a new line in the current environment. /// </summary> /// <value> /// The new line character(s) for the current environment. /// </value> public string NewLine => GlobalSystem.Environment.NewLine; /// <summary> /// Gets the current operating system version. /// </summary> /// <value> /// The current operating system version. /// </value> [SuppressMessage( "Usage", "DE0009:API is deprecated", Justification = "We have no other choice, if we are to emulate the API correctly.")] public GlobalSystem.OperatingSystem OperatingSystemVersion => GlobalSystem.Environment.OSVersion; /// <summary> /// Gets the executing assembly version. /// </summary> /// <value> /// The executing assembly version. /// </value> public GlobalSystem.Version Version => GlobalSystem.Environment.Version; /// <summary> /// Gets the current managed thread identifier. /// </summary> /// <value> /// The current managed thread identifier. /// </value> public int CurrentManagedThreadId => GlobalSystem.Environment.CurrentManagedThreadId; /// <summary> /// Gets a value indicating whether shutdown has started. /// </summary> /// <value> /// <c>true</c> if shutdown has started; otherwise, <c>false</c>. /// </value> /// <remarks> /// <para>On .NET Core, unconditionally returns false since .NET Core does not support object finalization during shutdown.</para> /// </remarks> public bool HasShutdownStarted => GlobalSystem.Environment.HasShutdownStarted; /// <summary> /// Gets the name of the user the current process is executing under. /// </summary> /// <value> /// The name of the user. /// </value> public string UserName => GlobalSystem.Environment.UserName; /// <summary> /// Gets the name of the user domain the current process is executing under. /// </summary> /// <value> /// The name of the user domain. /// </value> public string UserDomainName => GlobalSystem.Environment.UserDomainName; /// <summary> /// Gets the command line of the current process. /// </summary> /// <value> /// The command line. /// </value> public string CommandLine => GlobalSystem.Environment.CommandLine; /// <summary> /// Gets the current directory. /// </summary> /// <value> /// The current directory. /// </value> public string CurrentDirectory => GlobalSystem.Environment.CurrentDirectory; /// <summary> /// Gets the stack trace. /// </summary> /// <value> /// The stack trace. /// </value> public string StackTrace => GlobalSystem.Environment.StackTrace; /// <summary>Gets the number of milliseconds elapsed since the system started.</summary> /// <value> /// A 32-bit signed integer containing the amount of time in milliseconds that has passed since the last time the /// computer was started. /// </value> public int TickCount => GlobalSystem.Environment.TickCount; #if NET50_OR_GREATER /// <summary>Gets the number of milliseconds elapsed since the system started.</summary> /// <value> /// A 64-bit signed integer containing the amount of time in milliseconds that has passed since the last time the /// computer was started. /// </value> public long TickCount64 => GlobalSystem.Environment.TickCount64; #endif /// <summary> /// Gets or sets the exit code. /// </summary> /// <value> /// The exit code. /// </value> public int ExitCode { get => GlobalSystem.Environment.ExitCode; set => GlobalSystem.Environment.ExitCode = value; } /// <summary> /// Gets an environment variable. /// </summary> /// <param name="variableName">The variable name.</param> /// <returns>The value of the environment variable, or <c>null</c> (<c>Nothing</c> in Visual Basic) if one is not found.</returns> public string? GetEnvironmentVariable(string variableName) => GlobalSystem.Environment.GetEnvironmentVariable(variableName); /// <summary> /// Gets an environment variable. /// </summary> /// <param name="variableName">Name of the variable.</param> /// <param name="target">The target.</param> /// <returns>The value of the environment variable, or <c>null</c> (<c>Nothing</c> in Visual Basic) if one is not found.</returns> public string? GetEnvironmentVariable( string variableName, GlobalSystem.EnvironmentVariableTarget target) => GlobalSystem.Environment.GetEnvironmentVariable( variableName, target); /// <summary> /// Gets all available environment variables. /// </summary> /// <returns>A dictionary of available environment variables.</returns> [SuppressMessage( "Usage", "DE0006:API is deprecated", Justification = "We have no other choice, if we are to emulate the API correctly.")] public IDictionary<string, string> GetEnvironmentVariables() => GlobalSystem.Environment.GetEnvironmentVariables() .OfType<DictionaryEntry>() .ToDictionary( p => GlobalSystem.Convert.ToString(p.Key) ?? string.Empty, q => q.Value == null ? string.Empty : GlobalSystem.Convert.ToString(q.Value) ?? string.Empty); /// <summary> /// Gets all available environment variables. /// </summary> /// <param name="target">The target.</param> /// <returns>A dictionary of available environment variables.</returns> [SuppressMessage( "Usage", "DE0006:API is deprecated", Justification = "We have no other choice, if we are to emulate the API correctly.")] public IDictionary<string, string> GetEnvironmentVariables(GlobalSystem.EnvironmentVariableTarget target) => GlobalSystem.Environment.GetEnvironmentVariables(target) .OfType<DictionaryEntry>() .ToDictionary( p => GlobalSystem.Convert.ToString(p.Key) ?? string.Empty, q => q.Value == null ? string.Empty : GlobalSystem.Convert.ToString(q.Value) ?? string.Empty); /// <summary> /// Sets the value of an environment variable. /// </summary> /// <param name="variableName">Name of the variable.</param> /// <param name="value">The value.</param> public void SetEnvironmentVariable( string variableName, string? value) => GlobalSystem.Environment.SetEnvironmentVariable( variableName, value); /// <summary> /// Sets the value of an environment variable. /// </summary> /// <param name="variableName">Name of the variable.</param> /// <param name="value">The value.</param> /// <param name="target">The target.</param> public void SetEnvironmentVariable( string variableName, string? value, GlobalSystem.EnvironmentVariableTarget target) => GlobalSystem.Environment.SetEnvironmentVariable( variableName, value, target); /// <summary> /// Expands the environment variables. /// </summary> /// <param name="name">The name.</param> /// <returns>The expanded version of the environment variables.</returns> public string ExpandEnvironmentVariables(string name) => GlobalSystem.Environment.ExpandEnvironmentVariables(name); /// <summary> /// Gets a special folder path. /// </summary> /// <param name="folder">The folder.</param> /// <returns>The folder path.</returns> public string GetFolderPath(GlobalSystem.Environment.SpecialFolder folder) => GlobalSystem.Environment.GetFolderPath(folder); /// <summary> /// Gets a special folder path. /// </summary> /// <param name="folder">The folder.</param> /// <param name="option">The special folder option.</param> /// <returns>The folder path.</returns> public string GetFolderPath( GlobalSystem.Environment.SpecialFolder folder, GlobalSystem.Environment.SpecialFolderOption option) => GlobalSystem.Environment.GetFolderPath( folder, option); /// <summary> /// Exits using the specified exit code. /// </summary> /// <param name="exitCode">The exit code.</param> [DoesNotReturn] public void Exit(int exitCode) { GlobalSystem.Environment.Exit(exitCode); #if !FRAMEWORK_ADVANCED throw new global::System.InvalidOperationException(); #endif } /// <summary> /// Fails the current process fast. /// </summary> /// <param name="message">The message to fail with.</param> [DoesNotReturn] public void FailFast(string? message) { GlobalSystem.Environment.FailFast(message); #if !FRAMEWORK_ADVANCED throw new global::System.InvalidOperationException(); #endif } /// <summary> /// Fails the current process fast. /// </summary> /// <param name="message">The message to fail with.</param> /// <param name="exception">The exception to fail with.</param> [DoesNotReturn] public void FailFast( string? message, GlobalSystem.Exception? exception) { GlobalSystem.Environment.FailFast( message, exception); #if !FRAMEWORK_ADVANCED throw new global::System.InvalidOperationException(); #endif } /// <summary> /// Gets the command line arguments. /// </summary> /// <returns>The command line arguments.</returns> public string[] GetCommandLineArgs() => GlobalSystem.Environment.GetCommandLineArgs(); }
/* ==================================================================== 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 TestCases { using NPOI; using NPOI.OpenXmlFormats; using NPOI.Util; using NPOI.XSSF; using NPOI.XSSF.UserModel; using NPOI.XWPF.UserModel; using NUnit.Framework; using System; using TestCases.XWPF; /** * Test Setting extended and custom OOXML properties */ [TestFixture] public class TestPOIXMLProperties { private XWPFDocument sampleDoc; private XWPFDocument sampleNoThumb; private POIXMLProperties _props; private CoreProperties _coreProperties; [SetUp] public void SetUp() { sampleDoc = XWPFTestDataSamples.OpenSampleDocument("documentProperties.docx"); sampleNoThumb = XWPFTestDataSamples.OpenSampleDocument("SampleDoc.docx"); Assert.IsNotNull(sampleDoc); Assert.IsNotNull(sampleNoThumb); _props = sampleDoc.GetProperties(); _coreProperties = _props.CoreProperties; Assert.IsNotNull(_props); } [TearDown] public void closeResources() { sampleDoc.Close(); sampleNoThumb.Close(); } [Test] public void TestWorkbookExtendedProperties() { XSSFWorkbook workbook = new XSSFWorkbook(); POIXMLProperties props = workbook.GetProperties(); Assert.IsNotNull(props); ExtendedProperties properties = props.ExtendedProperties; CT_ExtendedProperties ctProps = properties.GetUnderlyingProperties(); String appVersion = "3.5 beta"; String application = "POI"; ctProps.Application = (application); ctProps.AppVersion = (appVersion); XSSFWorkbook newWorkbook = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook); workbook.Close(); Assert.IsTrue(workbook != newWorkbook); POIXMLProperties newProps = newWorkbook.GetProperties(); Assert.IsNotNull(newProps); ExtendedProperties newProperties = newProps.ExtendedProperties; Assert.AreEqual(application, newProperties.Application); Assert.AreEqual(appVersion, newProperties.AppVersion); CT_ExtendedProperties newCtProps = newProperties.GetUnderlyingProperties(); Assert.AreEqual(application, newCtProps.Application); Assert.AreEqual(appVersion, newCtProps.AppVersion); newWorkbook.Close(); } /** * Test usermodel API for Setting custom properties */ [Test] public void TestCustomProperties() { POIXMLDocument wb1 = new XSSFWorkbook(); CustomProperties customProps = wb1.GetProperties().CustomProperties; customProps.AddProperty("test-1", "string val"); customProps.AddProperty("test-2", 1974); customProps.AddProperty("test-3", 36.6); //Adding a duplicate try { customProps.AddProperty("test-3", 36.6); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.AreEqual("A property with this name already exists in the custom properties", e.Message); } customProps.AddProperty("test-4", true); POIXMLDocument wb2 = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack((XSSFWorkbook)wb1); wb1.Close(); CT_CustomProperties ctProps = wb2.GetProperties().CustomProperties.GetUnderlyingProperties(); Assert.AreEqual(6, ctProps.sizeOfPropertyArray()); CT_Property p; p = ctProps.GetPropertyArray(0); Assert.AreEqual("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.fmtid); Assert.AreEqual("test-1", p.name); Assert.AreEqual("string val", p.Item.ToString()); Assert.AreEqual(2, p.pid); p = ctProps.GetPropertyArray(1); Assert.AreEqual("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.fmtid); Assert.AreEqual("test-2", p.name); Assert.AreEqual(1974, p.Item); Assert.AreEqual(3, p.pid); p = ctProps.GetPropertyArray(2); Assert.AreEqual("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.fmtid); Assert.AreEqual("test-3", p.name); Assert.AreEqual(36.6, p.Item); Assert.AreEqual(4, p.pid); p = ctProps.GetPropertyArray(3); Assert.AreEqual("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.fmtid); Assert.AreEqual("test-4", p.name); Assert.AreEqual(true, p.Item); Assert.AreEqual(5, p.pid); p = ctProps.GetPropertyArray(4); Assert.AreEqual("Generator", p.name); Assert.AreEqual("NPOI", p.Item); Assert.AreEqual(6, p.pid); //p = ctProps.GetPropertyArray(5); //Assert.AreEqual("Generator Version", p.name); //Assert.AreEqual("2.0.9", p.Item); //Assert.AreEqual(7, p.pid); wb2.Close(); } [Ignore("test")] public void TestDocumentProperties() { String category = _coreProperties.Category; Assert.AreEqual("test", category); String contentStatus = "Draft"; _coreProperties.ContentStatus = contentStatus; Assert.AreEqual("Draft", contentStatus); DateTime? Created = _coreProperties.Created; // the original file Contains a following value: 2009-07-20T13:12:00Z Assert.IsTrue(DateTimeEqualToUTCString(Created, "2009-07-20T13:12:00Z")); String creator = _coreProperties.Creator; Assert.AreEqual("Paolo Mottadelli", creator); String subject = _coreProperties.Subject; Assert.AreEqual("Greetings", subject); String title = _coreProperties.Title; Assert.AreEqual("Hello World", title); } public void TestTransitiveSetters() { XWPFDocument doc = new XWPFDocument(); CoreProperties cp = doc.GetProperties().CoreProperties; DateTime dateCreated = new DateTime(2010, 6, 15, 10, 0, 0); cp.Created = new DateTime(2010, 6, 15, 10, 0, 0); Assert.AreEqual(dateCreated.ToString(), cp.Created.ToString()); XWPFDocument doc2 = XWPFTestDataSamples.WriteOutAndReadBack(doc); doc.Close(); cp = doc2.GetProperties().CoreProperties; DateTime? dt3 = cp.Created; Assert.AreEqual(dateCreated.ToString(), dt3.ToString()); doc2.Close(); } [Test] public void TestGetSetRevision() { String revision = _coreProperties.Revision; Assert.IsTrue(Int32.Parse(revision) > 1, "Revision number is 1"); _coreProperties.Revision = "20"; Assert.AreEqual("20", _coreProperties.Revision); _coreProperties.Revision = "20xx"; Assert.AreEqual("20", _coreProperties.Revision); } [Test] public void TestLastModifiedByProperty() { String lastModifiedBy = _coreProperties.LastModifiedByUser; Assert.AreEqual("Paolo Mottadelli", lastModifiedBy); _coreProperties.LastModifiedByUser = "Test User"; Assert.AreEqual("Test User", _coreProperties.LastModifiedByUser); } public static bool DateTimeEqualToUTCString(DateTime? dateTime, String utcString) { DateTime utcDt = DateTime.SpecifyKind((DateTime)dateTime, DateTimeKind.Utc); string dateTimeUtcString = utcDt.ToString("yyyy-MM-ddThh:mm:ssZ"); return utcString.Equals(dateTimeUtcString); } [Test] public void TestThumbnails() { POIXMLProperties noThumbProps = sampleNoThumb.GetProperties(); Assert.IsNotNull(_props.ThumbnailPart); Assert.IsNull(noThumbProps.ThumbnailPart); Assert.IsNotNull(_props.ThumbnailFilename); Assert.IsNull(noThumbProps.ThumbnailFilename); Assert.IsNotNull(_props.ThumbnailImage); Assert.IsNull(noThumbProps.ThumbnailImage); Assert.AreEqual("thumbnail.jpeg", _props.ThumbnailFilename); // Adding / changing noThumbProps.SetThumbnail("Testing.png", new ByteArrayInputStream(new byte[1])); Assert.IsNotNull(noThumbProps.ThumbnailPart); Assert.AreEqual("Testing.png", noThumbProps.ThumbnailFilename); Assert.IsNotNull(noThumbProps.ThumbnailImage); //Assert.AreEqual(1, noThumbProps.ThumbnailImage.Available()); Assert.AreEqual(1, noThumbProps.ThumbnailImage.Length - noThumbProps.ThumbnailImage.Position); noThumbProps.SetThumbnail("Testing2.png", new ByteArrayInputStream(new byte[2])); Assert.IsNotNull(noThumbProps.ThumbnailPart); Assert.AreEqual("Testing.png", noThumbProps.ThumbnailFilename); Assert.IsNotNull(noThumbProps.ThumbnailImage); //Assert.AreEqual(2, noThumbProps.ThumbnailImage.Available()); Assert.AreEqual(2, noThumbProps.ThumbnailImage.Length - noThumbProps.ThumbnailImage.Position); } private static String ZeroPad(long i) { if (i >= 0 && i <= 9) { return "0" + i; } else { return i.ToString(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Net; using Microsoft.AspNetCore.Mvc; using Zyborg.Vault.Ext.SystemBackend; using Zyborg.Vault.Model; using Zyborg.Vault.MockServer.Auth; using Zyborg.Vault.MockServer.Policy; namespace Zyborg.Vault.MockServer.Controllers { [Route("v1/sys")] public class SysController : Controller { private MockServer _server; public SysController(MockServer server) { _server = server; } // TODO: just for debugging [HttpGet("settings")] public ServerSettings GetSettings() { _server.AssertAuthorized(this, isSudo: true); return _server.Settings; } /// <summary> /// The /sys/health endpoint is used to check the health status of Vault. /// </summary> /// <param name="standbyok">Specifies if being a standby should still return the /// active status code instead of the standby status code. This is useful when /// Vault is behind a non-configurable load balance that just wants a 200-level /// response.</param> /// <param name="activecode">Specifies the status code that should be returned for /// an active node.</param> /// <param name="standbycode"Specifies the status code that should be returned for /// a standby node.</param> /// <param name="sealedcode">Specifies the status code that should be returned for /// a sealed node.</param> /// <param name="uninitcode">Specifies the status code that should be returned for /// a uninitialized node.</param> /// <remarks> /// <para><b><i>This is an unauthenticated endpoint.</i></b></para> /// /// <para> /// This endpoint returns the health status of Vault. This matches the semantics of /// a Consul HTTP health check and provides a simple way to monitor the health of a /// Vault instance. /// </para><para> /// The default status codes are: /// <list> /// <item>200 if initialized, unsealed, and active</item> /// <item>429 if unsealed and standby</item> /// <item>501 if not initialized</item> /// <item>503 if sealed</item> /// </list> /// </para> /// </remarks> [HttpHead("health")] [HttpGet("health")] public IActionResult GetHealth( [FromQuery]bool standbyok = false, [FromQuery]int activecode = 200, [FromQuery]int standbycode = 429, [FromQuery]int sealedcode = 503, [FromQuery]int uninitcode = 501) { var http = HttpContext; var cc = base.ControllerContext; var uh = base.Url; var rd = base.RouteData; var status = new HealthStatus { Initialized = _server.Health.Initialized, Sealed = _server.Health.Sealed, Standby = _server.Health.Standby, ServerTimeUtc = _server.Health.ServerTimeUtc, Version = _server.Health.Version, ClusterId = _server.Health.ClusterId, ClusterName = _server.Health.ClusterName, }; var statusCode = activecode; if (!status.Initialized) statusCode = uninitcode; else if (status.Sealed) statusCode = sealedcode; else if (status.Standby && !standbyok) statusCode = standbycode; return base.StatusCode(statusCode, status); } /// <summary> /// This endpoint returns the initialization status of Vault. /// </summary> /// <remarks> /// <para><b><i>This is an unauthenticated endpoint.</i></b></para> /// </remarks> [HttpGet("init")] public InitializationStatus GetInitStatus() { return _server.GetInitializationStatus(); } /// <summary> /// This endpoint initializes a new Vault. The Vault must not have been /// previously initialized. The recovery options, as well as the stored /// shares option, are only available when using Vault HSM. /// </summary> /// <param name="requ"></param> /// <remarks> /// <para><b><i>This is an unauthenticated endpoint.</i></b></para> /// </remarks> [HttpPut("init")] public InitializationResponse StartInit([FromBody]InitializationRequest requ) { return _server.Initialize(requ.SecretShares, requ.SecretThreshold) ?? throw new VaultServerException( HttpStatusCode.BadRequest, "Vault is already initialized"); } /// <summary> /// Used to check the seal status of a Vault. /// </summary> /// <remarks> /// <para><b><i>This is an unauthenticated endpoint.</i></b></para> /// /// This endpoint returns the seal status of the Vault. This is an unauthenticated endpoint. /// </remarks> [HttpGet("seal-status")] public SealStatus GetSealStatus() { return _server.GetSealStatus() ?? throw new VaultServerException( HttpStatusCode.BadRequest, "server is not yet initialized"); } /// <summary> /// Used to query info about the current encryption key of Vault. /// </summary> /// <remarks> /// <para><b><i>This endpoint is authenticated, but SUDO is NOT required.</i></b></para> /// /// This endpoint returns information about the current encryption key used by Vault. /// </remarks> [HttpGet("key-status")] public KeyStatus GetKeyStatus() { _server.AssertAuthorized(this); return _server.GetKeyStatus() ?? throw new VaultServerException( HttpStatusCode.ServiceUnavailable, "Vault is sealed"); } /// <summary> /// Used to check the high availability status and current leader of Vault. /// </summary> /// <remarks> /// <para><b><i>This is an unauthenticated endpoint.</i></b></para> /// </remarks> [HttpGet("leader")] public LeaderStatus GetLeaderStatus() { return _server.GetLeaderStatus() ?? throw new VaultServerException( HttpStatusCode.ServiceUnavailable, "Vault is sealed"); } /// <summary> /// Used to unseal the Vault. /// </summary> /// <param name="requ"></param> /// <remarks> /// <para><b><i>This is an unauthenticated endpoint.</i></b></para> /// /// This endpoint is used to enter a single master key share to progress the unsealing /// of the Vault. If the threshold number of master key shares is reached, Vault will /// attempt to unseal the Vault. Otherwise, this API must be called multiple times /// until that threshold is met. /// <para> /// Either the key or reset parameter must be provided; if both are provided, /// reset takes precedence. /// </para> /// </remarks> [HttpPut("unseal")] public SealStatus DoUnseal([FromBody]UnsealRequest requ) { return _server.Unseal(requ.Key, requ.Reset.GetValueOrDefault()) // TODO: confirm this is the correct response for this state ?? throw new VaultServerException( HttpStatusCode.BadRequest, "server is not yet initialized"); } /// <summary> /// Lists all enabled auth backends. /// </summary> [HttpGet("auth")] public ReadResponse<Dictionary<string, MountInfo>> ListAuthMounts() { _server.AssertAuthorized(this, isSudo: true); var mountNames = _server.ListAuthMounts().OrderBy(x => x); var mounts = mountNames.ToDictionary( key => key.Trim('/') + "/", key => new MountInfo { Accessor = key, Type = _server.ResolveAuthMount(key).backend?.GetType().FullName ?? "(UNKNOWN)", Config = new MountConfig(), }); // To be fully compliant with the HCVault CLI, we // have to honor the "repeated" response structure return new ReadRepeatedResponse<Dictionary<string, MountInfo>> { Data = mounts }; } /// <summary> /// Lists all the mounted secret backends. /// </summary> [HttpGet("mounts")] public ReadResponse<Dictionary<string, MountInfo>> ListSecretMounts() { _server.AssertAuthorized(this, isSudo: true); var mountNames = _server.ListSecretMounts().OrderBy(x => x); var mounts = mountNames.ToDictionary( key => key.Trim('/') + "/", key => new MountInfo { Accessor = key, Type = _server.ResolveSecretMount(key).backend?.GetType().FullName ?? "(UNKNOWN)", Config = new MountConfig(), }); // To be fully compliant with the HCVault CLI, we // have to honor the "repeated" response structure return new ReadRepeatedResponse<Dictionary<string, MountInfo>> { Data = mounts }; } /// <summary> /// Lists all configured policies. /// </summary> [HttpGet("policy")] public ReadResponse<PolicyKeysData> ListPolicies() { _server.AssertAuthorized(this, isSudo: true); // To be fully compliant with the HCVault CLI, we // have to honor the "repeated" response structure return new ReadRepeatedResponse<PolicyKeysData> { Data = new PolicyKeysData { Keys = _server.ListPolicies().ToArray() } }; } /// <summary> /// Retrieve the rules for the named policy. /// </summary> /// <param name="name">Specifies the name of the policy to retrieve.</param> [HttpGet("policy/{name}")] public ReadResponse<PolicyRulesData> ReadPolicy( [Required, FromRoute]string name) { _server.AssertAuthorized(this, isSudo: true); var polDef = _server.ReadPolicy(name) ?? throw new VaultServerException(HttpStatusCode.NotFound); // To be fully compliant with the HCVault CLI, we // have to honor the "repeated" response structure return new ReadRepeatedResponse<PolicyRulesData> { Data = new PolicyRulesData { Name = polDef.Name, Rules = polDef.Definition, } }; } /// <summary> /// Aadds a new or updates an existing policy. Once a policy is updated, /// it takes effect immediately to all associated users. /// </summary> /// <param name="name">Specifies the name of the policy to create.</param> /// <param name="policyDefinition">Specifies the policy document.</param> [HttpPut("policy/{name}")] public void WritePolicy( [Required, FromRoute]string name, [Required, FromBody]PolicyRulesData policyDefinition) { _server.AssertAuthorized(this, isSudo: true); try { _server.WritePolicy(name, policyDefinition.Rules); } catch (Exception ex) { throw DecodeServerException(ex); } } /// <summary> /// Deletes the policy with the given name. This will immediately affect /// all users associated with this policy. /// </summary> /// <param name="name">Specifies the name of the policy to delete.</param> [HttpDelete("policy/{name}")] public void DeletePolicy( [Required, FromRoute]string name) { _server.AssertAuthorized(this, isSudo: true); try { _server.DeletePolicy(name); } catch (Exception ex) { throw DecodeServerException(ex); } } public static Exception DecodeServerException(Exception ex) { var msgs = new string[0]; if (!string.IsNullOrEmpty(ex.Message)) msgs = new[] { ex.Message }; switch (ex) { case NotSupportedException nse: return new VaultServerException(HttpStatusCode.NotFound, msgs); case ArgumentException ae: return new VaultServerException(HttpStatusCode.BadRequest, msgs); case System.Security.SecurityException ae: return new VaultServerException(HttpStatusCode.Forbidden, msgs); default: Console.Error.WriteLine("--- UNEXPECTED ERROR ---"); Console.Error.WriteLine(ex.ToString()); Console.Error.WriteLine("------------------------"); return new VaultServerException(HttpStatusCode.InternalServerError, msgs); } } } }
namespace Petstore { using Microsoft.Rest.Azure; using Models; /// <summary> /// StorageAccountsOperations operations. /// </summary> public partial interface IStorageAccountsOperations { /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters /// in length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CheckNameAvailabilityResultInner>> CheckNameAvailabilityWithHttpMessagesAsync(StorageAccountCheckNameAvailabilityParametersInner accountName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account /// is already created and subsequent PUT request is issued with /// exact same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters /// in length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<StorageAccountInner>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParametersInner parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account /// is already created and subsequent PUT request is issued with /// exact same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters /// in length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<StorageAccountInner>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParametersInner parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters /// in length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns the properties for the specified storage account including /// but not limited to name, account type, location, and account /// status. The ListKeys operation should be used to retrieve storage /// keys. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters /// in length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<StorageAccountInner>> GetPropertiesWithHttpMessagesAsync(string resourceGroupName, string accountName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Updates the account type or tags for a storage account. It can /// also be used to add a custom domain (note that custom domains /// cannot be added via the Create operation). Only one custom domain /// is supported per storage account. In order to replace a custom /// domain, the old value must be cleared before a new value may be /// set. To clear a custom domain, simply update the custom domain /// with empty string. Then call update again with the new cutsom /// domain name. The update API can only be used to update one of /// tags, accountType, or customDomain per call. To update multiple /// of these properties, call the API multiple times with one change /// per call. This call does not change the storage keys for the /// account. If you want to change storage account keys, use the /// RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters /// in length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one /// property can be changed at a time using this API. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<StorageAccountInner>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountUpdateParametersInner parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<StorageAccountKeysInner>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all the storage accounts available under the subscription. /// Note that storage keys are not returned; use the ListKeys /// operation for this. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<StorageAccountInner>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all the storage accounts available under the given resource /// group. Note that storage keys are not returned; use the ListKeys /// operation for this. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<StorageAccountInner>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters /// in length and use numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or /// key2 for the default keys /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<StorageAccountKeysInner>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountRegenerateKeyParametersInner regenerateKey, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Python Tools for Visual Studio // 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.Linq; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Analysis.AnalysisSetDetails; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; namespace AnalysisTests { class TestAnalysisValue : AnalysisValue { public string _name; public override string Name { get { return _name; } } public string Value; public int MergeCount; public TestAnalysisValue() { MergeCount = 1; } public override bool Equals(object obj) { var tns = obj as TestAnalysisValue; if (tns == null) { return false; } return Name.Equals(tns.Name) && Value.Equals(tns.Value) && MergeCount.Equals(tns.MergeCount); } public override int GetHashCode() { return Name.GetHashCode() ^ Value.GetHashCode(); } internal override bool UnionEquals(AnalysisValue ns, int strength) { var tns = ns as TestAnalysisValue; if (tns == null) { return false; } return Name.Equals(tns.Name); } internal override int UnionHashCode(int strength) { return Name.GetHashCode(); } internal override AnalysisValue UnionMergeTypes(AnalysisValue ns, int strength) { var tns = ns as TestAnalysisValue; if (tns == null || object.ReferenceEquals(this, tns)) { return this; } return new TestAnalysisValue { _name = Name, Value = MergeCount > tns.MergeCount ? Value : tns.Value, MergeCount = MergeCount + tns.MergeCount }; } public override string ToString() { return string.Format("{0}:{1}", Name, Value); } } [TestClass] public class AnalysisSetTest { private static readonly AnalysisValue nsA1 = new TestAnalysisValue { _name = "A", Value = "a" }; private static readonly AnalysisValue nsA2 = new TestAnalysisValue { _name = "A", Value = "x" }; private static readonly AnalysisValue nsAU1 = nsA1.UnionMergeTypes(nsA2, 100); private static readonly AnalysisValue nsAU2 = nsAU1.UnionMergeTypes(nsA2, 100); private static readonly AnalysisValue nsAU3 = nsAU2.UnionMergeTypes(nsA2, 100); private static readonly AnalysisValue nsAU4 = nsAU3.UnionMergeTypes(nsA2, 100); private static readonly AnalysisValue nsB1 = new TestAnalysisValue { _name = "B", Value = "b" }; private static readonly AnalysisValue nsB2 = new TestAnalysisValue { _name = "B", Value = "y" }; private static readonly AnalysisValue nsBU1 = nsB1.UnionMergeTypes(nsB2, 100); private static readonly AnalysisValue nsBU2 = nsBU1.UnionMergeTypes(nsB2, 100); private static readonly AnalysisValue nsBU3 = nsBU2.UnionMergeTypes(nsB2, 100); private static readonly AnalysisValue nsBU4 = nsBU3.UnionMergeTypes(nsB2, 100); private static readonly AnalysisValue nsC1 = new TestAnalysisValue { _name = "C", Value = "c" }; private static readonly AnalysisValue nsC2 = new TestAnalysisValue { _name = "C", Value = "z" }; private static readonly AnalysisValue nsCU1 = nsC1.UnionMergeTypes(nsC2, 100); private static readonly AnalysisValue nsCU2 = nsCU1.UnionMergeTypes(nsC2, 100); private static readonly AnalysisValue nsCU3 = nsCU2.UnionMergeTypes(nsC2, 100); private static readonly AnalysisValue nsCU4 = nsCU3.UnionMergeTypes(nsC2, 100); [TestMethod, Priority(0)] public void SetOfOne_Object() { var set = AnalysisSet.Create(nsA1); Assert.AreSame(nsA1, set); set = AnalysisSet.Create(new[] { nsA1 }.AsEnumerable()); Assert.AreSame(nsA1, set); set = AnalysisSet.Create(new[] { nsA1, nsA1 }.AsEnumerable()); Assert.AreSame(nsA1, set); set = AnalysisSet.Create(new[] { nsA1, nsA2 }.AsEnumerable()); Assert.AreNotSame(nsA1, set); } [TestMethod, Priority(0)] public void SetOfOne_Union() { var set = AnalysisSet.CreateUnion(nsA1, UnionComparer.Instances[0]); Assert.IsInstanceOfType(set, typeof(AnalysisSetOneUnion)); AssertUtil.ContainsExactly(set, nsA1); set = AnalysisSet.CreateUnion(new[] { nsA1 }.AsEnumerable(), UnionComparer.Instances[0]); Assert.IsInstanceOfType(set, typeof(AnalysisSetOneUnion)); AssertUtil.ContainsExactly(set, nsA1); set = AnalysisSet.CreateUnion(new[] { nsA1, nsA1 }.AsEnumerable(), UnionComparer.Instances[0]); Assert.IsInstanceOfType(set, typeof(AnalysisSetOneUnion)); AssertUtil.ContainsExactly(set, nsA1); set = AnalysisSet.CreateUnion(new[] { nsA1, nsA2 }.AsEnumerable(), UnionComparer.Instances[0]); Assert.IsInstanceOfType(set, typeof(AnalysisSetOneUnion)); AssertUtil.ContainsExactly(set, nsAU1); } [TestMethod, Priority(0)] public void SetOfTwo_Object() { var set = AnalysisSet.Create(new[] { nsA1, nsA2 }); Assert.IsInstanceOfType(set, typeof(AnalysisSetTwoObject)); AssertUtil.ContainsExactly(set, nsA1, nsA2); set = AnalysisSet.Create(new[] { nsA1, nsA1, nsA2, nsA2 }); Assert.IsInstanceOfType(set, typeof(AnalysisSetTwoObject)); AssertUtil.ContainsExactly(set, nsA1, nsA2); } [TestMethod, Priority(0)] public void SetOfTwo_Union() { var set = AnalysisSet.CreateUnion(new[] { nsA1, nsA2, nsB1, nsB2 }, UnionComparer.Instances[0]); Assert.IsInstanceOfType(set, typeof(AnalysisSetTwoUnion)); AssertUtil.ContainsExactly(set, nsAU1, nsBU1); set = AnalysisSet.CreateUnion(new[] { nsA1, nsA1, nsA2, nsA2, nsB1, nsB1, nsB2, nsB2 }, UnionComparer.Instances[0]); Assert.IsInstanceOfType(set, typeof(AnalysisSetTwoUnion)); AssertUtil.ContainsExactly(set, nsAU2, nsBU2); } [TestMethod, Priority(0)] public void ManySet_Object() { var set = AnalysisSet.Create(new[] { nsA1, nsA2, nsB1, nsB2 }); Assert.IsInstanceOfType(set, typeof(AnalysisHashSet)); Assert.AreEqual(4, set.Count); AssertUtil.ContainsExactly(set, nsA1, nsA2, nsB1, nsB2); set = AnalysisSet.Create(new[] { nsA1, nsA1, nsA2, nsA2, nsB1, nsB1, nsB2, nsB2 }); Assert.IsInstanceOfType(set, typeof(AnalysisHashSet)); Assert.AreEqual(4, set.Count); AssertUtil.ContainsExactly(set, nsA1, nsA2, nsB1, nsB2); } [TestMethod, Priority(0)] public void ManySet_Union() { var set = AnalysisSet.CreateUnion(new[] { nsA1, nsA2, nsB1, nsB2, nsC1 }, UnionComparer.Instances[0]); Assert.IsInstanceOfType(set, typeof(AnalysisHashSet)); Assert.AreEqual(3, set.Count); AssertUtil.ContainsExactly(set, nsAU1, nsBU1, nsC1); set = AnalysisSet.CreateUnion(new[] { nsA1, nsA1, nsA2, nsA2, nsB1, nsB1, nsB2, nsB2, nsC1 }, UnionComparer.Instances[0]); Assert.IsInstanceOfType(set, typeof(AnalysisHashSet)); Assert.AreEqual(3, set.Count); AssertUtil.ContainsExactly(set, nsAU2, nsBU2, nsC1); } [TestMethod, Priority(0)] public void EmptySet_Add_Object() { var set = AnalysisSet.Empty; Assert.IsInstanceOfType(set, typeof(AnalysisSetEmptyObject)); set = AnalysisSet.Create(); Assert.IsInstanceOfType(set, typeof(AnalysisSetEmptyObject)); Assert.AreSame(AnalysisSet.Empty, set); bool added; set = set.Add(nsA1, out added, false); Assert.IsTrue(added); Assert.AreSame(nsA1, set); set = AnalysisSet.Empty; set = set.Add(nsA1, out added, true); Assert.IsTrue(added); Assert.AreSame(nsA1, set); } [TestMethod, Priority(0)] public void EmptySet_Add_Union() { var set = AnalysisSet.EmptyUnion; Assert.IsInstanceOfType(set, typeof(AnalysisSetEmptyUnion)); set = AnalysisSet.CreateUnion(UnionComparer.Instances[0]); Assert.IsInstanceOfType(set, typeof(AnalysisSetEmptyUnion)); Assert.AreSame(AnalysisSet.EmptyUnion, set); bool added; set = set.Add(nsA1, out added, false); Assert.IsTrue(added); AssertUtil.ContainsExactly(set, nsA1); set = AnalysisSet.EmptyUnion; set = set.Add(nsA1, out added, true); Assert.IsTrue(added); AssertUtil.ContainsExactly(set, nsA1); } [TestMethod, Priority(0)] public void SetOfOne_Add_Object() { var set = AnalysisSet.Create(nsA1); bool added; set = set.Add(nsA1, out added, true); Assert.AreSame(nsA1, set); Assert.IsFalse(added); set = set.Add(nsA1, out added, false); Assert.AreSame(nsA1, set); Assert.IsFalse(added); set = set.Add(nsB1, out added, true); Assert.IsInstanceOfType(set, typeof(AnalysisSetTwoObject)); Assert.IsTrue(added); set = AnalysisSet.Create(nsA1); var set2 = set.Add(nsA1, out added, true); Assert.AreSame(set, set2); Assert.IsFalse(added); AssertUtil.ContainsExactly(set2, nsA1); } [TestMethod, Priority(0)] public void SetOfOne_Add_Union() { var set = AnalysisSet.CreateUnion(nsA1, UnionComparer.Instances[0]); bool added; set = set.Add(nsA1, out added, true); Assert.IsInstanceOfType(set, typeof(AnalysisSetOneUnion)); Assert.IsFalse(added); set = set.Add(nsA1, out added, false); Assert.IsInstanceOfType(set, typeof(AnalysisSetOneUnion)); Assert.IsFalse(added); set = set.Add(nsB1, out added, true); Assert.IsInstanceOfType(set, typeof(AnalysisSetTwoUnion)); AssertUtil.ContainsExactly(set, nsA1, nsB1); Assert.IsTrue(added); set = AnalysisSet.CreateUnion(nsA1, UnionComparer.Instances[0]); var set2 = set.Add(nsA2, out added, true); Assert.AreNotSame(set, set2); Assert.IsTrue(added); AssertUtil.ContainsExactly(set2, nsAU1); } [TestMethod, Priority(0)] public void SetOfTwo_Add_Object() { var set = AnalysisSet.Create(new[] { nsA1, nsB1 }); IAnalysisSet set2; bool added; foreach (var o in new[] { nsA1, nsB1 }) { set2 = set.Add(o, out added, true); Assert.AreSame(set, set2); Assert.IsFalse(added); set2 = set.Add(o, out added, false); Assert.AreSame(set, set2); Assert.IsFalse(added); } foreach (var o in new[] { nsA2, nsB2, nsC1, nsC2 }) { set2 = set.Add(o, out added, true); Assert.AreNotSame(set, set2); AssertUtil.ContainsExactly(set2, nsA1, nsB1, o); Assert.IsTrue(added); set2 = set.Add(o, out added, false); Assert.AreNotSame(set, set2); AssertUtil.ContainsExactly(set2, nsA1, nsB1, o); Assert.IsTrue(added); } } [TestMethod, Priority(0)] public void SetOfTwo_Add_Union() { var set = AnalysisSet.CreateUnion(new[] { nsA1, nsB1 }, UnionComparer.Instances[0]); IAnalysisSet set2; bool added; foreach (var o in new[] { nsA1, nsB1 }) { set2 = set.Add(o, out added, true); Assert.AreSame(set, set2); Assert.IsFalse(added); set2 = set.Add(o, out added, false); Assert.AreSame(set, set2); Assert.IsFalse(added); } foreach (var o in new[] { nsC1, nsC2 }) { set2 = set.Add(o, out added, true); Assert.AreNotSame(set, set2); AssertUtil.ContainsExactly(set2, nsA1, nsB1, o); Assert.IsTrue(added); set2 = set.Add(o, out added, false); Assert.AreNotSame(set, set2); AssertUtil.ContainsExactly(set2, nsA1, nsB1, o); Assert.IsTrue(added); } set2 = set.Add(nsA2, out added, true); Assert.AreNotSame(set, set2); Assert.IsInstanceOfType(set2, typeof(AnalysisSetTwoUnion)); AssertUtil.ContainsExactly(set2, nsAU1, nsB1); Assert.IsTrue(added); set2 = set.Add(nsB2, out added, false); Assert.AreNotSame(set, set2); Assert.IsInstanceOfType(set2, typeof(AnalysisSetTwoUnion)); AssertUtil.ContainsExactly(set2, nsA1, nsBU1); Assert.IsTrue(added); } [TestMethod, Priority(0)] public void ManySet_Add_Object() { var set = AnalysisSet.Create(new[] { nsA1, nsB1, nsC1 }); IAnalysisSet set2; bool added; foreach (var o in new[] { nsA1, nsB1, nsC1 }) { set2 = set.Add(o, out added, true); Assert.AreSame(set, set2); Assert.IsFalse(added); set2 = set.Add(o, out added, false); Assert.AreSame(set, set2); Assert.IsFalse(added); } foreach (var o in new[] { nsA2, nsB2, nsC2 }) { set = AnalysisSet.Create(new[] { nsA1, nsB1, nsC1 }); set2 = set.Add(o, out added, false); Assert.AreNotSame(set, set2); AssertUtil.ContainsExactly(set2, nsA1, nsB1, nsC1, o); Assert.IsTrue(added); set2 = set.Add(o, out added, true); Assert.AreSame(set, set2); AssertUtil.ContainsExactly(set2, nsA1, nsB1, nsC1, o); Assert.IsTrue(added); } } [TestMethod, Priority(0)] public void ManySet_Add_Union() { var set = AnalysisSet.CreateUnion(new[] { nsA1, nsB1, nsC1 }, UnionComparer.Instances[0]); IAnalysisSet set2; bool added; foreach (var o in new[] { nsA1, nsB1, nsC1 }) { set2 = set.Add(o, out added, true); Assert.AreSame(set, set2); Assert.IsFalse(added); set2 = set.Add(o, out added, false); Assert.AreSame(set, set2); Assert.IsFalse(added); } set2 = set.Add(nsA2, out added, true); Assert.AreSame(set, set2); Assert.IsInstanceOfType(set2, typeof(AnalysisHashSet)); AssertUtil.ContainsExactly(set2, nsAU1, nsB1, nsC1); Assert.IsTrue(added); set = AnalysisSet.CreateUnion(new[] { nsA1, nsB1, nsC1 }, UnionComparer.Instances[0]); set2 = set.Add(nsA2, out added, false); Assert.AreNotSame(set, set2); Assert.IsInstanceOfType(set2, typeof(AnalysisHashSet)); AssertUtil.ContainsExactly(set2, nsAU1, nsB1, nsC1); Assert.IsTrue(added); set2 = set.Add(nsB2, out added, false); Assert.AreNotSame(set, set2); Assert.IsInstanceOfType(set2, typeof(AnalysisHashSet)); AssertUtil.ContainsExactly(set2, nsA1, nsBU1, nsC1); Assert.IsTrue(added); set2 = set.Add(nsC2, out added, false); Assert.AreNotSame(set, set2); Assert.IsInstanceOfType(set2, typeof(AnalysisHashSet)); AssertUtil.ContainsExactly(set2, nsA1, nsB1, nsCU1); Assert.IsTrue(added); } } }
using System; using Android.OS; using Android.App; using Android.Views; using Android.Widget; using System.Net.Http; using System.Threading.Tasks; using Microsoft.WindowsAzure.MobileServices; using Microsoft.WindowsAzure.MobileServices.Sync; using Microsoft.WindowsAzure.MobileServices.SQLiteStore; using System.IO; using Gcm.Client; using Newtonsoft.Json.Linq; namespace todolist_complete { [Activity (MainLauncher = true, Icon="@drawable/ic_launcher", Label="@string/app_name", Theme="@style/AppTheme")] public class ToDoActivity : Activity { //Mobile Service Client reference private MobileServiceClient client; //Mobile Service sync table used to access data private IMobileServiceSyncTable<ToDoItem> toDoTable; //Adapter to map the items list to the view private ToDoItemAdapter adapter; //EditText containing the "New ToDo" text private EditText textNewToDo; // URL of the Mobile App backend const string applicationURL = @"https://{your-mobile-app-backend}.azurewebsites.net"; const string localDbFilename = "localstore.db"; const MobileServiceAuthenticationProvider provider = MobileServiceAuthenticationProvider.Facebook; // Create a new instance field for this activity. static ToDoActivity instance = new ToDoActivity(); // Return the current activity instance. public static ToDoActivity CurrentActivity { get { return instance; } } // Return the Mobile Services client. public MobileServiceClient CurrentClient { get { return client; } } protected override async void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Activity_To_Do); CurrentPlatform.Init (); // Create the Mobile Service Client instance, using the provided // Mobile Service URL client = new MobileServiceClient(applicationURL); await InitLocalStoreAsync(); // Set the current instance of TodoActivity. instance = this; // Make sure the GCM client is set up correctly. GcmClient.CheckDevice(this); GcmClient.CheckManifest(this); // Get the Mobile Service sync table instance to use toDoTable = client.GetSyncTable <ToDoItem> (); textNewToDo = FindViewById<EditText> (Resource.Id.textNewToDo); // Create an adapter to bind the items with the view adapter = new ToDoItemAdapter (this, Resource.Layout.Row_List_To_Do); var listViewToDo = FindViewById<ListView> (Resource.Id.listViewToDo); listViewToDo.Adapter = adapter; //// Load the items from the Mobile App backend. //OnRefreshItemsSelected (); } // Define a authenticated user. private MobileServiceUser user; private async Task<bool> Authenticate() { var success = false; try { // Sign in with Facebook login using a server-managed flow. user = await client.LoginAsync(this, provider ); CreateAndShowDialog(string.Format("you are now logged in - {0}", user.UserId), "Logged in!"); success = true; } catch (Exception ex) { CreateAndShowDialog(ex, "Authentication failed"); } return success; } [Java.Interop.Export()] public async void LoginUser(View view) { // Only register for push notifications and load data after authentication succeeds. if (await Authenticate()) { // Register the app for push notifications. GcmClient.Register(this, ToDoBroadcastReceiver.senderIDs); //Hide the button after authentication succeeds. FindViewById<Button>(Resource.Id.buttonLoginUser).Visibility = ViewStates.Gone; // Load the data. OnRefreshItemsSelected(); } } private async Task InitLocalStoreAsync() { // new code to initialize the SQLite store string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), localDbFilename); if (!File.Exists(path)) { File.Create(path).Dispose(); } var store = new MobileServiceSQLiteStore(path); store.DefineTable<ToDoItem>(); // Uses the default conflict handler, which fails on conflict // To use a different conflict handler, pass a parameter to InitializeAsync. // For more details, see http://go.microsoft.com/fwlink/?LinkId=521416 await client.SyncContext.InitializeAsync(store); } //Initializes the activity menu public override bool OnCreateOptionsMenu (IMenu menu) { MenuInflater.Inflate (Resource.Menu.activity_main, menu); return true; } //Select an option from the menu public override bool OnOptionsItemSelected (IMenuItem item) { if (item.ItemId == Resource.Id.menu_refresh) { item.SetEnabled(false); OnRefreshItemsSelected (); item.SetEnabled(true); } return true; } private async Task SyncAsync() { try { await client.SyncContext.PushAsync(); await toDoTable.PullAsync("allTodoItems", toDoTable.CreateQuery()); // query ID is used for incremental sync } catch (Java.Net.MalformedURLException) { CreateAndShowDialog (new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error"); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } // Called when the refresh menu option is selected private async void OnRefreshItemsSelected () { await SyncAsync(); // get changes from the mobile service await RefreshItemsFromTableAsync(); // refresh view using local database } //Refresh the list with the items in the local database private async Task RefreshItemsFromTableAsync () { try { // Get the items that weren't marked as completed and add them in the adapter var list = await toDoTable.Where (item => item.Complete == false).ToListAsync (); adapter.Clear (); foreach (ToDoItem current in list) adapter.Add (current); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } public async Task CheckItem (ToDoItem item) { if (client == null) { return; } // Set the item as completed and update it in the table item.Complete = true; try { await toDoTable.UpdateAsync(item); // update the new item in the local database await SyncAsync(); // send changes to the mobile service if (item.Complete) adapter.Remove (item); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } [Java.Interop.Export()] public async void AddItem (View view) { if (client == null || string.IsNullOrWhiteSpace (textNewToDo.Text)) { return; } // Create a new item var item = new ToDoItem { Text = textNewToDo.Text, Complete = false }; try { await toDoTable.InsertAsync(item); // insert the new item into the local database await SyncAsync(); // send changes to the mobile service if (!item.Complete) { adapter.Add (item); } } catch (Exception e) { CreateAndShowDialog (e, "Error"); } textNewToDo.Text = ""; } private void CreateAndShowDialog (Exception exception, String title) { CreateAndShowDialog (exception.Message, title); } private void CreateAndShowDialog (string message, string title) { AlertDialog.Builder builder = new AlertDialog.Builder (this); builder.SetMessage (message); builder.SetTitle (title); builder.Create ().Show (); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public enum ToolMode { Brush, Eraser, Dropper, Bucket }; public enum TextEnteringMode { None, AnimName, PixelDimensions, Hitbox, CurrentFrameTime, PaletteColor, LoadAnimation }; [RequireComponent(typeof(Camera))] public class PixelEditorScreen : MonoBehaviour { private static PixelEditorScreen _instance; public static PixelEditorScreen shared { get{ return _instance; } } bool _initialized = false; Vector2 _borderDragWorldOffset; //----------------------------------------------------- // GUI TEXT BOXES //----------------------------------------------------- string _animName = "..."; public string AnimName { get { return _animName; } set { _animName = value; } } string _animNameTempString; string _pixelDimensionsString = ""; PixelRect _hitbox; public PixelRect Hitbox { get { return _hitbox; } } string _hitboxString; bool _showingHitbox; public bool ShowingHitbox { get { return _showingHitbox; } } string _loopTypeString = ""; public string LoopTypeString { get { return _loopTypeString; } set { _loopTypeString = value; } } string _onionSkinString = ""; public string OnionSkinString { get { return _onionSkinString; } set { _onionSkinString = value; } } string _mirroringString = ""; public string MirroringString { get { return _mirroringString; } set { _mirroringString = value; } } string _currentFrameTimeString = ""; public string CurrentFrameTimeString { get { return _currentFrameTimeString; } set { _currentFrameTimeString = value; } } string _paletteColorString = ""; public string PaletteColorString { get { return _paletteColorString; } set { _paletteColorString = value; } } string _gridIndexString = "(4,0)"; public string GridIndexString { get { return _gridIndexString; } set { _gridIndexString = value; } } string _loadAnimString = ""; GUIStyle _textStyle; GUIStyle _textStyleRed; GUIStyle _textStyleFocused; TextEnteringMode _textEnteringMode = TextEnteringMode.None; public TextEnteringMode GetTextEnteringMode() { return _textEnteringMode; } public void SetTextEnteringMode(TextEnteringMode mode) { _textEnteringMode = mode; } bool _firstChar = true; Vector2 _paletteInputScreenPosition; public Vector2 PaletteInputScreenPosition { get { return _paletteInputScreenPosition; } set { _paletteInputScreenPosition = value; } } Color32 _currentColor; public Color32 GetCurrentColor() { return _swatch.GetCurrentColor(); } Canvas _canvas; public Canvas GetCanvas() { return _canvas; } Swatch _swatch; Palette _palette; public Palette GetPalette() { return _palette; } FramePreview _framePreview; public FramePreview GetFramePreview() { return _framePreview; } PatternViewer _patternViewer; public PatternViewer GetPatternViewer() { return _patternViewer; } int _lastCanvasWidth; int _lastCanvasHeight; const int MAX_CANVAS_WIDTH = 128; const int MAX_CANVAS_HEIGHT = 128; public int CurrentFrame { get { if(_framePreview == null) { return 0; } return _framePreview.CurrentFrame; } } //----------------------------------------------------- // CURSOR STUFF //----------------------------------------------------- ToolMode _toolMode; public ToolMode GetToolMode() { return _toolMode; } public Texture2D cursorBrush; public Texture2D cursorEraser; public Texture2D cursorDropper; public Texture2D cursorPaint; //----------------------------------------------------- // COPY & PASTE EFFECTS //----------------------------------------------------- Color32[] _copiedPixels; GameObject _effectPlane; const float EFFECT_ZOOM_TIME = 0.25f; const float EFFECT_EXTRA_SCALE = 0.15f; public static float CAMERA_ZOOM_SPEED = 0.08f; public static float ZOOM_TIMER_LENIENCY = 0.2f; //----------------------------------------------------- // PLANE DEPTHS //----------------------------------------------------- public static float EFFECT_PLANE_DEPTH = 1.0f; public static float CANVAS_PLANE_DEPTH = 2.0f; public static float PALETTE_PLANE_DEPTH = 3.0f; public static float FRAME_PREVIEW_DEPTH = 4.0f; public static float SWATCH_PLANE_DEPTH = 5.0f; public static float PATTERN_PLANE_DEPTH = 6.0f; //----------------------------------------------------- // COLORS //----------------------------------------------------- // public static Color BORDER_COLOR = new Color(0.0f, 0.0f, 0.0f, 0.3f); public static Color BORDER_COLOR = new Color(0.7f, 0.7f, 0.7f, 1.0f); public static Color BORDER_COLOR_CURRENT_FRAME = new Color(0.45f, 0.45f, 0.45f, 1.0f); public static Color BORDER_COLOR_NONCURRENT_FRAME = new Color(0.8f, 0.8f, 0.8f, 1.0f); public static byte CANVAS_CHECKERS_EVEN_SHADE = 255; public static byte CANVAS_CHECKERS_ODD_SHADE = 249; public bool GetIsDragging() { return _canvas.DraggingCanvasBorder || _palette.DraggingPaletteBorder || _framePreview.DraggingPreviewFrames || _swatch.DraggingSwatchBorder || _patternViewer.DraggingPatternBorder; } public bool GetIsEditingPixels() { return _canvas.CurrentlyEditingPixels; } public bool GetModifierKey() { return Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) || Input.GetKey(KeyCode.LeftControl); } PseudoStack<Command> _commandUndoStack = new PseudoStack<Command>(); PseudoStack<Command> _commandRedoStack = new PseudoStack<Command>(); const int MAX_COMMANDS = 50; GUIText _consoleText; ConsoleTextSetter _consoleTextWrap; bool _isShowingConsoleText = false; public void AddNewCommand(Command command) { Debug.Log("AddNewCommand: " + command.Name); if(_commandUndoStack.Count >= MAX_COMMANDS) _commandUndoStack.Remove(0); command.SetEditor(this); command.DoCommand(); _commandUndoStack.Push(command); _commandRedoStack.Clear(); } public void UndoLastCommand() { if(_commandUndoStack.Count > 0) { Command lastCommand = _commandUndoStack.Pop(); lastCommand.UndoCommand(); _commandRedoStack.Push(lastCommand); // Debug.Log("Undo: " + lastCommand.Name); } } public void RedoLastCommand() { if(_commandRedoStack.Count > 0) { Command lastCommand = _commandRedoStack.Pop(); lastCommand.RedoCommand(); _commandUndoStack.Push(lastCommand); // Debug.Log("Redo: " + lastCommand.Name); } } void Awake() { _instance = this; } void Start() { Init(); } public bool Init() { if(!_initialized) { // these seem to return 0 sometimes if we check them too early // so we won't consider the pixel screen initialized until we can get back a non-zero value for these if(Screen.width == 0 || Screen.height == 0) return false; int screenWidth = PlayerPrefs.GetInt("screenWidth", 800); int screenHeight = PlayerPrefs.GetInt("screenHeight", 500); screenWidth = Mathf.Max(screenHeight, 300); screenHeight = Mathf.Max(screenHeight, 300); Screen.SetResolution(screenWidth, screenHeight, false); Camera camera = GetComponent<Camera>(); camera.orthographic = true; camera.orthographicSize = 1; // ---------------------------------------------- // CANVAS // ---------------------------------------------- _canvas = gameObject.AddComponent<Canvas>(); _canvas.Init(this); _lastCanvasWidth = _canvas.pixelWidth; _lastCanvasHeight = _canvas.pixelHeight; _copiedPixels = new Color32[_canvas.pixelWidth * _canvas.pixelHeight]; _canvas.GetPixels(CurrentFrame).CopyTo(_copiedPixels, 0); _pixelDimensionsString = _canvas.pixelWidth.ToString() + "," + _canvas.pixelHeight.ToString(); _hitbox = new PixelRect(0, 0, _canvas.pixelWidth, _canvas.pixelHeight); RefreshHitboxString(); // ---------------------------------------------- // SWATCH // ---------------------------------------------- _swatch = gameObject.AddComponent<Swatch>(); _swatch.Init(this); SetCurrentColor(Color.black); // ---------------------------------------------- // PALETTE // ---------------------------------------------- _palette = gameObject.AddComponent<Palette>(); _palette.Init(this); CreateEffectPlane(); // ---------------------------------------------- // FRAME PREVIEW // ---------------------------------------------- _framePreview = gameObject.AddComponent<FramePreview>(); _framePreview.Init(this); // ---------------------------------------------- // PATTERN VIEWER // ---------------------------------------------- _patternViewer = gameObject.AddComponent<PatternViewer>(); _patternViewer.Init(this); _initialized = true; _textStyle = new GUIStyle(); _textStyle.font = Resources.Load("Fonts/04b03") as Font; _textStyle.normal.textColor = new Color(0.8f, 0.8f, 0.8f); _textStyle.fontSize = 20; _textStyleRed = new GUIStyle(_textStyle); _textStyleRed.normal.textColor = new Color(0.8f, 0.2f, 0.2f); _textStyleFocused = new GUIStyle(); _textStyleFocused.font = Resources.Load("Fonts/04b03") as Font; _textStyleFocused.normal.textColor = Color.white; Texture2D black = new Texture2D(1, 1); black.SetPixel(0, 0, Color.black); black.Apply(); _textStyleFocused.normal.background = black; _textStyleFocused.fontSize = 20; _toolMode = ToolMode.Brush; // Cursor.SetCursor(cursorBrush, Vector2.zero, CursorMode.Auto); _canvas.SetOnionSkinMode((OnionSkinMode)PlayerPrefs.GetInt("onionSkinMode", 0)); _canvas.RefreshOnionSkin(); _canvas.SetMirroringMode((MirroringMode)PlayerPrefs.GetInt("mirroringMode", 0)); _consoleText = gameObject.AddComponent<GUIText>(); _consoleText.color = Color.black; _consoleText.font = Resources.Load("Fonts/04b03") as Font; _consoleText.fontSize = 12; _consoleText.transform.position = new Vector2(0.0025f, 0); _consoleText.anchor = TextAnchor.LowerLeft; _consoleTextWrap = gameObject.AddComponent<ConsoleTextSetter>(); string animData = PlayerPrefs.GetString("animData", ""); Debug.Log("animData: " + animData); if(animData != "") LoadAnimationString(animData); } return _initialized; } void ShowConsoleText(string text) { _consoleTextWrap.SetText(text); _isShowingConsoleText = true; } // create the plane that will be animated for copy/paste effects // (only do this once) void CreateEffectPlane() { GameObject canvasPlane = _canvas.GetCanvasPlane(); _effectPlane = (GameObject)Instantiate(canvasPlane); Destroy(_effectPlane.transform.FindChild("Border").gameObject); // get rid of border Destroy(_effectPlane.transform.FindChild("Grid").gameObject); // get rid of grid Destroy(_effectPlane.transform.FindChild("OnionSkin").gameObject); // get rid of onion skin _effectPlane.transform.parent = canvasPlane.transform.parent; _effectPlane.name = "EffectPlane"; Material effectMaterial = (Material)Instantiate(Resources.Load("Materials/UnlitAlphaWithFade") as Material); _effectPlane.renderer.material = effectMaterial; _effectPlane.SetActive(false); } // used each time we want to play the copy effect // resets the orientation of the copy frame, fills with current pixel data, and starts the copy animation coroutine void PlayCopyEffect() { GameObject canvasPlane = _canvas.GetCanvasPlane(); StopCoroutine("CopyEffectCoroutine"); StopCoroutine("PasteEffectCoroutine"); _effectPlane.renderer.material.mainTexture = (Texture2D)Instantiate(canvasPlane.renderer.material.mainTexture); _effectPlane.transform.localPosition = new Vector3(canvasPlane.transform.localPosition.x, canvasPlane.transform.localPosition.y, EFFECT_PLANE_DEPTH); _effectPlane.transform.localScale = canvasPlane.transform.localScale; _effectPlane.renderer.material.color = Color.white; _effectPlane.SetActive(true); StartCoroutine("CopyEffectCoroutine"); } IEnumerator CopyEffectCoroutine() { GameObject canvasPlane = _canvas.GetCanvasPlane(); float elapsedTime = 0.0f; while(elapsedTime < EFFECT_ZOOM_TIME) { float extraScale = Utils.Map(elapsedTime, 0.0f, EFFECT_ZOOM_TIME, 0.0f, EFFECT_EXTRA_SCALE, true, EASING_TYPE.CUBIC_EASE_OUT); float opacity = Utils.Map(elapsedTime, 0.0f, EFFECT_ZOOM_TIME, 1.0f, 0.0f, true, EASING_TYPE.CUBIC_EASE_OUT); _effectPlane.transform.localScale = new Vector3(canvasPlane.transform.localScale.x * (1.0f + extraScale), canvasPlane.transform.localScale.y * (1.0f + extraScale), 1.0f); _effectPlane.renderer.material.color = new Color(1.0f, 1.0f, 1.0f, opacity); elapsedTime += Time.deltaTime; yield return null; } _effectPlane.SetActive(false); _effectPlane.renderer.material.mainTexture = null; } // used each time we want to play the paste effect // sets the effect frame to the zoomed-out orientation, fills with current copied pixel data, and starts the paste animation coroutine void PlayPasteEffect() { GameObject canvasPlane = _canvas.GetCanvasPlane(); StopCoroutine("CopyEffectCoroutine"); StopCoroutine("PasteEffectCoroutine"); _effectPlane.renderer.material.mainTexture = (Texture2D)Instantiate(canvasPlane.renderer.material.mainTexture); ((Texture2D)_effectPlane.renderer.material.mainTexture).SetPixels32(_copiedPixels); ((Texture2D)_effectPlane.renderer.material.mainTexture).Apply(); _effectPlane.transform.localPosition = new Vector3(canvasPlane.transform.localPosition.x, canvasPlane.transform.localPosition.y, EFFECT_PLANE_DEPTH); _effectPlane.transform.localScale = new Vector3(canvasPlane.transform.localScale.x * (1.0f + EFFECT_EXTRA_SCALE), canvasPlane.transform.localScale.y * (1.0f + EFFECT_EXTRA_SCALE), 1.0f); _effectPlane.renderer.material.color = new Color(1.0f, 1.0f, 1.0f, 0.0f); _effectPlane.SetActive(true); StartCoroutine("PasteEffectCoroutine"); } IEnumerator PasteEffectCoroutine() { GameObject canvasPlane = _canvas.GetCanvasPlane(); float elapsedTime = 0.0f; while(elapsedTime < EFFECT_ZOOM_TIME) { float extraScale = Utils.Map(elapsedTime, 0.0f, EFFECT_ZOOM_TIME, EFFECT_EXTRA_SCALE, 0.0f, true, EASING_TYPE.SINE_EASE_IN); float opacity = Utils.Map(elapsedTime, 0.0f, EFFECT_ZOOM_TIME, 0.0f, 1.0f, true, EASING_TYPE.SINE_EASE_IN); _effectPlane.transform.localScale = new Vector3(canvasPlane.transform.localScale.x * (1.0f + extraScale), canvasPlane.transform.localScale.y * (1.0f + extraScale), 1.0f); _effectPlane.renderer.material.color = new Color(1.0f, 1.0f, 1.0f, opacity); elapsedTime += Time.deltaTime; yield return null; } _effectPlane.SetActive(false); _effectPlane.renderer.material.mainTexture = null; AddNewCommand(new PasteFrameCommand(_copiedPixels)); } void NewCanvas() { _framePreview.NewCanvas(); _commandUndoStack.Clear(); _commandRedoStack.Clear(); _canvas.NewCanvas(); // re-init copied pixels so the array is the right size/dimensions if(_canvas.pixelWidth != _lastCanvasWidth || _canvas.pixelHeight != _lastCanvasHeight) _copiedPixels = new Color32[_canvas.pixelWidth * _canvas.pixelHeight]; _hitbox = new PixelRect(0, 0, _canvas.pixelWidth, _canvas.pixelHeight); RefreshHitboxString(); _canvas.RefreshHitbox(); _framePreview.ResizeFramePreviews(); _framePreview.CreateFramePlane(); _lastCanvasWidth = _canvas.pixelWidth; _lastCanvasHeight = _canvas.pixelHeight; _patternViewer.NewCanvas(); } void Update() { // ------------------------------------------------- // UNDO // ------------------------------------------------- if(GetModifierKey() && Input.GetKeyDown(KeyCode.Z) && !GetIsEditingPixels()) UndoLastCommand(); // ------------------------------------------------- // REDO // ------------------------------------------------- if(GetModifierKey() && Input.GetKeyDown(KeyCode.Y) && !GetIsEditingPixels()) RedoLastCommand(); // ------------------------------------------------- // TOGGLE SHOWING HITBOX // ------------------------------------------------- if(Input.GetKeyDown(KeyCode.H) && _textEnteringMode == TextEnteringMode.None) { _showingHitbox = !_showingHitbox; _canvas.RefreshHitbox(); } // ------------------------------------------------- // LOADING ANIMATIONS // ------------------------------------------------- if(GetModifierKey() && Input.GetKeyDown(KeyCode.O) && !GetIsEditingPixels()) { _loadAnimString = "***PASTE ANIM DATA***"; _textEnteringMode = TextEnteringMode.LoadAnimation; } // ------------------------------------------------- // SWITCHING TOOLS // ------------------------------------------------- if(_textEnteringMode == TextEnteringMode.None) { if(Input.GetKeyDown(KeyCode.B)) SetToolMode(ToolMode.Brush); else if(Input.GetKeyDown(KeyCode.E)) SetToolMode(ToolMode.Eraser); else if(Input.GetKeyDown(KeyCode.G)) SetToolMode(ToolMode.Bucket); else if(Input.GetKeyDown(KeyCode.F)) SetToolMode(ToolMode.Dropper); } // ------------------------------------------------- // CANVAS // ------------------------------------------------- if(GetModifierKey() && Input.GetKeyDown(KeyCode.N) && !GetIsEditingPixels() && _textEnteringMode == TextEnteringMode.None) { NewCanvas(); } _canvas.UpdateCanvas(); _swatch.UpdateSwatch(); _palette.UpdatePalette(); _framePreview.UpdateFramePreview(); _patternViewer.UpdatePatternViewer(); // ------------------------------------------------- // COPYING FRAMES // ------------------------------------------------- if(GetModifierKey() && Input.GetKeyDown(KeyCode.C) && !GetIsEditingPixels()) { _canvas.GetPixels(CurrentFrame).CopyTo(_copiedPixels, 0); _canvas.DirtyPixels = true; PlayCopyEffect(); } // ------------------------------------------------- // PASTING FRAMES // ------------------------------------------------- if(GetModifierKey() && Input.GetKeyDown(KeyCode.V) && !GetIsEditingPixels()) { PlayPasteEffect(); } // ------------------------------------------------- // SAVING DATA // ------------------------------------------------- if(GetModifierKey() && Input.GetKeyDown(KeyCode.S)) { ClipboardHelper.clipBoard = GetAnimData(); Debug.Log("clipboard: " + ClipboardHelper.clipBoard); ShowConsoleText(ClipboardHelper.clipBoard); } // ------------------------------------------------- // CONSOLE TEXT // ------------------------------------------------- if(_isShowingConsoleText && (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1))) { _consoleTextWrap.SetText(""); _isShowingConsoleText = false; } // ------------------------------------------------- // TEXT INPUT // ------------------------------------------------- if(_textEnteringMode == TextEnteringMode.None) { if(Input.GetKeyDown(KeyCode.Return)) { _textEnteringMode = TextEnteringMode.CurrentFrameTime; _firstChar = true; } } else { HandleInputString(Input.inputString); // ------------------------------------------------------------------------------------- // ENTERING ANIM NAME // ------------------------------------------------------------------------------------- if(_textEnteringMode == TextEnteringMode.AnimName) { if(Input.GetKeyDown(KeyCode.Return)) { if(_animNameTempString != "") { AddNewCommand(new SetAnimNameCommand(_animNameTempString)); _textEnteringMode = TextEnteringMode.None; } } else if(Input.GetKeyDown(KeyCode.Tab)) { if(GetModifierKey()) { // edit frame time _textEnteringMode = TextEnteringMode.CurrentFrameTime; } else { // edit dimensions _textEnteringMode = TextEnteringMode.PixelDimensions; } _animNameTempString = _animName; _firstChar = true; } } // ------------------------------------------------------------------------------------- // ENTERING PIXEL DIMENSTIONS // ------------------------------------------------------------------------------------- else if(_textEnteringMode == TextEnteringMode.PixelDimensions) { if(Input.GetKeyDown(KeyCode.Return)) { string[] vals = _pixelDimensionsString.Split(','); if(vals.Length == 2) { int pw = 0; int.TryParse(vals[0], out pw); int ph = 0; int.TryParse(vals[1], out ph); if((pw != 0 && ph != 0) && !(pw == _canvas.pixelWidth && ph == _canvas.pixelHeight) && (pw <= MAX_CANVAS_WIDTH && ph <= MAX_CANVAS_HEIGHT)) { _canvas.pixelWidth = pw; _canvas.pixelHeight = ph; NewCanvas(); } _pixelDimensionsString = _canvas.pixelWidth.ToString() + "," + _canvas.pixelHeight.ToString(); _textEnteringMode = TextEnteringMode.None; } } else if(Input.GetKeyDown(KeyCode.Tab)) { if(GetModifierKey()) { // edit anim name _textEnteringMode = TextEnteringMode.AnimName; } else { // edit hitbox _textEnteringMode = TextEnteringMode.Hitbox; } _pixelDimensionsString = _canvas.pixelWidth.ToString() + "," + _canvas.pixelHeight.ToString(); _firstChar = true; } } // ------------------------------------------------------------------------------------- // ENTERING HITBOX // ------------------------------------------------------------------------------------- else if(_textEnteringMode == TextEnteringMode.Hitbox) { if(Input.GetKeyDown(KeyCode.Return)) { string[] vals = _hitboxString.Split(','); if(vals.Length == 4) { int left = -1; int.TryParse(vals[0], out left); int bottom = -1; int.TryParse(vals[1], out bottom); int width = -1; int.TryParse(vals[2], out width); int height = -1; int.TryParse(vals[3], out height); if(left >= 0 && bottom >= 0 && width > 0 && height > 0 && width <= _canvas.pixelWidth && height <= _canvas.pixelHeight && left + width <= _canvas.pixelWidth && bottom + height <= _canvas.pixelHeight) { _hitbox = new PixelRect(left, bottom, width, height); _canvas.RefreshHitbox(); } RefreshHitboxString(); _textEnteringMode = TextEnteringMode.None; } } else if(Input.GetKeyDown(KeyCode.Tab)) { if(GetModifierKey()) { // edit dimensions _textEnteringMode = TextEnteringMode.PixelDimensions; } else { // edit frame time _textEnteringMode = TextEnteringMode.CurrentFrameTime; } RefreshHitboxString(); _firstChar = true; } } // ------------------------------------------------------------------------------------- // ENTERING CURRENT FRAME TIME // ------------------------------------------------------------------------------------- else if(_textEnteringMode == TextEnteringMode.CurrentFrameTime) { if(Input.GetKeyDown(KeyCode.Return)) { float time = 0.0f; bool valid = float.TryParse(_currentFrameTimeString, out time); if(valid && time > 0.0f) { AddNewCommand(new SetCurrentFrameTimeCommand(time)); _textEnteringMode = TextEnteringMode.None; } else { _currentFrameTimeString = _framePreview.GetCurrentFrameTime().ToString(); _textEnteringMode = TextEnteringMode.None; } } else if(Input.GetKeyDown(KeyCode.Tab)) { if(GetModifierKey()) { // edit hitbox _textEnteringMode = TextEnteringMode.Hitbox; } else { // edit anim name _textEnteringMode = TextEnteringMode.AnimName; } _currentFrameTimeString = _framePreview.GetCurrentFrameTime().ToString(); _firstChar = true; } } } } void HandleInputString(string inputString) { if(_textEnteringMode == TextEnteringMode.AnimName) { foreach (char c in Input.inputString) { if(c == "\b"[0]) { if(_firstChar) { _animNameTempString = ""; _firstChar = false; } else if(_animNameTempString.Length != 0) { _animNameTempString = _animNameTempString.Substring(0, _animNameTempString.Length - 1); } } else if(c != "\n"[0] && c != "\r"[0] && c != "\t"[0]) { if(_firstChar) { _animNameTempString = ""; _firstChar = false; } if(_animNameTempString.Length < 16) _animNameTempString += c; } } } else if(_textEnteringMode == TextEnteringMode.PixelDimensions) { foreach (char c in Input.inputString) { if(c == "\b"[0]) { if(_firstChar) { _pixelDimensionsString = ""; _firstChar = false; } else if(_pixelDimensionsString.Length != 0) { _pixelDimensionsString = _pixelDimensionsString.Substring(0, _pixelDimensionsString.Length - 1); } } else if(c != "\n"[0] && c != "\r"[0] && c != "\t"[0]) { if(_firstChar) { _pixelDimensionsString = ""; _firstChar = false; } if(_pixelDimensionsString.Length < 16) _pixelDimensionsString += c; } } } else if(_textEnteringMode == TextEnteringMode.Hitbox) { foreach (char c in Input.inputString) { if(c == "\b"[0]) { if(_firstChar) { _hitboxString = ""; _firstChar = false; } else if(_hitboxString.Length != 0) { _hitboxString = _hitboxString.Substring(0, _hitboxString.Length - 1); } } else if(c != "\n"[0] && c != "\r"[0] && c != "\t"[0]) { if(_firstChar) { _hitboxString = ""; _firstChar = false; } if(_hitboxString.Length < 24) _hitboxString += c; } } } else if(_textEnteringMode == TextEnteringMode.CurrentFrameTime) { foreach (char c in Input.inputString) { if(c == "\b"[0]) { if(_firstChar) { _currentFrameTimeString = ""; _firstChar = false; } else if(_currentFrameTimeString.Length != 0) { _currentFrameTimeString = _currentFrameTimeString.Substring(0, _currentFrameTimeString.Length - 1); } } else if(c != "\n"[0] && c != "\r"[0] && c != "\t"[0]) { if(_firstChar) { _currentFrameTimeString = ""; _firstChar = false; } if(_currentFrameTimeString.Length < 16) _currentFrameTimeString += c; } } } } void OnGUI() { float SPACING = 20; GUILayout.BeginHorizontal(); GUILayout.Space(4); GUILayout.Label((_textEnteringMode == TextEnteringMode.AnimName) ? "\"" + _animNameTempString + "\"" : "\"" + _animName + "\"", (_textEnteringMode == TextEnteringMode.AnimName) ? _textStyleFocused : _textStyle); GUILayout.Space(SPACING); GUILayout.Label("SIZE: " + _pixelDimensionsString, (_textEnteringMode == TextEnteringMode.PixelDimensions) ? _textStyleFocused : _textStyle); GUILayout.Space(SPACING); GUILayout.Label("HITBOX: " + _hitboxString, (_textEnteringMode == TextEnteringMode.Hitbox) ? _textStyleFocused : (_showingHitbox) ? _textStyleRed : _textStyle); GUILayout.Space(SPACING * 5); GUILayout.Label("TIME: " + _currentFrameTimeString + ((_textEnteringMode == TextEnteringMode.CurrentFrameTime) ? "" : "s"), (_textEnteringMode == TextEnteringMode.CurrentFrameTime) ? _textStyleFocused : _textStyle); GUILayout.Space(SPACING * 3); GUILayout.Label(_loopTypeString, _textStyle); GUILayout.Space(SPACING * 3); GUILayout.Label(_onionSkinString, _textStyle); GUILayout.Space(SPACING * 3); GUILayout.Label(_mirroringString, _textStyle); GUILayout.EndHorizontal(); if(Input.GetKey(KeyCode.T)) { Vector2 pos = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y); // gotta flip the y-position; float width = _textStyleFocused.CalcSize(new GUIContent(_gridIndexString)).x; GUI.TextField(new Rect(pos.x - 2, pos.y - 26, width, 20), _gridIndexString, _textStyleFocused); } if(_textEnteringMode == TextEnteringMode.LoadAnimation) { GUI.SetNextControlName("LoadAnim"); float width = _textStyleFocused.CalcSize(new GUIContent(_loadAnimString)).x; _loadAnimString = GUI.TextField(new Rect(30, 30, width, 20), _loadAnimString, _textStyleFocused); GUI.FocusControl("LoadAnim"); if(Event.current.keyCode == KeyCode.Tab) { _textEnteringMode = TextEnteringMode.None; } else if(Event.current.keyCode == KeyCode.Return) { if(_loadAnimString.Length > 0) LoadAnimationString(_loadAnimString); _textEnteringMode = TextEnteringMode.None; } } else if(_textEnteringMode == TextEnteringMode.PaletteColor) { GUI.SetNextControlName("PaletteColor"); float width = _textStyleFocused.CalcSize(new GUIContent(_paletteColorString)).x; _paletteColorString = _paletteColorString.Replace(System.Environment.NewLine, "*"); _paletteColorString = _paletteColorString.Replace(" ", string.Empty); _paletteColorString = _paletteColorString.Replace("\t", string.Empty); _paletteColorString = GUI.TextField(new Rect(_paletteInputScreenPosition.x - 2, _paletteInputScreenPosition.y - 26, width, 20), _paletteColorString, _textStyleFocused); GUI.FocusControl("PaletteColor"); if(Event.current.keyCode == KeyCode.Tab) { _textEnteringMode = TextEnteringMode.None; } else if(Event.current.keyCode == KeyCode.Return) { if(_paletteColorString == "x all" || _paletteColorString == "xall") { _palette.ClearAllColors(); _textEnteringMode = TextEnteringMode.None; return; } else if(_paletteColorString == "x") { AddNewCommand(new DeletePaletteColorCommand(_palette.PaletteColorEditIndex)); _palette.RefreshPaletteTextureColors(); _textEnteringMode = TextEnteringMode.None; return; } bool firstColor = true; bool replaceAllInstances = false; if(_paletteColorString.Length > 0 && _paletteColorString[0] == '=') { _paletteColorString = _paletteColorString.Substring(1); replaceAllInstances = true; } List<Color32> colorsToAdd = new List<Color32>(); string[] colors = _paletteColorString.Split('*'); for(int i = 0; i < colors.Length; i++) { string[] vals = colors[i].Split(','); if(vals.Length == 3 || vals.Length == 4) { byte r = 0; bool rSet = byte.TryParse(vals[0], out r); byte g = 0; bool gSet = byte.TryParse(vals[1], out g); byte b = 0; bool bSet = byte.TryParse(vals[2], out b); byte a = 0; bool aSet = false; if(vals.Length == 4) aSet = byte.TryParse(vals[3], out a); if(vals.Length == 3 && rSet && gSet && bSet) colorsToAdd.Add(new Color32(r, g, b, 255)); else if(vals.Length == 4 && rSet && gSet && bSet && aSet) colorsToAdd.Add(new Color32(r, g, b, a)); } } int currentIndex = _palette.PaletteColorEditIndex; foreach(Color32 color in colorsToAdd) { if(currentIndex > _palette.GetNumPaletteColors() - 1) break; if(firstColor) { // set swatch to the new color SetCurrentColor(color); firstColor = false; } if(replaceAllInstances) { Color32 oldColor = _palette.GetColor(currentIndex); AddNewCommand(new ReplaceColorCommand(oldColor, color)); replaceAllInstances = false; } AddNewCommand(new SetPaletteColorCommand(color, currentIndex)); currentIndex++; } _palette.RefreshPaletteTextureColors(); _textEnteringMode = TextEnteringMode.None; } } } void RefreshHitboxString() { _hitboxString = _hitbox.left.ToString() + "," + _hitbox.bottom.ToString() + "," + _hitbox.width + "," + _hitbox.height; } public void SetCurrentColor(Color color) { SetCurrentColor((Color32)color); } public void SetCurrentColor(Color32 color) { _swatch.SetColor(color); } string GetAnimData() { string str = ""; // NAME str += "*" + ((_animName == "" || _animName == "...") ? "NAME" : _animName) + "*"; // ANIM SIZE str += "!" + _canvas.pixelWidth.ToString() + "," + _canvas.pixelHeight.ToString() + "!"; // HITBOX RefreshHitboxString(); str += "<" + _hitboxString + ">"; // FRAMES for(int i = 0; i < _framePreview.GetNumFrames(); i++) str += GetFrameData(i); // LOOPS str += "&" + ((int)_framePreview.LoopMode).ToString() + "&"; return str; } string GetFrameData(int frameNumber) { Color32[] currentFramePixels = _canvas.GetPixels(frameNumber); // figure out if we should use 'differences from last frame' mode or not bool differencesMode = false; if(frameNumber > 0) { Color32[] lastFramePixels = _canvas.GetPixels(frameNumber - 1); int numSamePixels = 0; for(int x = 0; x < _canvas.pixelWidth; x++) { for(int y = 0; y < _canvas.pixelHeight; y++) { int index = y * _canvas.pixelWidth + x; if(currentFramePixels[index].a > 0 && currentFramePixels[index].Equals(lastFramePixels[index])) numSamePixels++; } } int numTotalPixels = _canvas.pixelWidth * _canvas.pixelHeight; if(numSamePixels > (int)(numTotalPixels / 2)) differencesMode = true; } // START FRAME string str = "{"; if(differencesMode) str += "^"; else str += "-"; // COLOR AND PIXELS Dictionary<Color32, List<PixelPoint>> pixels = new Dictionary<Color32, List<PixelPoint>>(); for(int x = 0; x < _canvas.pixelWidth; x++) { for(int y = 0; y < _canvas.pixelHeight; y++) { int index = y * _canvas.pixelWidth + x; if(differencesMode) { Color32[] lastFramePixels = _canvas.GetPixels(frameNumber - 1); if(!currentFramePixels[index].Equals(lastFramePixels[index])) { Color32 color = currentFramePixels[index]; PixelPoint pixelPoint = new PixelPoint(x, y); if(pixels.ContainsKey(color)) pixels[color].Add(pixelPoint); else pixels[color] = new List<PixelPoint>() { pixelPoint }; } } else { if(_canvas.GetPixelExists(frameNumber, index)) { Color32 color = currentFramePixels[index]; PixelPoint pixelPoint = new PixelPoint(x, y); if(pixels.ContainsKey(color)) pixels[color].Add(pixelPoint); else pixels[color] = new List<PixelPoint>() { pixelPoint }; } } } } foreach(KeyValuePair<Color32, List<PixelPoint>> pair in pixels) { List<PixelPoint> pixelPoints = pair.Value; if(pixelPoints.Count > 0) { Dictionary<int, List<int>> coordinates = new Dictionary<int, List<int>>(); // y-value is the key, and has list of x-values (for that y) for the value foreach(PixelPoint point in pixelPoints) { if(coordinates.ContainsKey(point.y)) coordinates[point.y].Add(point.x); else coordinates[point.y] = new List<int>() { point.x }; } Color32 col = pair.Key; if(col.a == 0) // a blank pixel { str += "[]"; } else if(col.r == col.g && col.r == col.b) // a shade of grey { if(col.a == 255) str += "[" + col.r.ToString() + "]"; // solid grey else str += "[" + col.r.ToString() + "," + col.a.ToString() + "]"; } else if(col.a == 255) // a solid color { str += "[" + col.r.ToString() + "," + col.g.ToString() + "," + col.b.ToString() + "]"; } else // a transparent color { str += "[" + col.r.ToString() + "," + col.g.ToString() + "," + col.b.ToString() + "," + col.a.ToString() + "]"; } foreach(KeyValuePair<int, List<int>> coordPair in coordinates) { int yPos = coordPair.Key; List<int> xPositions = coordPair.Value; str += "(" + yPos.ToString() + "-"; bool first = true; foreach(int xPos in xPositions) { if(first) first = false; else str += ","; str += xPos.ToString(); } str += ")"; } } } // FRAME TIME str += "#" + _framePreview.GetFrameTime(frameNumber).ToString() + "#"; // END FRAME str += "}"; return str; } void LateUpdate() { if(!_initialized) return; if(_canvas.DirtyPixels) { // ------------------------------------------------------------ // UPDATE CANVAS // ------------------------------------------------------------ _canvas.UpdateTexture(); // ------------------------------------------------------------ // UPDATE FRAME PREVIEWS // ------------------------------------------------------------ for(int i = 0; i < _framePreview.GetNumFrames(); i++) _framePreview.SetPixels(_canvas.GetPixels(i), i); // ------------------------------------------------------------ // UPDATE PATTERN VIEWER // ------------------------------------------------------------ _patternViewer.RefreshPatternViewer(); } } // void HandleSwatchColorChanging() // { // float COLOR_CHANGE_AMOUNT = 0.99f; // // if(GetModifierKey()) // { // if(Input.GetAxis("Mouse ScrollWheel") < 0) // { // Color color = (Color)_currentColor; // Color newColor = new Color(color.r * COLOR_CHANGE_AMOUNT, color.g * COLOR_CHANGE_AMOUNT, color.b * COLOR_CHANGE_AMOUNT); // SetCurrentColor((Color32)newColor); // } // else if(Input.GetAxis("Mouse ScrollWheel") > 0) // { // Color color = (Color)_currentColor; // Color newColor = new Color(color.r * (1.0f - COLOR_CHANGE_AMOUNT), color.g * (1.0f - COLOR_CHANGE_AMOUNT), color.b * (1.0f - COLOR_CHANGE_AMOUNT)); // SetCurrentColor((Color32)newColor); // } // } // } public GameObject CreatePlane(string planeName, Transform parentTransform, float localDepth) { GameObject plane = new GameObject(planeName); plane.AddComponent(typeof(MeshRenderer)); plane.AddComponent(typeof(MeshFilter)); plane.transform.parent = parentTransform; plane.transform.localPosition = new Vector3(0, 0, localDepth); Mesh mesh = new Mesh(); mesh.vertices = new Vector3[] { new Vector3(-1, 1, 0), new Vector3(1, 1, 0), new Vector3(-1, -1, 0), new Vector3(1, -1, 0) }; mesh.triangles = new int[] {0, 1, 2, 1, 3, 2}; mesh.uv = new Vector2[] { new Vector2(0, 1), new Vector2(1, 1), new Vector2(0, 0), new Vector2(1, 0) }; plane.GetComponent<MeshFilter>().mesh = mesh; plane.AddComponent(typeof(MeshCollider)); return plane; } public void SetToolMode(ToolMode toolMode) { if(_toolMode == toolMode) return; _toolMode = toolMode; switch(_toolMode) { case ToolMode.Brush: Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto); // Cursor.SetCursor(cursorBrush, Vector2.zero, CursorMode.Auto); break; case ToolMode.Eraser: Cursor.SetCursor(cursorEraser, Vector2.zero, CursorMode.Auto); break; case ToolMode.Dropper: Cursor.SetCursor(cursorDropper, Vector2.zero, CursorMode.Auto); break; case ToolMode.Bucket: Cursor.SetCursor(cursorPaint, Vector2.zero, CursorMode.Auto); break; } } void OnApplicationQuit() { _palette.OnQuit(); PlayerPrefs.SetInt("screenWidth", Screen.width); PlayerPrefs.SetInt("screenHeight", Screen.height); PlayerPrefs.SetString("animData", GetAnimData()); PlayerPrefs.Save(); } // ** name // !! size // {} frame // [] color // () pixel // <> hitbox // ## time // && loops void LoadAnimationString(string animString) { AnimationData animData = ParseAnimationString(animString); if(animData == null) return; _animName = animData.name; _framePreview.SetLoopMode(animData.loopMode); _canvas.pixelWidth = animData.animSize.x; _canvas.pixelHeight = animData.animSize.y; NewCanvas(); int frameNumber = 0; foreach(FrameData frameData in animData.frames) { // create a new frame if(frameNumber >= _framePreview.GetNumFrames()) _framePreview.AddNewBlankFrame(); _framePreview.SetFrameTime(frameData.animTime, frameNumber); foreach(PixelData pixelData in frameData.pixels) _canvas.SetPixelForFrame(frameNumber, pixelData.position.x, pixelData.position.y, pixelData.color); frameNumber++; } // NewCanvas() resets hitbox to anim size so gotta set it again _hitbox = animData.hitbox; RefreshHitboxString(); _canvas.DirtyPixels = true; } AnimationData ParseAnimationString(string animString) { Stack<ParseAnimState> animStates = new Stack<ParseAnimState>(); string currentString = ""; // ANIMATION DATA string name = ""; List<FrameData> frames = new List<FrameData>(); LoopMode loopMode = LoopMode.Loops; // CURRENT FRAME DATA Color32 currentColor = new Color32(0, 0, 0, 0); List<PixelData> currentPixels = new List<PixelData>(); List<PixelData> previousFramePixels = new List<PixelData>(); PixelPoint animSize = new PixelPoint(0, 0); PixelRect hitbox = new PixelRect(0, 0, 0, 0); float currentAnimTime = 0.0f; int currentPixelYPos = 0; bool differencesMode = false; foreach(char c in animString) { if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.DifferencesMode) { if(c == '^') differencesMode = true; else differencesMode = false; animStates.Pop(); animStates.Push(ParseAnimState.Frame); } else { if(c == '*') { if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.Name) { name = currentString; currentString = ""; animStates.Pop(); } else { animStates.Push(ParseAnimState.Name); currentString = ""; } } else if(c == '!') { if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.Size) { // parse current string for animation rect and save it string[] vals = currentString.Split(','); if(vals.Length == 2) { int xSize = 0; int ySize = 0; if(!(int.TryParse(vals[0], out xSize) && int.TryParse(vals[1], out ySize))) { ShowConsoleText(currentString + " is not properly formatted anim size data!"); return null; } animSize = new PixelPoint(xSize, ySize); } else { ShowConsoleText(currentString + " is not properly formatted anim size data!"); return null; } currentString = ""; animStates.Pop(); } else { animStates.Push(ParseAnimState.Size); } } else if(c == '<') { animStates.Push(ParseAnimState.Hitbox); } else if(c == '>') { if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.Hitbox) { // parse current string for hitbox info and save it string[] vals = currentString.Split(','); if(vals.Length == 4) { int left = 0; int bottom = 0; int width = 0; int height = 0; if(!(int.TryParse(vals[0], out left) && int.TryParse(vals[1], out bottom) && int.TryParse(vals[2], out width) && int.TryParse(vals[3], out height))) { ShowConsoleText(currentString + " is not properly formatted hitbox data!"); return null; } hitbox = new PixelRect(left, bottom, width, height); } else { ShowConsoleText(currentString + " is not properly formatted hitbox data!"); return null; } currentString = ""; animStates.Pop(); } } else if(c == '{') { animStates.Push(ParseAnimState.DifferencesMode); } else if(c == '}') { if(differencesMode) { // currentPixels holds pixels that are DIFFERENT than the previous frame List<PixelData> pixels = new List<PixelData>(); foreach(PixelData prevPixelData in previousFramePixels) { // only add the previous frame pixels that AREN'T being overriden by the new frame data bool allowPixel = true; foreach(PixelData pixel in currentPixels) { if(pixel.position == prevPixelData.position) { allowPixel = false; break; } } if(allowPixel) pixels.Add(new PixelData(prevPixelData.position, prevPixelData.color)); } // add in the new, different pixels foreach(PixelData newPixel in currentPixels) { pixels.Add(newPixel); } currentPixels.Clear(); frames.Add(new FrameData(pixels, currentAnimTime)); previousFramePixels.Clear(); previousFramePixels.AddRange(pixels); } else { // save current frame data List<PixelData> pixels = new List<PixelData>(); pixels.AddRange(currentPixels); currentPixels.Clear(); frames.Add(new FrameData(pixels, currentAnimTime)); previousFramePixels.Clear(); previousFramePixels.AddRange(pixels); } if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.Frame) animStates.Pop(); } else if(c == '[') { animStates.Push(ParseAnimState.PixelColor); } else if(c == ']') { if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.PixelColor) { // parse current string for pixel color if(currentString.Length == 0) { currentColor = new Color32(0, 0, 0, 0); } else { string[] vals = currentString.Split(','); if(vals.Length == 1) { byte grey = 0; if(!byte.TryParse(vals[0], out grey)) { ShowConsoleText(currentString + " is not properly formatted color data!"); return null; } currentColor = new Color32(grey, grey, grey, 255); } else if(vals.Length == 2) { byte grey = 0; byte opacity = 0; if(!(byte.TryParse(vals[0], out grey) && byte.TryParse(vals[1], out opacity))) { ShowConsoleText(currentString + " is not properly formatted color data!"); return null; } currentColor = new Color32(grey, grey, grey, opacity); } else if(vals.Length == 3) { byte red = 0; byte green = 0; byte blue = 0; if(!(byte.TryParse(vals[0], out red) && byte.TryParse(vals[1], out green) && byte.TryParse(vals[2], out blue))) { ShowConsoleText(currentString + " is not properly formatted color data!"); return null; } currentColor = new Color32(red, green, blue, 255); } else if(vals.Length == 4) { byte red = 0; byte green = 0; byte blue = 0; byte opacity = 0; if(!(byte.TryParse(vals[0], out red) && byte.TryParse(vals[1], out green) && byte.TryParse(vals[2], out blue) && byte.TryParse(vals[3], out opacity))) { ShowConsoleText(currentString + " is not properly formatted color data!"); return null; } currentColor = new Color32(red, green, blue, opacity); } else { ShowConsoleText(currentString + " is not properly formatted color data!"); } } currentString = ""; animStates.Pop(); } } else if(c == '(') { animStates.Push(ParseAnimState.PixelYPos); } else if(c == '-') { if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.PixelYPos) { if(!int.TryParse(currentString, out currentPixelYPos)) { ShowConsoleText(currentString + " is not a properly formatted y-position!"); return null; } currentString = ""; animStates.Pop(); animStates.Push(ParseAnimState.PixelXPos); } } else if(c == ')') { if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.PixelXPos) { // parse current string for x pixel positions (for the current pixel y pos) // add a pixel of current color to a list string[] vals = currentString.Split(','); for(int i = 0; i < vals.Length; i++) { int xPos = 0; if(!int.TryParse(vals[i], out xPos)) { ShowConsoleText(currentString + " is not a properly formatted x-position!"); return null; } currentPixels.Add(new PixelData(new PixelPoint(xPos, currentPixelYPos), currentColor)); } animStates.Pop(); } currentString = ""; } else if(c == '#') { if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.AnimTime) { // parse current string for animation time and save it if(!float.TryParse(currentString, out currentAnimTime)) { ShowConsoleText(currentString + " is not a properly formatted frame time!"); return null; } currentString = ""; animStates.Pop(); } else { animStates.Push(ParseAnimState.AnimTime); } } else if(c == '&') { if(animStates.Count > 0 && animStates.Peek() == ParseAnimState.Loops) { // parse current string for loop mode and save it int loopModeInt = 0; if(!int.TryParse(currentString, out loopModeInt)) { ShowConsoleText(currentString + " is not a properly formatted loop mode!"); return null; } loopMode = (LoopMode)loopModeInt; currentString = ""; animStates.Pop(); } else { animStates.Push(ParseAnimState.Loops); } } else { currentString += c; } } } AnimationData animData = new AnimationData(name, frames, animSize, hitbox, loopMode); return animData; } } public enum ParseAnimState { Name, Size, Hitbox, Frame, DifferencesMode, PixelColor, PixelYPos, PixelXPos, AnimTime, Loops }; public class AnimationData { public string name; public List<FrameData> frames; public PixelPoint animSize; public PixelRect hitbox; public LoopMode loopMode; public AnimationData(string name, List<FrameData> frames, PixelPoint animSize, PixelRect hitbox, LoopMode loopMode) { this.name = name; this.frames = frames; this.animSize = animSize; this.hitbox = hitbox; this.loopMode = loopMode; } } public struct FrameData { public List<PixelData> pixels; public float animTime; public FrameData(List<PixelData> pixels, float animTime = 0.0f) { this.pixels = pixels; this.animTime = animTime; } } public struct PixelData { public PixelPoint position; public Color32 color; public PixelData(PixelPoint position, Color32 color) { this.position = position; this.color = color; } }
using System; using System.Globalization; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Threading; using jk.plaveninycz; using jk.plaveninycz.DataSources; using jk.plaveninycz.BO; using jk.plaveninycz.Bll; public partial class station_list : System.Web.UI.Page { protected override void InitializeCulture() { //Response.Cache.SetNoStore(); string lang = "en"; string cult = "en-US"; VariableEnum varEnum = VariableEnum.Stage; //VariableInfo varInfo = new VariableInfo(varEnum); Variable var = VariableManager.GetItemByEnum(varEnum); if ( Context.Request.QueryString["lang"] != null ) { lang = Context.Request.QueryString["lang"]; switch ( lang ) { case "cz": cult = "cs-CZ"; break; default: cult = "en-US"; break; } } Thread.CurrentThread.CurrentCulture = new CultureInfo(cult); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cult); // this code is invoked, when the form is posted back. // (after pressing the "OK" button) // The page is then redirected to a different URL if ( Context.Request.Form.Count > 0 ) { //set culture according to the language of request string requestPath = Context.Request.UrlReferrer.AbsolutePath; if ( requestPath.IndexOf("/cz/") >= 0 ) { cult = "cs-CZ"; } else { cult = "en-US"; } Thread.CurrentThread.CurrentCulture = new CultureInfo(cult); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cult); //string ctlHeading = @"ctl00$cph_main$"; string varName = Context.Request.Form[@"ctl00$cph_main$select_station_type"]; string orderBy = Context.Request.Form[@"ctl00$cph_main$select_order"]; if ( varName == "discharge" ) varName = "flow"; //special case.. var = VariableManager.GetItemByShortName(varName); string varUrl = var.Url; int orderId = Convert.ToInt32(orderBy) + 1; string newUrl = String.Format(@"~/{0}/{1}/{2}/", var.UrlLang, Resources.global.Url_Stations, varUrl); if ( orderId > 1 ) { newUrl = String.Format(@"{0}o{1}.aspx", newUrl, orderId); } // redirect the browser to the new page! Context.Response.Redirect(newUrl); } } protected void Page_Load(object sender, EventArgs e) { // local variables VariableEnum varEnum = VariableEnum.Stage; Variable varInfo = VariableManager.GetItemByEnum(varEnum); string cultureStr = Thread.CurrentThread.CurrentCulture.ToString(); int order = 1; DateTime t = DateTime.Now.Date; if ( !( Page.IsPostBack ) ) { // resolve query string parameters this.resolveVariable(varInfo); varEnum = varInfo.VarEnum; order = this.resolveOrder(); // initialize control values and set page metadata this.initialize(varEnum); this.setMetaData(varEnum); // set value of select_station_type control this.selectVariable(varInfo); this.selectOrder(order); // create the table of stations! this.createStationTable(varInfo, order); // set the correct page title! Master.PageTitle = Resources.global.Link_List_Of_Stations + " - " + varInfo.Name; // set right url of the language hyperlink Master.LanguageUrl = CreateLanguageLink(varInfo); } } /// <summary> /// generates a correct URL to be used in the 'language' link /// </summary> /// <param name="varInfo"></param> /// <returns></returns> private string CreateLanguageLink(Variable varInfo) { string LangPath = Context.Request.AppRelativeCurrentExecutionFilePath.ToLower(); string LangPathStart; string lang = Thread.CurrentThread.CurrentCulture.ToString(); string tempLang = lang; //the different culture string(to be changed) //resolve language of the link switch ( lang ) { case "en-US": tempLang = "cs-CZ"; break; case "cs-CZ": tempLang = "en-US"; break; default: tempLang = "cs-CZ"; break; } //temporarily change the culture CultureInfo pageCulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = new CultureInfo(tempLang); Thread.CurrentThread.CurrentUICulture = new CultureInfo(tempLang); VariableManager.ChangeCulture(varInfo, Thread.CurrentThread.CurrentUICulture); LangPathStart = "/" + varInfo.UrlLang + "/" + Resources.global.Url_Stations + "/" + varInfo.Url + "/"; //switch back to original culture Thread.CurrentThread.CurrentCulture = pageCulture; Thread.CurrentThread.CurrentUICulture = pageCulture; if ( LangPath.EndsWith("/default.aspx") ) { LangPath = LangPath.Remove(LangPath.IndexOf("/default.aspx")); } //string LangPath2 = System.Text.RegularExpressions.Regex.Replace //(LangPath, "(/[czen]{2}/[a-z_-]+/[a-z_-]*)", LangPathStart, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if ( LangPath.EndsWith(".aspx")) { LangPathStart = LangPathStart + LangPath.Substring(LangPath.LastIndexOf("/")); } if ( !( LangPathStart.EndsWith(".aspx") || LangPathStart.EndsWith("/") ) ) { LangPathStart = LangPathStart + "/"; } return "~/" + LangPathStart; } // sets initial values to dropdownlists in the page form private void initialize(VariableEnum varEnum) { string cultStr = Thread.CurrentThread.CurrentCulture.ToString(); SetNavigationMenu(); string[] variableList; variableList = new string[4] { Resources.global.Var_Snow, Resources.global.Var_Precip, Resources.global.Var_Stage, Resources.global.Var_Discharge }; int orderListCount = 4; Dictionary<int,string> orderList = new Dictionary<int,string>(); for ( int i = 0; i < orderListCount; ++i ) { // special case: recognize river/territory if ( i == 1 & ( varEnum == VariableEnum.Stage | varEnum == VariableEnum.Discharge ) ) { orderList.Add(i, GetLocalResourceObject("StationOrderType_River").ToString()); } else { orderList.Add(i, GetLocalResourceObject("StationOrderType_" + ( i + 1 ).ToString()).ToString()); } } select_station_type.DataSource = variableList; select_station_type.DataBind(); select_order.DataSource = orderList; select_order.DataTextField = "Value"; select_order.DataValueField = "Key"; select_order.DataBind(); if ( varEnum == VariableEnum.Stage | varEnum == VariableEnum.Discharge ) { th_location.Text = GetLocalResourceObject("LocationHeader2.Text").ToString(); } } // set the active (current) menu item in master page // also create a correct language url link private void SetNavigationMenu() { Master.ActiveMenuItem = "link_stations"; //Master.LanguageUrl = GetLocalResourceObject("LanguageLink.NavigateUrl").ToString(); } private void resolveVariable(Variable varInfo) { string varName; if ( Request.QueryString["var"] != null ) { varName = Request.QueryString["var"]; varInfo = VariableManager.GetItemByName(varName); } } // returns the index indicating the order of // displayed stations private int resolveOrder() { int order = 1; if ( Request.QueryString["order"] != null ) { order = Convert.ToInt32(Request.QueryString["order"]); } return order; } // selects the variable in select_station_type DropDownList // also sets correct variable to page title, heading and graph // hyperlink private void selectVariable(Variable varInfo) { VariableEnum varEnum = varInfo.VarEnum; // first, set the table caption label string varName = varInfo.Name; LblCaption2.Text = varName; // second, set the main page heading lbl_h1.Text = GetLocalResourceObject("PageTitle1.Text").ToString() + ": " + varName; // third, set correct variable for the graph hyperlink Master.GraphUrl = Resources.global.Url_Graphs + "/" + varInfo.Url + "/"; //link_graphs.NavigateUrl = Resources.global.Url_Graphs + "/" + varInfo.Url + "/"; // third, select the right index in the variable listbox int index = 0; switch ( varEnum ) { case VariableEnum.Snow: index = 0; break; case VariableEnum.Precip: index = 1; break; case VariableEnum.Stage: index = 2; break; case VariableEnum.Discharge: index = 3; break; default: break; } select_station_type.SelectedIndex = index; } // set the caption and headers of station table! //private void StationList_OnItemDataBound() // select the order in select_order DropDownList private void selectOrder(int order) { if ( order < 1 | order > 4 ) { order = 1; } select_order.SelectedIndex = order - 1; } // the main function: fill the table of stations with data! private void createStationTable(Variable varInfo, int order) { int varId = varInfo.Id; StationListDataSource.SelectParameters["variableId"].DefaultValue = varId.ToString(); StationListDataSource.SelectParameters["orderBy"].DefaultValue = order.ToString(); } // set the metadata in page header from local resource file! private void setMetaData(VariableEnum varEnum) { string varName = varEnum.ToString() + ".text"; // meta_language Master.MetaLanguage = String.Format("<meta http-equiv='content-language' content='{0}' />", Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName); // meta_description Master.MetaDescription = "<meta name='description' content='" + GetLocalResourceObject("MetaDescription_" + varName) + "' />"; // meta_keywords Master.MetaKeywords = "<meta name='keywords' content='" + GetLocalResourceObject("MetaKeywords_" + varName) + "' />"; } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Windows.Forms; using Aga.Controls.Tree; using Gallio.Icarus.Controllers.Interfaces; using Gallio.Icarus.Models; using Gallio.Icarus.Models.TestTreeNodes; using Gallio.Icarus.Services; using Gallio.Model; using Gallio.Model.Filters; using Gallio.Model.Schema; using MbUnit.Framework; using Rhino.Mocks; namespace Gallio.Icarus.Tests.Services { [TestsOn(typeof(FilterService))] public class FilterServiceTest { private ITestTreeModel testTreeModel; private FilterService filterService; [SetUp] public void SetUp() { testTreeModel = MockRepository.GenerateStub<ITestTreeModel>(); var optionsController = MockRepository.GenerateStub<IOptionsController>(); filterService = new FilterService(testTreeModel, optionsController); } [Test] public void Apply_filter_set_should_do_nothing_if_tree_model_root_is_null() { filterService.ApplyFilterSet(new FilterSet<ITestDescriptor>(new AnyFilter<ITestDescriptor>())); } [Test] public void If_applied_filter_set_is_empty_then_the_root_should_be_checked() { var testTreeNode = new TestTreeNode("root", "root") { CheckState = CheckState.Unchecked }; testTreeModel.Stub(ttm => ttm.Root).Return(testTreeNode); filterService.ApplyFilterSet(FilterSet<ITestDescriptor>.Empty); Assert.AreEqual(CheckState.Checked, testTreeNode.CheckState); } [Test] public void If_applied_filter_set_is_any_filter_then_the_root_should_be_checked() { var testTreeNode = new TestDataNode(new TestData("root", "root", "root")) { CheckState = CheckState.Unchecked }; testTreeModel.Stub(ttm => ttm.Root).Return(testTreeNode); var filterSet = new FilterSet<ITestDescriptor>(new AnyFilter<ITestDescriptor>()); filterService.ApplyFilterSet(filterSet); Assert.AreEqual(CheckState.Checked, testTreeNode.CheckState); } [Test] public void If_applied_filter_set_is_none_filter_then_the_root_should_be_unchecked() { var testTreeNode = new TestTreeNode("root", "root"); testTreeModel.Stub(ttm => ttm.Root).Return(testTreeNode); var filterSet = new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()); filterService.ApplyFilterSet(filterSet); Assert.AreEqual(CheckState.Unchecked, testTreeNode.CheckState); } [Test] public void Filter_sets_should_be_applied_appropriately() { var root = new TestDataNode(new TestData("root", "root", "root")); var test1 = new TestDataNode(new TestData("test1", "test1", "test1")); var test2 = new TestDataNode(new TestData("test2", "test2", "test2")); root.Nodes.Add(test1); root.Nodes.Add(test2); testTreeModel.Stub(ttm => ttm.Root).Return(root); var filterSet = new FilterSet<ITestDescriptor>(new OrFilter<ITestDescriptor>(new[] { new IdFilter<ITestDescriptor>(new EqualityFilter<string>("test2")) })); filterService.ApplyFilterSet(filterSet); Assert.AreEqual(CheckState.Indeterminate, root.CheckState); Assert.AreEqual(CheckState.Unchecked, test1.CheckState); Assert.AreEqual(CheckState.Checked, test2.CheckState); } [Test] public void Generated_filter_should_be_empty_if_tree_model_root_is_null() { var filterSet = filterService.GenerateFilterSetFromSelectedTests(); Assert.IsTrue(filterSet.IsEmpty); } [Test] public void Generated_filter_should_be_empty_if_tree_model_root_is_checked() { var testTreeNode = new TestTreeNode("root", "root") { CheckState = CheckState.Checked }; testTreeModel.Stub(ttm => ttm.Root).Return(testTreeNode); var filterSet = filterService.GenerateFilterSetFromSelectedTests(); Assert.IsTrue(filterSet.IsEmpty); } [Test] public void Generated_filter_should_be_none_if_tree_model_root_is_unchecked() { var root = new TestTreeNode("root", "root") { CheckState = CheckState.Unchecked }; testTreeModel.Stub(ttm => ttm.Root).Return(root); var filterSet = filterService.GenerateFilterSetFromSelectedTests(); Assert.IsInstanceOfType(typeof(NoneFilter<ITestDescriptor>), filterSet.Rules[0].Filter); } [Test] public void Generated_filter_should_be_correct_if_root_is_indeterminate_and_namespace_is_checked() { var root = new TestTreeNode("root", "root") { CheckState = CheckState.Indeterminate }; var child = new TestTreeNode("child", "child") { CheckState = CheckState.Checked }; root.Nodes.Add(child); const string @namespace = "Gallio.Icarus.Tests.Services"; child.Nodes.Add(new NamespaceNode(@namespace, @namespace) { CheckState = CheckState.Checked }); testTreeModel.Stub(ttm => ttm.Root).Return(root); var filterSet = filterService.GenerateFilterSetFromSelectedTests(); var filter = (PropertyFilter<ITestDescriptor>)filterSet.Rules[0].Filter; Assert.IsInstanceOfType(typeof(NamespaceFilter<ITestDescriptor>), filter); Assert.AreEqual(true, filter.ValueFilter.IsMatch(@namespace)); } [Test] public void Generated_filter_should_be_correct_if_root_is_indeterminate_and_test_data_is_checked() { var root = new TestTreeNode("root", "root") { CheckState = CheckState.Indeterminate }; var child = new TestTreeNode("child", "child") { CheckState = CheckState.Indeterminate }; root.Nodes.Add(child); const string id = "id"; child.Nodes.Add(new TestDataNode(new TestData(id, "name", "fullName")) { CheckState = CheckState.Checked }); child.Nodes.Add(new Node()); testTreeModel.Stub(ttm => ttm.Root).Return(root); var filterSet = filterService.GenerateFilterSetFromSelectedTests(); var filter = (PropertyFilter<ITestDescriptor>)filterSet.Rules[0].Filter; Assert.IsInstanceOfType(typeof(IdFilter<ITestDescriptor>), filter); Assert.AreEqual(true, filter.ValueFilter.IsMatch(id)); } [Test] public void Generated_filter_should_be_correct_if_root_is_indeterminate_and_metadata_is_checked() { var root = new TestTreeNode("root", "root") { CheckState = CheckState.Indeterminate }; const string category = "blahblah"; const string metadataType = MetadataKeys.Category; root.Nodes.Add(new MetadataNode(category, metadataType) { CheckState = CheckState.Checked }); testTreeModel.Stub(ttm => ttm.Root).Return(root); var filterSet = filterService.GenerateFilterSetFromSelectedTests(); var filter = (PropertyFilter<ITestDescriptor>)filterSet.Rules[0].Filter; Assert.IsInstanceOfType(typeof(MetadataFilter<ITestDescriptor>), filter); Assert.AreEqual(metadataType, filter.Key); Assert.AreEqual(true, filter.ValueFilter.IsMatch(category)); } } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green ([email protected]) * * SharpNEAT is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections; using System.Collections.Generic; using SharpNeat.Network; namespace SharpNeat.Genomes.Neat { // ENHANCEMENT: Consider switching to a SortedList[K,V] - which guarantees item sort order at all times. /// <summary> /// Represents a sorted list of ConnectionGene objects. The sorting of the items is done on request /// rather than being strictly enforced at all times (e.g. as part of adding and removing genes). This /// approach is currently more convenient for use in some of the routines that work with NEAT genomes. /// /// Because we are not using a strictly sorted list such as the generic class SortedList[K,V] a customised /// BinarySearch() method is provided for fast lookup of items if the list is known to be sorted. If the list is /// not sorted then the BinarySearch method's behaviour is undefined. This is potentially a source of bugs /// and thus this class should probably migrate to SortedList[K,V] or be modified to ensure items are sorted /// prior to a binary search. /// /// Sort order is with respect to connection gene innovation ID. /// </summary> public class ConnectionGeneList : List<ConnectionGene>, IConnectionList { static readonly ConnectionGeneComparer __connectionGeneComparer = new ConnectionGeneComparer(); #region Constructors /// <summary> /// Construct an empty list. /// </summary> public ConnectionGeneList() { } /// <summary> /// Construct an empty list with the specified capacity. /// </summary> public ConnectionGeneList(int capacity) : base(capacity) { } /// <summary> /// Copy constructor. The newly allocated list has a capacity 2 larger than copyFrom /// allowing addition mutations to occur without reallocation of memory. /// Note that a single add node mutation adds two connections and a single /// add connection mutation adds one. /// </summary> public ConnectionGeneList(ICollection<ConnectionGene> copyFrom) : base(copyFrom.Count + 2) { // ENHANCEMENT: List.Foreach() is potentially faster then a foreach loop. // http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx foreach(ConnectionGene srcGene in copyFrom) { Add(srcGene.CreateCopy()); } } #endregion #region Public Methods /// <summary> /// Inserts a ConnectionGene into its correct (sorted) location within the gene list. /// Normally connection genes can safely be assumed to have a new Innovation ID higher /// than all existing IDs, and so we can just call Add(). /// This routine handles genes with older IDs that need placing correctly. /// </summary> public void InsertIntoPosition(ConnectionGene connectionGene) { // Determine the insert idx with a linear search, starting from the end // since mostly we expect to be adding genes that belong only 1 or 2 genes // from the end at most. int idx=Count-1; for(; idx > -1; idx--) { if(this[idx].InnovationId < connectionGene.InnovationId) { // Insert idx found. break; } } Insert(idx+1, connectionGene); } /// <summary> /// Remove the connection gene with the specified innovation ID. /// </summary> public void Remove(uint innovationId) { int idx = BinarySearch(innovationId); if(idx<0) { throw new ApplicationException("Attempt to remove connection with an unknown innovationId"); } RemoveAt(idx); } /// <summary> /// Sort connection genes into ascending order by their innovation IDs. /// </summary> public void SortByInnovationId() { Sort(__connectionGeneComparer); } /// <summary> /// Obtain the index of the gene with the specified innovation ID by performing a binary search. /// Binary search is fast and can be performed so long as we know the genes are sorted by innovation ID. /// If the genes are not sorted then the behaviour of this method is undefined. /// </summary> public int BinarySearch(uint innovationId) { int lo = 0; int hi = Count-1; while (lo <= hi) { int i = (lo + hi) >> 1; // Note. we don't calculate this[i].InnovationId-innovationId because we are dealing with uint. // ENHANCEMENT: List<T>[i] invokes a bounds check on each call. Can we avoid this? if(this[i].InnovationId < innovationId) { lo = i + 1; } else if(this[i].InnovationId > innovationId) { hi = i - 1; } else { return i; } } return ~lo; } /// <summary> /// Resets the IsMutated flag on all ConnectionGenes in the list. /// </summary> public void ResetIsMutatedFlags() { int count = this.Count; for(int i=0; i<count; i++) { this[i].IsMutated = false; } } /// <summary> /// For debug purposes only. Don't call this method in normal circumstances as it is an /// expensive O(n) operation. /// </summary> public bool IsSorted() { int count = this.Count; if(0 == count) { return true; } uint prev = this[0].InnovationId; for(int i=1; i<count; i++) { if(this[i].InnovationId <= prev) { return false; } } return true; } #endregion #region IConnectionList Members INetworkConnection IConnectionList.this[int index] { get { return this[index]; } } int IConnectionList.Count { get { return this.Count; } } IEnumerator<INetworkConnection> IEnumerable<INetworkConnection>.GetEnumerator() { foreach(ConnectionGene gene in this) { yield return gene; } } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<INetworkConnection>)this).GetEnumerator(); } #endregion } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Hydra.Panes.HydraPublic File: ChartPane.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Hydra.Panes { using System; using System.Collections.Generic; using System.Windows; using Ecng.Collections; using Ecng.Common; using Ecng.Serialization; using Ecng.Xaml; using MoreLinq; using StockSharp.Algo.Candles; using StockSharp.Algo.Indicators; using StockSharp.Configuration; using StockSharp.Logging; using StockSharp.Xaml.Charting; using StockSharp.Xaml.Charting.IndicatorPainters; using StockSharp.Localization; public partial class ChartPane : IPane { private readonly SynchronizedDictionary<ChartIndicatorElement, IIndicator> _indicators = new SynchronizedDictionary<ChartIndicatorElement, IIndicator>(); private readonly CachedSynchronizedList<RefPair<IChartElement, int>> _elements = new CachedSynchronizedList<RefPair<IChartElement, int>>(); private readonly ResettableTimer _drawTimer; private ChartCandleElement _candlesElem; private ChartIndicatorElement _volumeElem; private IEnumerable<Candle> _candles; public ChartPane() { InitializeComponent(); _drawTimer = new ResettableTimer(TimeSpan.FromSeconds(2), "Chart"); _drawTimer.Elapsed += DrawTimerOnElapsed; ChartPanel.MinimumRange = 200; ChartPanel.IsInteracted = true; ChartPanel.FillIndicators(); ChartPanel.SubscribeCandleElement += OnChartPanelSubscribeCandleElement; ChartPanel.SubscribeIndicatorElement += OnChartPanelSubscribeIndicatorElement; ChartPanel.UnSubscribeElement += ChartPanelOnUnSubscribeElement; } private void OnChartPanelSubscribeCandleElement(ChartCandleElement element, CandleSeries candleSeries) { _drawTimer.Cancel(); _elements.Add(new RefPair<IChartElement, int>(element, 0)); _drawTimer.Activate(); } private void OnChartPanelSubscribeIndicatorElement(ChartIndicatorElement element, CandleSeries candleSeries, IIndicator indicator) { _drawTimer.Cancel(); _elements.Add(new RefPair<IChartElement, int>(element, 0)); _indicators.Add(element, indicator); _drawTimer.Activate(); } private void ChartPanelOnUnSubscribeElement(IChartElement element) { lock (_elements.SyncRoot) _elements.RemoveWhere(p => p.First == element); } private void DrawTimerOnElapsed(Func<bool> canProcess) { try { GuiDispatcher.GlobalDispatcher.AddAction(() => CancelButton.Visibility = Visibility.Visible); var index = 0; foreach (var batch in _candles.Batch(50)) { if (!canProcess()) break; var values = new List<RefPair<DateTimeOffset, IDictionary<IChartElement, object>>>(); foreach (var c in batch) { var candle = c; var pair = new RefPair<DateTimeOffset, IDictionary<IChartElement, object>>(candle.OpenTime, new Dictionary<IChartElement, object>()); foreach (var elemPair in _elements.Cache) { if (elemPair.Second >= index) continue; elemPair.First.DoIf<IChartElement, ChartCandleElement>(e => pair.Second.Add(e, candle)); elemPair.First.DoIf<IChartElement, ChartIndicatorElement>(e => pair.Second.Add(e, CreateIndicatorValue(e, candle))); elemPair.Second = index; } values.Add(pair); index++; } ChartPanel.Draw(values); } GuiDispatcher.GlobalDispatcher.AddAction(() => CancelButton.Visibility = Visibility.Collapsed); } catch (Exception ex) { ex.LogError(); } } private IIndicatorValue CreateIndicatorValue(ChartIndicatorElement element, Candle candle) { var indicator = _indicators.TryGetValue(element); if (indicator == null) throw new InvalidOperationException(LocalizedStrings.IndicatorNotFound.Put(element)); return indicator.Process(candle); } public void Draw(CandleSeries series, IEnumerable<Candle> candles) { if (series == null) throw new ArgumentNullException(nameof(series)); if (candles == null) throw new ArgumentNullException(nameof(candles)); Series = series; _candles = candles; //_candlesCount = 0; var ohlcArea = new ChartArea { Height = 210 }; ChartPanel.AddArea(ohlcArea); _candlesElem = new ChartCandleElement(); ChartPanel.AddElement(ohlcArea, _candlesElem, series); var volumeArea = new ChartArea { Height = 130 }; ChartPanel.AddArea(volumeArea); _volumeElem = new ChartIndicatorElement { IndicatorPainter = new VolumePainter(), }; var indicator = new VolumeIndicator(); ChartPanel.AddElement(volumeArea, _volumeElem, series, indicator); CancelButton.Visibility = Visibility.Visible; _drawTimer.Activate(); } public CandleSeries Series { get; set; } void IPersistable.Load(SettingsStorage storage) { ChartPanel.Load(storage); } void IPersistable.Save(SettingsStorage storage) { ChartPanel.Save(storage); } string IPane.Title => LocalizedStrings.Str3200 + " " + Series; Uri IPane.Icon => null; bool IPane.IsValid => false; void IDisposable.Dispose() { _drawTimer.Dispose(); } private void Cancel_OnClick(object sender, RoutedEventArgs e) { _drawTimer.Cancel(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime; namespace System.Collections.ObjectModel { [Serializable] [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Collection<T> : IList<T>, IList, IReadOnlyList<T> { private IList<T> items; // Do not rename (binary serialization) [NonSerialized] private Object _syncRoot; public Collection() { items = new List<T>(); } public Collection(IList<T> list) { if (list == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } items = list; } public int Count { get { return items.Count; } } protected IList<T> Items { get { return items; } } public T this[int index] { get { return items[index]; } set { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (index < 0 || index >= items.Count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } SetItem(index, value); } } public void Add(T item) { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } int index = items.Count; InsertItem(index, item); } public void Clear() { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ClearItems(); } public void CopyTo(T[] array, int index) { items.CopyTo(array, index); } public bool Contains(T item) { return items.Contains(item); } public IEnumerator<T> GetEnumerator() { return items.GetEnumerator(); } public int IndexOf(T item) { return items.IndexOf(item); } public void Insert(int index, T item) { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (index < 0 || index > items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert); } InsertItem(index, item); } public bool Remove(T item) { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } int index = items.IndexOf(item); if (index < 0) return false; RemoveItem(index); return true; } public void RemoveAt(int index) { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (index < 0 || index >= items.Count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } RemoveItem(index); } protected virtual void ClearItems() { items.Clear(); } protected virtual void InsertItem(int index, T item) { items.Insert(index, item); } protected virtual void RemoveItem(int index) { items.RemoveAt(index); } protected virtual void SetItem(int index, T item) { items[index] = item; } bool ICollection<T>.IsReadOnly { get { return items.IsReadOnly; } } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)items).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { ICollection c = items as ICollection; if (c != null) { _syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } } return _syncRoot; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } T[] tArray = array as T[]; if (tArray != null) { items.CopyTo(tArray, index); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = items.Count; try { for (int i = 0; i < count; i++) { objects[index++] = items[i]; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } object IList.this[int index] { get { return items[index]; } set { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { this[index] = (T)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } } } bool IList.IsReadOnly { get { return items.IsReadOnly; } } bool IList.IsFixedSize { get { // There is no IList<T>.IsFixedSize, so we must assume that only // readonly collections are fixed size, if our internal item // collection does not implement IList. Note that Array implements // IList, and therefore T[] and U[] will be fixed-size. IList list = items as IList; if (list != null) { return list.IsFixedSize; } return items.IsReadOnly; } } int IList.Add(object value) { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { Add((T)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } return this.Count - 1; } bool IList.Contains(object value) { if (IsCompatibleObject(value)) { return Contains((T)value); } return false; } int IList.IndexOf(object value) { if (IsCompatibleObject(value)) { return IndexOf((T)value); } return -1; } void IList.Insert(int index, object value) { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { Insert(index, (T)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } } void IList.Remove(object value) { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (IsCompatibleObject(value)) { Remove((T)value); } } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Specialized; using System.IO; using System.Linq.Expressions; using Glass.Mapper.Sc.Web.Ui; using Sitecore.Data; namespace Glass.Mapper.Sc { /// <summary> /// IGlassHtml /// </summary> public interface IGlassHtml { /// <summary> /// Gets the sitecore context. /// </summary> /// <value> /// The sitecore context. /// </value> ISitecoreContext SitecoreContext { get; } /// <summary> /// Returns an Sitecore Edit Frame /// </summary> /// <param name="buttons">The buttons.</param> /// <param name="path">The path.</param> /// <param name="output">The stream to write the editframe output to. If the value is null the HttpContext Response Stream is used.</param> /// <param name="title">The title for the edit frame</param> /// <returns> /// GlassEditFrame. /// </returns> GlassEditFrame EditFrame(string title, string buttons, string path = null, TextWriter output= null); /// <summary> /// Returns an Sitecore Edit Frame using the fields from the specified model. /// </summary> /// <param name="model">The model of the item to use.</param> /// <param name="title">The title to display with the editframe</param> /// <param name="fields">The fields to add to the edit frame</param> /// <param name="output">The stream to write the editframe output to. If the value is null the HttpContext Response Stream is used.</param> /// <returns> /// GlassEditFrame. /// </returns> GlassEditFrame EditFrame<T>(T model, string title = null, TextWriter output= null, params Expression<Func<T, object>>[] fields) where T : class; /// <summary> /// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data. /// </summary> /// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam> /// <param name="target">The target object that contains the item to be edited</param> /// <param name="field">The field that should be made editable</param> /// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param> /// <returns>HTML output to either render the editable controls or normal HTML</returns> string Editable<T>(T target, Expression<Func<T, object>> field, object parameters = null); /// <summary> /// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data. /// </summary> /// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam> /// <param name="target">The target object that contains the item to be edited</param> /// <param name="field">The field that should be made editable</param> /// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param> /// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param> /// <returns>HTML output to either render the editable controls or normal HTML</returns> string Editable<T>(T target, Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, object parameters = null); /// <summary> /// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data. /// </summary> /// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam> /// <param name="target">The target object that contains the item to be edited</param> /// <param name="predicate">Predicate to determine if the field should be made editable</para> /// <param name="field">The field that should be made editable</param> /// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param> /// <returns>HTML output to either render the editable controls or normal HTML</returns> string EditableIf<T>(T target, Func<bool> predicate, Expression<Func<T, object>> field, object parameters = null); /// <summary> /// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data. /// </summary> /// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam> /// <param name="target">The target object that contains the item to be edited</param> /// <param name="predicate">Predicate to determine if the field should be made editable</para> /// <param name="field">The field that should be made editable</param> /// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param> /// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param> /// <returns>HTML output to either render the editable controls or normal HTML</returns> string EditableIf<T>(T target, Func<bool> predicate, Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, object parameters = null); /// <summary> /// Renders HTML for an image /// </summary> /// <param name="field">The image to render</param> /// <param name="parameters">Additional parameters to add. Do not include alt or src</param> /// <param name="outputHeightWidth">Indicates if the height and width attributes should be outputted when rendering the image</param> /// <param name="alwaysRender">Renders an A element even if the link is null</param> /// <returns>An img HTML element</returns> string RenderImage<T>(T model, Expression<Func<T, object>> field, object parameters = null, bool isEditable = false, bool outputHeightWidth = false); RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field, TextWriter writer, object attributes = null, bool isEditable = false, bool alwaysRender = false); /// <summary> /// Render HTML for a link /// </summary> /// <param name="field">The link to render</param> /// <param name="alwaysRender">Renders an A element even if the link is null</param> /// <returns>An "a" HTML element</returns> string RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents = null, bool alwaysRender = false); /// <summary> /// Gets rendering parameters using the specified template. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <param name="renderParametersTemplateId">The template used by the rendering parameters</param> /// <returns></returns> T GetRenderingParameters<T>(string parameters, ID renderParametersTemplateId) where T : class; /// <summary> /// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the /// model configuration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> T GetRenderingParameters<T>(string parameters) where T : class; /// <summary> /// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the /// model configuration. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> T GetRenderingParameters<T>(NameValueCollection parameters) where T : class; /// <summary> /// Gets rendering parameters using the specified template. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <param name="renderParametersTemplateId">The template used by the rendering parameters</param> /// <returns></returns> T GetRenderingParameters<T>(NameValueCollection parameters, ID renderParametersTemplateId) where T : class; #if (SC81 || SC80 || SC75 || SC82 || SC90) string ProtectMediaUrl(string url); #endif /// <summary> /// Allows you to get a compiled function form the lambda expression. Typically used with extension methods. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expression"></param> /// <returns></returns> Func<T, object> GetCompiled<T>(Expression<Func<T, object>> expression); /// <summary> /// Allows you to get a compiled function form the lambda expression. Typically used with extension methods. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expression"></param> /// <returns></returns> Func<T, string> GetCompiled<T>(Expression<Func<T, string>> expression); } }
// 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.ComponentModel.Composition.Primitives; using System.ComponentModel.Composition.ReflectionModel; using System.Linq; using System.Reflection; using Microsoft.Internal; namespace System.ComponentModel.Composition.Hosting { internal static class CompositionServices { internal static readonly Type InheritedExportAttributeType = typeof(InheritedExportAttribute); internal static readonly Type ExportAttributeType = typeof(ExportAttribute); internal static readonly Type AttributeType = typeof(Attribute); internal static readonly Type ObjectType = typeof(object); private static readonly string[] reservedMetadataNames = new string[] { CompositionConstants.PartCreationPolicyMetadataName }; internal static Type GetDefaultTypeFromMember(this MemberInfo member) { if (member == null) { throw new ArgumentNullException(nameof(member)); } switch (member.MemberType) { case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.NestedType: case MemberTypes.TypeInfo: return ((Type)member); case MemberTypes.Field: default: if (member.MemberType != MemberTypes.Field) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } return ((FieldInfo)member).FieldType; } } internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, MemberInfo member) { if (member.MemberType == MemberTypes.Method) { return specifiedContractType; } else { return specifiedContractType.AdjustSpecifiedTypeIdentityType(member.GetDefaultTypeFromMember()); } } internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, Type memberType) { if (specifiedContractType == null) { throw new ArgumentNullException(nameof(specifiedContractType)); } if ((memberType != null) && memberType.IsGenericType && specifiedContractType.IsGenericType) { // if the memeber type is closed and the specified contract type is open and they have exatly the same number of parameters // we will close the specfied contract type if (specifiedContractType.ContainsGenericParameters && !memberType.ContainsGenericParameters) { var typeGenericArguments = memberType.GetGenericArguments(); var metadataTypeGenericArguments = specifiedContractType.GetGenericArguments(); if (typeGenericArguments.Length == metadataTypeGenericArguments.Length) { return specifiedContractType.MakeGenericType(typeGenericArguments); } } // if both member type and the contract type are open generic types, make sure that their parameters are ordered the same way else if (specifiedContractType.ContainsGenericParameters && memberType.ContainsGenericParameters) { var memberGenericParameters = memberType.GetPureGenericParameters(); if (specifiedContractType.GetPureGenericArity() == memberGenericParameters.Count) { return specifiedContractType.GetGenericTypeDefinition().MakeGenericType(memberGenericParameters.ToArray()); } } } return specifiedContractType; } private static string AdjustTypeIdentity(string originalTypeIdentity, Type typeIdentityType) { return GenericServices.GetGenericName(originalTypeIdentity, GenericServices.GetGenericParametersOrder(typeIdentityType), GenericServices.GetPureGenericArity(typeIdentityType)); } internal static void GetContractInfoFromExport(this MemberInfo member, ExportAttribute export, out Type typeIdentityType, out string contractName) { typeIdentityType = member.GetTypeIdentityTypeFromExport(export); if (!string.IsNullOrEmpty(export.ContractName)) { contractName = export.ContractName; } else { contractName = member.GetTypeIdentityFromExport(typeIdentityType); } } internal static string GetTypeIdentityFromExport(this MemberInfo member, Type typeIdentityType) { if (typeIdentityType != null) { string typeIdentity = AttributedModelServices.GetTypeIdentity(typeIdentityType); if (typeIdentityType.ContainsGenericParameters) { typeIdentity = AdjustTypeIdentity(typeIdentity, typeIdentityType); } return typeIdentity; } else { MethodInfo method = member as MethodInfo; if (method == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } return AttributedModelServices.GetTypeIdentity(method); } } private static Type GetTypeIdentityTypeFromExport(this MemberInfo member, ExportAttribute export) { if (export.ContractType != null) { return export.ContractType.AdjustSpecifiedTypeIdentityType(member); } else { return (member.MemberType != MemberTypes.Method) ? member.GetDefaultTypeFromMember() : null; } } internal static bool IsContractNameSameAsTypeIdentity(this ExportAttribute export) { return string.IsNullOrEmpty(export.ContractName); } internal static Type GetContractTypeFromImport(this IAttributedImport import, ImportType importType) { if (import.ContractType != null) { return import.ContractType.AdjustSpecifiedTypeIdentityType(importType.ContractType); } return importType.ContractType; } internal static string GetContractNameFromImport(this IAttributedImport import, ImportType importType) { if (!string.IsNullOrEmpty(import.ContractName)) { return import.ContractName; } Type contractType = import.GetContractTypeFromImport(importType); return AttributedModelServices.GetContractName(contractType); } internal static string GetTypeIdentityFromImport(this IAttributedImport import, ImportType importType) { Type contractType = import.GetContractTypeFromImport(importType); // For our importers we treat object as not having a type identity if (contractType == CompositionServices.ObjectType) { return null; } return AttributedModelServices.GetTypeIdentity(contractType); } internal static IDictionary<string, object> GetPartMetadataForType(this Type type, CreationPolicy creationPolicy) { IDictionary<string, object> dictionary = new Dictionary<string, object>(StringComparers.MetadataKeyNames); if (creationPolicy != CreationPolicy.Any) { dictionary.Add(CompositionConstants.PartCreationPolicyMetadataName, creationPolicy); } foreach (PartMetadataAttribute partMetadata in type.GetAttributes<PartMetadataAttribute>()) { if (reservedMetadataNames.Contains(partMetadata.Name, StringComparers.MetadataKeyNames) || dictionary.ContainsKey(partMetadata.Name)) { // Perhaps we should log an error here so that people know this value is being ignored. continue; } dictionary.Add(partMetadata.Name, partMetadata.Value); } // metadata for generic types if (type.ContainsGenericParameters) { // Register the part as generic dictionary.Add(CompositionConstants.IsGenericPartMetadataName, true); // Add arity Type[] genericArguments = type.GetGenericArguments(); dictionary.Add(CompositionConstants.GenericPartArityMetadataName, genericArguments.Length); // add constraints bool hasConstraints = false; object[] genericParameterConstraints = new object[genericArguments.Length]; GenericParameterAttributes[] genericParameterAttributes = new GenericParameterAttributes[genericArguments.Length]; for (int i = 0; i < genericArguments.Length; i++) { Type genericArgument = genericArguments[i]; Type[] constraints = genericArgument.GetGenericParameterConstraints(); if (constraints.Length == 0) { constraints = null; } GenericParameterAttributes attributes = genericArgument.GenericParameterAttributes; if ((constraints != null) || (attributes != GenericParameterAttributes.None)) { genericParameterConstraints[i] = constraints; genericParameterAttributes[i] = attributes; hasConstraints = true; } } if (hasConstraints) { dictionary.Add(CompositionConstants.GenericParameterConstraintsMetadataName, genericParameterConstraints); dictionary.Add(CompositionConstants.GenericParameterAttributesMetadataName, genericParameterAttributes); } } if (dictionary.Count == 0) { return MetadataServices.EmptyMetadata; } else { return dictionary; } } internal static void TryExportMetadataForMember(this MemberInfo member, out IDictionary<string, object> dictionary) { dictionary = new Dictionary<string, object>(); foreach (var attr in member.GetAttributes<Attribute>()) { var provider = attr as ExportMetadataAttribute; if (provider != null) { if (reservedMetadataNames.Contains(provider.Name, StringComparers.MetadataKeyNames)) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_ReservedMetadataNameUsed, member.GetDisplayName(), provider.Name); } // we pass "null" for valueType which would make it inferred. We don;t have additional type information when metadata // goes through the ExportMetadataAttribute path if (!dictionary.TryContributeMetadataValue(provider.Name, provider.Value, null, provider.IsMultiple)) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_DuplicateMetadataNameValues, member.GetDisplayName(), provider.Name); } } else { Type attrType = attr.GetType(); // Perf optimization, relies on short circuit evaluation, often a property attribute is an ExportAttribute if ((attrType != CompositionServices.ExportAttributeType) && attrType.IsAttributeDefined<MetadataAttributeAttribute>(true)) { bool allowsMultiple = false; AttributeUsageAttribute usage = attrType.GetFirstAttribute<AttributeUsageAttribute>(true); if (usage != null) { allowsMultiple = usage.AllowMultiple; } foreach (PropertyInfo pi in attrType.GetProperties()) { if (pi.DeclaringType == CompositionServices.ExportAttributeType || pi.DeclaringType == CompositionServices.AttributeType) { // Don't contribute metadata properies from the base attribute types. continue; } if (reservedMetadataNames.Contains(pi.Name, StringComparers.MetadataKeyNames)) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_ReservedMetadataNameUsed, member.GetDisplayName(), provider.Name); } object value = pi.GetValue(attr, null); if (value != null && !IsValidAttributeType(value.GetType())) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_MetadataContainsValueWithInvalidType, pi.GetDisplayName(), value.GetType().GetDisplayName()); } if (!dictionary.TryContributeMetadataValue(pi.Name, value, pi.PropertyType, allowsMultiple)) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_DuplicateMetadataNameValues, member.GetDisplayName(), pi.Name); } } } } } // Need Keys.ToArray because we alter the dictionary in the loop foreach (var key in dictionary.Keys.ToArray()) { var list = dictionary[key] as MetadataList; if (list != null) { dictionary[key] = list.ToArray(); } } return; } private static bool TryContributeMetadataValue(this IDictionary<string, object> dictionary, string name, object value, Type valueType, bool allowsMultiple) { object metadataValue; if (!dictionary.TryGetValue(name, out metadataValue)) { if (allowsMultiple) { var list = new MetadataList(); list.Add(value, valueType); value = list; } dictionary.Add(name, value); } else { var list = metadataValue as MetadataList; if (!allowsMultiple || list == null) { // Either single value already found when should be multiple // or a duplicate name already exists dictionary.Remove(name); return false; } list.Add(value, valueType); } return true; } private class MetadataList { private Type _arrayType = null; private bool _containsNulls = false; private static readonly Type ObjectType = typeof(object); private static readonly Type TypeType = typeof(Type); private readonly Collection<object> _innerList = new Collection<object>(); public void Add(object item, Type itemType) { _containsNulls |= (item == null); // if we've been passed typeof(object), we basically have no type inmformation if (itemType == ObjectType) { itemType = null; } // if we have no type information, get it from the item, if we can if ((itemType == null) && (item != null)) { itemType = item.GetType(); } // Types are special, because the are abstract classes, so if the item casts to Type, we assume System.Type if (item is Type) { itemType = TypeType; } // only try to call this if we got a meaningful type if (itemType != null) { InferArrayType(itemType); } _innerList.Add(item); } private void InferArrayType(Type itemType) { if (itemType == null) { throw new ArgumentNullException(nameof(itemType)); } if (_arrayType == null) { // this is the first typed element we've been given, it sets the type of the array _arrayType = itemType; } else { // if there's a disagreement on the array type, we flip to Object // NOTE : we can try to do better in the future to find common base class, but given that we support very limited set of types // in metadata right now, it's a moot point if (_arrayType != itemType) { _arrayType = ObjectType; } } } public Array ToArray() { if (_arrayType == null) { // if the array type has not been set, assume Object _arrayType = ObjectType; } else if (_containsNulls && _arrayType.IsValueType) { // if the array type is a value type and we have seen nulls, then assume Object _arrayType = ObjectType; } Array array = Array.CreateInstance(_arrayType, _innerList.Count); for (int i = 0; i < array.Length; i++) { array.SetValue(_innerList[i], i); } return array; } } //UNDONE: Need to add these warnings somewhere...Dev10:472538 should address //internal static CompositionResult MatchRequiredMetadata(this IDictionary<string, object> metadata, IEnumerable<string> requiredMetadata, string contractName) //{ // Assumes.IsTrue(metadata != null); // var result = CompositionResult.SucceededResult; // var missingMetadata = (requiredMetadata == null) ? null : requiredMetadata.Except<string>(metadata.Keys); // if (missingMetadata != null && missingMetadata.Any()) // { // result = result.MergeIssue( // CompositionError.CreateIssueAsWarning(CompositionErrorId.RequiredMetadataNotFound, // SR.RequiredMetadataNotFound, // contractName, // string.Join(", ", missingMetadata.ToArray()))); // return new CompositionResult(false, result.Issues); // } // return result; //} internal static IEnumerable<KeyValuePair<string, Type>> GetRequiredMetadata(Type metadataViewType) { if ((metadataViewType == null) || ExportServices.IsDefaultMetadataViewType(metadataViewType) || ExportServices.IsDictionaryConstructorViewType(metadataViewType) || !metadataViewType.IsInterface) { return Enumerable.Empty<KeyValuePair<string, Type>>(); } // A metadata view is required to be an Intrerface, and therefore only properties are allowed List<PropertyInfo> properties = metadataViewType.GetAllProperties(). Where(property => property.GetFirstAttribute<DefaultValueAttribute>() == null). ToList(); // NOTE : this is a carefully found balance between eager and delay-evaluation - the properties are filtered once and upfront // whereas the key/Type pairs are created every time. The latter is fine as KVPs are structs and as such copied on access regardless. // This also allows us to avoid creation of List<KVP> which - at least according to FxCop - leads to isues with NGEN return properties.Select(property => new KeyValuePair<string, Type>(property.Name, property.PropertyType)); } internal static IDictionary<string, object> GetImportMetadata(ImportType importType, IAttributedImport attributedImport) { return GetImportMetadata(importType.ContractType, attributedImport); } internal static IDictionary<string, object> GetImportMetadata(Type type, IAttributedImport attributedImport) { Dictionary<string, object> metadata = null; //Prior to V4.5 MEF did not support ImportMetadata if (type.IsGenericType) { metadata = new Dictionary<string, object>(); if (type.ContainsGenericParameters) { metadata[CompositionConstants.GenericImportParametersOrderMetadataName] = GenericServices.GetGenericParametersOrder(type); } else { metadata[CompositionConstants.GenericContractMetadataName] = ContractNameServices.GetTypeIdentity(type.GetGenericTypeDefinition()); metadata[CompositionConstants.GenericParametersMetadataName] = type.GetGenericArguments(); } } // Default value is ImportSource.Any if (attributedImport != null && attributedImport.Source != ImportSource.Any) { if (metadata == null) { metadata = new Dictionary<string, object>(); } metadata[CompositionConstants.ImportSourceMetadataName] = attributedImport.Source; } if (metadata != null) { return metadata.AsReadOnly(); } else { return MetadataServices.EmptyMetadata; } } internal static object GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition) { if (engine != null) { try { engine.SatisfyImports(part); } catch (CompositionException ex) { throw ExceptionBuilder.CreateCannotGetExportedValue(part, definition, ex); } } try { return part.GetExportedValue(definition); } catch (ComposablePartException ex) { throw ExceptionBuilder.CreateCannotGetExportedValue(part, definition, ex); } } internal static bool IsRecomposable(this ComposablePart part) { return part.ImportDefinitions.Any(import => import.IsRecomposable); } internal static CompositionResult TryInvoke(Action action) { try { action(); return CompositionResult.SucceededResult; } catch (CompositionException ex) { return new CompositionResult(ex.Errors); } } internal static CompositionResult TryFire<TEventArgs>(EventHandler<TEventArgs> _delegate, object sender, TEventArgs e) where TEventArgs : EventArgs { CompositionResult result = CompositionResult.SucceededResult; foreach (EventHandler<TEventArgs> _subscriber in _delegate.GetInvocationList()) { try { _subscriber.Invoke(sender, e); } catch (CompositionException ex) { result = result.MergeErrors(ex.Errors); } } return result; } internal static CreationPolicy GetRequiredCreationPolicy(this ImportDefinition definition) { ContractBasedImportDefinition contractDefinition = definition as ContractBasedImportDefinition; if (contractDefinition != null) { return contractDefinition.RequiredCreationPolicy; } return CreationPolicy.Any; } /// <summary> /// Returns a value indicating whether cardinality is /// <see cref="ImportCardinality.ZeroOrOne"/> or /// <see cref="ImportCardinality.ExactlyOne"/>. /// </summary> internal static bool IsAtMostOne(this ImportCardinality cardinality) { return cardinality == ImportCardinality.ZeroOrOne || cardinality == ImportCardinality.ExactlyOne; } private static bool IsValidAttributeType(Type type) { return IsValidAttributeType(type, true); } private static bool IsValidAttributeType(Type type, bool arrayAllowed) { if (type == null) { throw new ArgumentNullException(nameof(type)); } // Definitions of valid attribute type taken from C# 3.0 Specification section 17.1.3. // One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort. if (type.IsPrimitive) { return true; } if (type == typeof(string)) { return true; } // An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility if (type.IsEnum && type.IsVisible) { return true; } if (typeof(Type).IsAssignableFrom(type)) { return true; } // Single-dimensional arrays of the above types. if (arrayAllowed && type.IsArray && type.GetArrayRank() == 1 && IsValidAttributeType(type.GetElementType(), false)) { return true; } return false; } } }
// Python Tools for Visual Studio // 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.Collections.Generic; using System.Linq; using Microsoft.Build.Construction; namespace Microsoft.PythonTools.Project.ImportWizard { abstract class ProjectCustomization { public abstract string DisplayName { get; } public override string ToString() { return DisplayName; } public abstract void Process( ProjectRootElement project, Dictionary<string, ProjectPropertyGroupElement> groups ); protected static void AddOrSetProperty(ProjectRootElement project, string name, string value) { bool anySet = false; foreach (var prop in project.Properties.Where(p => p.Name == name)) { prop.Value = value; anySet = true; } if (!anySet) { project.AddProperty(name, value); } } protected static void AddOrSetProperty(ProjectPropertyGroupElement group, string name, string value) { bool anySet = false; foreach (var prop in group.Properties.Where(p => p.Name == name)) { prop.Value = value; anySet = true; } if (!anySet) { group.AddProperty(name, value); } } } class DefaultProjectCustomization : ProjectCustomization { public static readonly ProjectCustomization Instance = new DefaultProjectCustomization(); private DefaultProjectCustomization() { } public override string DisplayName { get { return Strings.ImportWizardDefaultProjectCustomization; } } public override void Process( ProjectRootElement project, Dictionary<string, ProjectPropertyGroupElement> groups ) { ProjectPropertyGroupElement imports; if (!groups.TryGetValue("Imports", out imports)) { imports = project.AddPropertyGroup(); } AddOrSetProperty(imports, "PtvsTargetsFile", @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets"); project.AddImport("$(PtvsTargetsFile)").Condition = "Exists($(PtvsTargetsFile))"; project.AddImport(@"$(MSBuildToolsPath)\Microsoft.Common.targets").Condition = "!Exists($(PtvsTargetsFile))"; } } class BottleProjectCustomization : ProjectCustomization { public static readonly ProjectCustomization Instance = new BottleProjectCustomization(); private BottleProjectCustomization() { } public override string DisplayName { get { return Strings.ImportWizardBottleProjectCustomization; } } public override void Process( ProjectRootElement project, Dictionary<string, ProjectPropertyGroupElement> groups ) { ProjectPropertyGroupElement globals; if (!groups.TryGetValue("Globals", out globals)) { globals = project.AddPropertyGroup(); } AddOrSetProperty(globals, "ProjectTypeGuids", "{e614c764-6d9e-4607-9337-b7073809a0bd};{1b580a1a-fdb3-4b32-83e1-6407eb2722e6};{349c5851-65df-11da-9384-00065b846f21};{888888a0-9f3d-457c-b088-3a5042f75d52}"); AddOrSetProperty(globals, "LaunchProvider", PythonConstants.WebLauncherName); AddOrSetProperty(globals, "PythonDebugWebServerCommandArguments", "--debug $(CommandLineArguments)"); AddOrSetProperty(globals, "PythonWsgiHandler", "{StartupModule}.wsgi_app()"); project.AddImport(@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets"); } } class DjangoProjectCustomization : ProjectCustomization { public static readonly ProjectCustomization Instance = new DjangoProjectCustomization(); private DjangoProjectCustomization() { } public override string DisplayName { get { return Strings.ImportWizardDjangoProjectCustomization; } } public override void Process( ProjectRootElement project, Dictionary<string, ProjectPropertyGroupElement> groups ) { ProjectPropertyGroupElement globals; if (!groups.TryGetValue("Globals", out globals)) { globals = project.AddPropertyGroup(); } AddOrSetProperty(globals, "StartupFile", "manage.py"); AddOrSetProperty(globals, "ProjectTypeGuids", "{5F0BE9CA-D677-4A4D-8806-6076C0FAAD37};{349c5851-65df-11da-9384-00065b846f21};{888888a0-9f3d-457c-b088-3a5042f75d52}"); AddOrSetProperty(globals, "LaunchProvider", "Django launcher"); project.AddImport(@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Django.targets"); } } class FlaskProjectCustomization : ProjectCustomization { public static readonly ProjectCustomization Instance = new FlaskProjectCustomization(); private FlaskProjectCustomization() { } public override string DisplayName { get { return Strings.ImportWizardFlaskProjectCustomization; } } public override void Process( ProjectRootElement project, Dictionary<string, ProjectPropertyGroupElement> groups ) { ProjectPropertyGroupElement globals; if (!groups.TryGetValue("Globals", out globals)) { globals = project.AddPropertyGroup(); } AddOrSetProperty(globals, "ProjectTypeGuids", "{789894c7-04a9-4a11-a6b5-3f4435165112};{1b580a1a-fdb3-4b32-83e1-6407eb2722e6};{349c5851-65df-11da-9384-00065b846f21};{888888a0-9f3d-457c-b088-3a5042f75d52}"); AddOrSetProperty(globals, "LaunchProvider", PythonConstants.WebLauncherName); AddOrSetProperty(globals, "PythonWsgiHandler", "{StartupModule}.wsgi_app"); project.AddImport(@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets"); } } class GenericWebProjectCustomization : ProjectCustomization { public static readonly ProjectCustomization Instance = new GenericWebProjectCustomization(); private GenericWebProjectCustomization() { } public override string DisplayName { get { return Strings.ImportWizardGenericWebProjectCustomization; } } public override void Process( ProjectRootElement project, Dictionary<string, ProjectPropertyGroupElement> groups ) { ProjectPropertyGroupElement globals; if (!groups.TryGetValue("Globals", out globals)) { globals = project.AddPropertyGroup(); } AddOrSetProperty(globals, "ProjectTypeGuids", "{1b580a1a-fdb3-4b32-83e1-6407eb2722e6};{349c5851-65df-11da-9384-00065b846f21};{888888a0-9f3d-457c-b088-3a5042f75d52}"); AddOrSetProperty(globals, "LaunchProvider", PythonConstants.WebLauncherName); project.AddImport(@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets"); } } class UwpProjectCustomization : ProjectCustomization { public static readonly ProjectCustomization Instance = new UwpProjectCustomization(); private UwpProjectCustomization() { } public override string DisplayName { get { return Strings.ImportWizardUwpProjectCustomization; } } public override void Process( ProjectRootElement project, Dictionary<string, ProjectPropertyGroupElement> groups ) { ProjectPropertyGroupElement globals; if (!groups.TryGetValue("Globals", out globals)) { globals = project.AddPropertyGroup(); } AddOrSetProperty(globals, "ProjectTypeGuids", "{2b557614-1a2b-4903-b9df-ed20d7b63f3a};{888888A0-9F3D-457C-B088-3A5042F75D52}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.IO; using System.Web.UI; using System.Text.RegularExpressions; using ClientDependency.Core.CompositeFiles.Providers; using ClientDependency.Core.Controls; using ClientDependency.Core.FileRegistration.Providers; using ClientDependency.Core.Config; using ClientDependency.Core; using System.Net; namespace ClientDependency.Core.Module { /// <summary> /// Used as an http response filter to modify the contents of the output html. /// This filter is used to intercept js and css rogue registrations on the html page. /// </summary> public class RogueFileFilter : IFilter { #region Private members private bool? m_Runnable = null; private string m_MatchScript = "<script(?:(?:.*(?<src>(?<=src=\")[^\"]*(?=\"))[^>]*)|[^>]*)>(?<content>(?:(?:\n|.)(?!(?:\n|.)<script))*)</script>"; private string m_MatchLink = "<link\\s+[^>]*(href\\s*=\\s*(['\"])(?<href>.*?)\\2)"; private RogueFileCompressionElement m_FoundPath = null; #endregion #region IFilter Members public void SetHttpContext(HttpContextBase ctx) { CurrentContext = ctx; m_FoundPath = GetSupportedPath(); } /// <summary> /// This filter can only execute when it's a Page or MvcHandler /// </summary> /// <returns></returns> public virtual bool ValidateCurrentHandler() { //don't filter if we're in debug mode if (CurrentContext.IsDebuggingEnabled || !ClientDependencySettings.Instance.DefaultFileRegistrationProvider.EnableCompositeFiles) return false; return (CurrentContext.CurrentHandler is Page); } /// <summary> /// Returns true when this filter should be applied /// </summary> /// <returns></returns> public bool CanExecute() { if (!ValidateCurrentHandler()) { return false; } if (!m_Runnable.HasValue) { m_Runnable = (m_FoundPath != null); } return m_Runnable.Value; } /// <summary> /// Replaces any rogue script tag's with calls to the compression handler instead /// of just the script. /// </summary> public string UpdateOutputHtml(string html) { html = ReplaceScripts(html); html = ReplaceStyles(html); return html; } public HttpContextBase CurrentContext { get; private set; } #endregion #region Private methods private RogueFileCompressionElement GetSupportedPath() { var rawUrl = CurrentContext.GetRawUrlSafe(); if (string.IsNullOrWhiteSpace(rawUrl)) return null; var rogueFiles = ClientDependencySettings.Instance .ConfigSection .CompositeFileElement .RogueFileCompression; //*** DNN related change *** begin return (from m in rogueFiles.Cast<RogueFileCompressionElement>() let reg = m.FilePath == "*" ? ".*" : m.FilePath let matched = Regex.IsMatch(rawUrl, reg, RegexOptions.IgnoreCase) where matched let isGood = m.ExcludePaths.Cast<RogueFileCompressionExcludeElement>().Select(e => Regex.IsMatch(rawUrl, e.FilePath, RegexOptions.IgnoreCase)).All(excluded => !excluded) where isGood select m).FirstOrDefault(); //*** DNN related change *** end } /// <summary> /// Replaces all src attribute values for a script tag with their corresponding /// URLs as a composite script. /// </summary> /// <param name="html"></param> /// <returns></returns> private string ReplaceScripts(string html) { //check if we should be processing! if (CanExecute() && m_FoundPath.CompressJs) { return ReplaceContent(html, "src", m_FoundPath.JsRequestExtension.Split(','), ClientDependencyType.Javascript, m_MatchScript, CurrentContext); } return html; } /// <summary> /// Replaces all href attribute values for a link tag with their corresponding /// URLs as a composite style. /// </summary> /// <param name="html"></param> /// <returns></returns> private string ReplaceStyles(string html) { //check if we should be processing! if (CanExecute() && m_FoundPath.CompressCss) { return ReplaceContent(html, "href", m_FoundPath.CssRequestExtension.Split(','), ClientDependencyType.Css, m_MatchLink, CurrentContext); } return html; } /// <summary> /// Replaces the content with the new js/css paths /// </summary> /// <param name="html"></param> /// <param name="namedGroup"></param> /// <param name="extensions"></param> /// <param name="type"></param> /// <param name="regex"></param> /// <param name="http"></param> /// <returns></returns> /// <remarks> /// For some reason ampersands that aren't html escaped are not compliant to HTML standards when they exist in 'link' or 'script' tags in URLs, /// we need to replace the ampersands with &amp; . This is only required for this one w3c compliancy, the URL itself is a valid URL. /// </remarks> private static string ReplaceContent(string html, string namedGroup, string[] extensions, ClientDependencyType type, string regex, HttpContextBase http) { html = Regex.Replace(html, regex, (m) => { var grp = m.Groups[namedGroup]; //if there is no namedGroup group name or it doesn't end with a js/css extension or it's already using the composite handler, //the return the existing string. if (grp == null || string.IsNullOrEmpty(grp.ToString()) || !grp.ToString().EndsWithOneOf(extensions) || grp.ToString().StartsWith(ClientDependencySettings.Instance.CompositeFileHandlerPath)) return m.ToString(); //make sure that it's an internal request, though we can deal with external //requests, we'll leave that up to the developer to register an external request //explicitly if they want to include in the composite scripts. try { var url = new Uri(grp.ToString(), UriKind.RelativeOrAbsolute); if (!url.IsLocalUri(http)) return m.ToString(); //not a local uri else { var dependency = new BasicFile(type) { FilePath = grp.ToString() }; var file = new[] { new BasicFile(type) { FilePath = dependency.ResolveFilePath(http) } }; var resolved = ClientDependencySettings.Instance.DefaultCompositeFileProcessingProvider.ProcessCompositeList( file, type, http).Single(); return m.ToString().Replace(grp.ToString(), resolved.Replace("&", "&amp;")); } } catch (UriFormatException) { //malformed url, let's exit return m.ToString(); } //*** DNN related change *** begin }); //*** DNN related change *** begin return html; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using Internal.Reflection.Core.Execution; namespace System.Reflection.Runtime.BindingFlagSupport { // // Stores the result of a member filtering that's filtered by name and visibility from base class (as defined by the Type.Get*() family of apis). // // The results are as if you'd passed in a bindingFlags value of "Public | NonPublic | Instance | Static | FlattenHierarchy" // In addition, if "ignoreCase" was passed to Create(), BindingFlags.IgnoreCase is also in effect. // // Results are sorted by declaring type. The members declared by the most derived type appear first, then those declared by his base class, and so on. // The Disambiguation logic takes advantage of this. // // This object is a good candidate for long term caching. // internal sealed class QueriedMemberList<M> where M : MemberInfo { private QueriedMemberList() { _members = new M[Grow]; _allFlagsThatMustMatch = new BindingFlags[Grow]; } private QueriedMemberList(int totalCount, int declaredOnlyCount, M[] members, BindingFlags[] allFlagsThatMustMatch, RuntimeTypeInfo typeThatBlockedBrowsing) { _totalCount = totalCount; _declaredOnlyCount = declaredOnlyCount; _members = members; _allFlagsThatMustMatch = allFlagsThatMustMatch; _typeThatBlockedBrowsing = typeThatBlockedBrowsing; } /// <summary> /// Returns the # of candidates for a non-DeclaredOnly search. Caution: Can throw MissingMetadataException. Use DeclaredOnlyCount if you don't want to search base classes. /// </summary> public int TotalCount { get { if (_typeThatBlockedBrowsing != null) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(_typeThatBlockedBrowsing); return _totalCount; } } /// <summary> /// Returns the # of candidates for a DeclaredOnly search /// </summary> public int DeclaredOnlyCount => _declaredOnlyCount; public M this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Debug.Assert(index >= 0 && index < _totalCount); return _members[index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Matches(int index, BindingFlags bindingAttr) { Debug.Assert(index >= 0 && index < _totalCount); BindingFlags allFlagsThatMustMatch = _allFlagsThatMustMatch[index]; return ((bindingAttr & allFlagsThatMustMatch) == allFlagsThatMustMatch); } public QueriedMemberList<M> Filter(Func<M, bool> predicate) { BindingFlags[] newAllFlagsThatMustMatch = new BindingFlags[_totalCount]; M[] newMembers = new M[_totalCount]; int newDeclaredOnlyCount = 0; int newTotalCount = 0; for (int i = 0; i < _totalCount; i++) { M member = _members[i]; if (predicate(member)) { newMembers[newTotalCount] = member; newAllFlagsThatMustMatch[newTotalCount] = _allFlagsThatMustMatch[i]; newTotalCount++; if (i < _declaredOnlyCount) newDeclaredOnlyCount++; } } return new QueriedMemberList<M>(newTotalCount, newDeclaredOnlyCount, newMembers, newAllFlagsThatMustMatch, _typeThatBlockedBrowsing); } // // Filter by name and visibility from the ReflectedType. // public static QueriedMemberList<M> Create(RuntimeTypeInfo type, string optionalNameFilter, bool ignoreCase) { RuntimeTypeInfo reflectedType = type; MemberPolicies<M> policies = MemberPolicies<M>.Default; NameFilter nameFilter; if (optionalNameFilter == null) nameFilter = null; else if (ignoreCase) nameFilter = new NameFilterCaseInsensitive(optionalNameFilter); else nameFilter = new NameFilterCaseSensitive(optionalNameFilter); bool inBaseClass = false; QueriedMemberList<M> queriedMembers = new QueriedMemberList<M>(); while (type != null) { int numCandidatesInDerivedTypes = queriedMembers._totalCount; foreach (M member in policies.CoreGetDeclaredMembers(type, nameFilter, reflectedType)) { MethodAttributes visibility; bool isStatic; bool isVirtual; bool isNewSlot; policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot); if (inBaseClass && visibility == MethodAttributes.Private) continue; if (numCandidatesInDerivedTypes != 0 && policies.IsSuppressedByMoreDerivedMember(member, queriedMembers._members, startIndex: 0, endIndex: numCandidatesInDerivedTypes)) continue; BindingFlags allFlagsThatMustMatch = default(BindingFlags); allFlagsThatMustMatch |= (isStatic ? BindingFlags.Static : BindingFlags.Instance); if (isStatic && inBaseClass) allFlagsThatMustMatch |= BindingFlags.FlattenHierarchy; allFlagsThatMustMatch |= ((visibility == MethodAttributes.Public) ? BindingFlags.Public : BindingFlags.NonPublic); queriedMembers.Add(member, allFlagsThatMustMatch); } if (!inBaseClass) { queriedMembers._declaredOnlyCount = queriedMembers._totalCount; if (policies.AlwaysTreatAsDeclaredOnly) break; inBaseClass = true; } type = type.BaseType.CastToRuntimeTypeInfo(); if (type != null && !type.CanBrowseWithoutMissingMetadataExceptions) { // If we got here, one of the base classes is missing metadata. We don't want to throw a MissingMetadataException now because we may be // building a cached result for a caller who passed BindingFlags.DeclaredOnly. So we'll mark the results in a way that // it will throw a MissingMetadataException if a caller attempts to iterate past the declared-only subset. queriedMembers._typeThatBlockedBrowsing = type; queriedMembers._totalCount = queriedMembers._declaredOnlyCount; break; } } return queriedMembers; } public void Compact() { Array.Resize(ref _members, _totalCount); Array.Resize(ref _allFlagsThatMustMatch, _totalCount); } private void Add(M member, BindingFlags allFlagsThatMustMatch) { const BindingFlags validBits = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; Debug.Assert((allFlagsThatMustMatch & ~validBits) == 0); Debug.Assert(((allFlagsThatMustMatch & BindingFlags.Public) == 0) != ((allFlagsThatMustMatch & BindingFlags.NonPublic) == 0)); Debug.Assert(((allFlagsThatMustMatch & BindingFlags.Instance) == 0) != ((allFlagsThatMustMatch & BindingFlags.Static) == 0)); Debug.Assert((allFlagsThatMustMatch & BindingFlags.FlattenHierarchy) == 0 || (allFlagsThatMustMatch & BindingFlags.Static) != 0); int count = _totalCount; if (count == _members.Length) { Array.Resize(ref _members, count + Grow); Array.Resize(ref _allFlagsThatMustMatch, count + Grow); } _members[count] = member; _allFlagsThatMustMatch[count] = allFlagsThatMustMatch; _totalCount++; } private int _totalCount; // # of entries including members in base classes. private int _declaredOnlyCount; // # of entries for members only in the most derived class. private M[] _members; // Length is equal to or greater than _totalCount. Entries beyond _totalCount contain null or garbage and should be read. private BindingFlags[] _allFlagsThatMustMatch; // Length will be equal to _members.Length private RuntimeTypeInfo _typeThatBlockedBrowsing; // If non-null, one of the base classes was missing metadata. private const int Grow = 64; } }
using System; using System.Collections.Generic; using System.Data.Services.Client; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime.Versioning; using System.Windows; using NuGet.Resources; namespace NuGet { public class DataServicePackageRepository : PackageRepositoryBase, IHttpClientEvents, IServiceBasedRepository, ICloneableRepository, ICultureAwareRepository, IOperationAwareRepository, IPackageLookup, ILatestPackageLookup, IWeakEventListener { private const string FindPackagesByIdSvcMethod = "FindPackagesById"; private const string PackageServiceEntitySetName = "Packages"; private const string SearchSvcMethod = "Search"; private const string GetUpdatesSvcMethod = "GetUpdates"; private IDataServiceContext _context; private readonly IHttpClient _httpClient; private readonly PackageDownloader _packageDownloader; private CultureInfo _culture; private Tuple<string, string, string> _currentOperation; public DataServicePackageRepository(Uri serviceRoot) : this(new HttpClient(serviceRoot)) { } public DataServicePackageRepository(IHttpClient client) : this(client, new PackageDownloader()) { } public DataServicePackageRepository(IHttpClient client, PackageDownloader packageDownloader) { if (client == null) { throw new ArgumentNullException("client"); } if (packageDownloader == null) { throw new ArgumentNullException("packageDownloader"); } _httpClient = client; _httpClient.AcceptCompression = true; _packageDownloader = packageDownloader; if (EnvironmentUtility.RunningFromCommandLine) { _packageDownloader.SendingRequest += OnPackageDownloaderSendingRequest; } else { // weak event pattern SendingRequestEventManager.AddListener(_packageDownloader, this); } } private void OnPackageDownloaderSendingRequest(object sender, WebRequestEventArgs e) { if (_currentOperation != null) { string operation = _currentOperation.Item1; string mainPackageId = _currentOperation.Item2; string mainPackageVersion = _currentOperation.Item3; if (!String.IsNullOrEmpty(mainPackageId) && !String.IsNullOrEmpty(_packageDownloader.CurrentDownloadPackageId)) { if (!mainPackageId.Equals(_packageDownloader.CurrentDownloadPackageId, StringComparison.OrdinalIgnoreCase)) { operation = operation + "-Dependency"; } } e.Request.Headers[RepositoryOperationNames.OperationHeaderName] = operation; if (!operation.Equals(_currentOperation.Item1, StringComparison.OrdinalIgnoreCase)) { e.Request.Headers[RepositoryOperationNames.DependentPackageHeaderName] = mainPackageId; if (!String.IsNullOrEmpty(mainPackageVersion)) { e.Request.Headers[RepositoryOperationNames.DependentPackageVersionHeaderName] = mainPackageVersion; } } } } // Just forward calls to the package downloader public event EventHandler<ProgressEventArgs> ProgressAvailable { add { _packageDownloader.ProgressAvailable += value; } remove { _packageDownloader.ProgressAvailable -= value; } } public event EventHandler<WebRequestEventArgs> SendingRequest { add { _packageDownloader.SendingRequest += value; _httpClient.SendingRequest += value; } remove { _packageDownloader.SendingRequest -= value; _httpClient.SendingRequest -= value; } } public CultureInfo Culture { get { if (_culture == null) { // TODO: Technically, if this is a remote server, we have to return the culture of the server // instead of invariant culture. However, there is no trivial way to retrieve the server's culture, // So temporarily use Invariant culture here. _culture = _httpClient.Uri.IsLoopback ? CultureInfo.CurrentCulture : CultureInfo.InvariantCulture; } return _culture; } } // Do NOT delete this property. It is used by the functional test. public PackageDownloader PackageDownloader { get { return _packageDownloader; } } public override string Source { get { return _httpClient.Uri.OriginalString; } } public override bool SupportsPrereleasePackages { get { return Context.SupportsProperty("IsAbsoluteLatestVersion"); } } // Don't initialize the Context at the constructor time so that // we don't make a web request if we are not going to actually use it // since getting the Uri property of the RedirectedHttpClient will // trigger that functionality. internal IDataServiceContext Context { private get { if (_context == null) { _context = new DataServiceContextWrapper(_httpClient.Uri); _context.SendingRequest += OnSendingRequest; _context.ReadingEntity += OnReadingEntity; _context.IgnoreMissingProperties = true; } return _context; } set { _context = value; } } private void OnReadingEntity(object sender, ReadingWritingEntityEventArgs e) { var package = (DataServicePackage)e.Entity; // REVIEW: This is the only way (I know) to download the package on demand // GetReadStreamUri cannot be evaluated inside of OnReadingEntity. Lazily evaluate it inside DownloadPackage package.Context = Context; package.Downloader = _packageDownloader; } private void OnSendingRequest(object sender, SendingRequestEventArgs e) { // Initialize the request _httpClient.InitializeRequest(e.Request); } public override IQueryable<IPackage> GetPackages() { // REVIEW: Is it ok to assume that the package entity set is called packages? return new SmartDataServiceQuery<DataServicePackage>(Context, PackageServiceEntitySetName); } public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions) { if (!Context.SupportsServiceMethod(SearchSvcMethod)) { // If there's no search method then we can't filter by target framework return GetPackages().Find(searchTerm) .FilterByPrerelease(allowPrereleaseVersions) .AsQueryable(); } // Convert the list of framework names into short names var shortFrameworkNames = targetFrameworks.Select(name => new FrameworkName(name)) .Select(VersionUtility.GetShortFrameworkName); // Create a '|' separated string of framework names string targetFrameworkString = String.Join("|", shortFrameworkNames); var searchParameters = new Dictionary<string, object> { { "searchTerm", "'" + UrlEncodeOdataParameter(searchTerm) + "'" }, { "targetFramework", "'" + UrlEncodeOdataParameter(targetFrameworkString) + "'" }, }; if (SupportsPrereleasePackages) { searchParameters.Add("includePrerelease", ToLowerCaseString(allowPrereleaseVersions)); } // Create a query for the search service method var query = Context.CreateQuery<DataServicePackage>(SearchSvcMethod, searchParameters); return new SmartDataServiceQuery<DataServicePackage>(Context, query); } public bool Exists(string packageId, SemanticVersion version) { IQueryable<DataServicePackage> query = Context.CreateQuery<DataServicePackage>(PackageServiceEntitySetName).AsQueryable(); foreach (string versionString in version.GetComparableVersionStrings()) { try { var packages = query.Where(p => p.Id == packageId && p.Version == versionString) .Select(p => p.Id) // since we only want to check for existence, no need to get all attributes .ToArray(); if (packages.Length == 1) { return true; } } catch (DataServiceQueryException) { // DataServiceQuery exception will occur when the (id, version) // combination doesn't exist. } } return false; } public IPackage FindPackage(string packageId, SemanticVersion version) { IQueryable<DataServicePackage> query = Context.CreateQuery<DataServicePackage>(PackageServiceEntitySetName).AsQueryable(); foreach (string versionString in version.GetComparableVersionStrings()) { try { var packages = query.Where(p => p.Id == packageId && p.Version == versionString).ToArray(); Debug.Assert(packages == null || packages.Length <= 1); if (packages.Length != 0) { return packages[0]; } } catch (DataServiceQueryException) { // DataServiceQuery exception will occur when the (id, version) // combination doesn't exist. } } return null; } public IEnumerable<IPackage> FindPackagesById(string packageId) { try { if (!Context.SupportsServiceMethod(FindPackagesByIdSvcMethod)) { // If there's no search method then we can't filter by target framework return PackageRepositoryExtensions.FindPackagesByIdCore(this, packageId); } var serviceParameters = new Dictionary<string, object> { { "id", "'" + UrlEncodeOdataParameter(packageId) + "'" } }; // Create a query for the search service method var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters); return new SmartDataServiceQuery<DataServicePackage>(Context, query); } catch (Exception ex) { var message = string.Format( CultureInfo.CurrentCulture, NuGetResources.ErrorLoadingPackages, _httpClient.OriginalUri, ex.Message); throw new InvalidOperationException(message, ex); } } public IEnumerable<IPackage> GetUpdates( IEnumerable<IPackageName> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFrameworks, IEnumerable<IVersionSpec> versionConstraints) { if (!Context.SupportsServiceMethod(GetUpdatesSvcMethod)) { // If there's no search method then we can't filter by target framework return PackageRepositoryExtensions.GetUpdatesCore(this, packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints); } // Pipe all the things! string ids = String.Join("|", packages.Select(p => p.Id)); string versions = String.Join("|", packages.Select(p => p.Version.ToString())); string targetFrameworksValue = targetFrameworks.IsEmpty() ? "" : String.Join("|", targetFrameworks.Select(VersionUtility.GetShortFrameworkName)); string versionConstraintsValue = versionConstraints.IsEmpty() ? "" : String.Join("|", versionConstraints.Select(v => v == null ? "" : v.ToString())); var serviceParameters = new Dictionary<string, object> { { "packageIds", "'" + ids + "'" }, { "versions", "'" + versions + "'" }, { "includePrerelease", ToLowerCaseString(includePrerelease) }, { "includeAllVersions", ToLowerCaseString(includeAllVersions) }, { "targetFrameworks", "'" + UrlEncodeOdataParameter(targetFrameworksValue) + "'" }, { "versionConstraints", "'" + UrlEncodeOdataParameter(versionConstraintsValue) + "'" } }; var query = Context.CreateQuery<DataServicePackage>(GetUpdatesSvcMethod, serviceParameters); return new SmartDataServiceQuery<DataServicePackage>(Context, query); } public IPackageRepository Clone() { return new DataServicePackageRepository(_httpClient, _packageDownloader); } public IDisposable StartOperation(string operation, string mainPackageId, string mainPackageVersion) { Tuple<string, string, string> oldOperation = _currentOperation; _currentOperation = Tuple.Create(operation, mainPackageId, mainPackageVersion); return new DisposableAction(() => { _currentOperation = oldOperation; }); } public bool TryFindLatestPackageById(string id, out SemanticVersion latestVersion) { latestVersion = null; try { var serviceParameters = new Dictionary<string, object> { { "id", "'" + UrlEncodeOdataParameter(id) + "'" } }; // Create a query for the search service method var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters); var packages = (IQueryable<DataServicePackage>)query.AsQueryable(); var latestPackage = packages.Where(p => p.IsLatestVersion) .Select(p => new { p.Id, p.Version }) .FirstOrDefault(); if (latestPackage != null) { latestVersion = new SemanticVersion(latestPackage.Version); return true; } } catch (DataServiceQueryException) { } return false; } public bool TryFindLatestPackageById(string id, bool includePrerelease, out IPackage package) { try { var serviceParameters = new Dictionary<string, object> { { "id", "'" + UrlEncodeOdataParameter(id) + "'" } }; // Create a query for the search service method var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters); var packages = (IQueryable<DataServicePackage>)query.AsQueryable(); if (includePrerelease) { package = packages.Where(p => p.IsAbsoluteLatestVersion).FirstOrDefault(); } else { package = packages.Where(p => p.IsLatestVersion).FirstOrDefault(); } return package != null; } catch (DataServiceQueryException) { package = null; return false; } } private static string UrlEncodeOdataParameter(string value) { if (!String.IsNullOrEmpty(value)) { // OData requires that a single quote MUST be escaped as 2 single quotes. // In .NET 4.5, Uri.EscapeDataString() escapes single quote as %27. Thus we must replace %27 with 2 single quotes. // In .NET 4.0, Uri.EscapeDataString() doesn't escape single quote. Thus we must replace it with 2 single quotes. return Uri.EscapeDataString(value).Replace("'", "''").Replace("%27", "''"); } return value; } [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "OData expects a lower case value.")] private static string ToLowerCaseString(bool value) { return value.ToString().ToLowerInvariant(); } public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { if (managerType == typeof(SendingRequestEventManager)) { OnPackageDownloaderSendingRequest(sender, (WebRequestEventArgs)e); return true; } else { return false; } } } }
/* * Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ using System; using System.Collections; using System.IO; using System.Text; using PrototypeManager = org.javarosa.core.services.PrototypeManager; using OrderedMap = org.javarosa.core.util.OrderedHashtable; using System.Collections.Generic; using org.javarosa.core.model; namespace org.javarosa.core.util.externalizable { public class ExtUtil { public static byte[] serialize(Object o) { System.IO.MemoryStream baos = new System.IO.MemoryStream(); try { write(new System.IO.BinaryWriter(baos), o); } catch (IOException ioe) { throw new SystemException("IOException writing to ByteArrayOutputStream; shouldn't happen!"); } return (byte[])(Array)baos.ToArray(); } public static System.Object deserialize(sbyte[] data, System.Type type) { System.IO.MemoryStream bais = new System.IO.MemoryStream((byte[])(Array)data); try { return read(new System.IO.BinaryReader(bais), type); } catch (System.IO.EndOfStreamException eofe) { throw new DeserializationException("Unexpectedly reached end of stream when deserializing"); } catch (System.IO.IOException udfe) { throw new DeserializationException("Unexpectedly reached end of stream when deserializing"); } finally { try { bais.Close(); } catch (System.IO.IOException e) { //already closed. Don't sweat it } } } public static System.Object deserialize(sbyte[] data, ExternalizableWrapper ew) { System.IO.MemoryStream bais = new System.IO.MemoryStream((byte[])(Array)data); try { return read(new System.IO.BinaryReader(bais), ew); } catch (System.IO.EndOfStreamException eofe) { throw new DeserializationException("Unexpectedly reached end of stream when deserializing"); } catch (System.IO.IOException udfe) { throw new DeserializationException("Unexpectedly reached end of stream when deserializing"); } finally { try { bais.Close(); } catch (System.IO.IOException e) { //already closed. Don't sweat it } } } public static int getSize(Object o) { return serialize(o).Length; } public static PrototypeFactory defaultPrototypes() { return PrototypeManager.Default; } public static void write(System.IO.BinaryWriter out_Renamed, System.Object data) { if (data is Externalizable) { ((Externalizable)data).writeExternal(out_Renamed); } else if (data is System.SByte) { writeNumeric(out_Renamed, (sbyte)((System.SByte)data)); } else if (data is System.Int16) { writeNumeric(out_Renamed, (short)((System.Int16)data)); } else if (data is System.Int32) { writeNumeric(out_Renamed, ((System.Int32)data)); } else if (data is System.Int64) { writeNumeric(out_Renamed, (long)((System.Int64)data)); } else if (data is System.Char) { writeChar(out_Renamed, ((System.Char)data)); } else if (data is System.Single) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" writeDecimal(out_Renamed, (float)((System.Single)data)); } else if (data is System.Double) { writeDecimal(out_Renamed, ((System.Double)data)); } else if (data is System.Boolean) { writeBool(out_Renamed, ((System.Boolean)data)); } else if (data is System.String) { writeString(out_Renamed, (System.String)data); } else if (data is System.DateTime) { //UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'" writeDate(out_Renamed, ref new System.DateTime[] { (System.DateTime)data }[0]); } else if (data is sbyte[]) { writeBytes(out_Renamed, (sbyte[])data); } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Class.getName' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new System.InvalidCastException("Not a serializable datatype: " + data.GetType().FullName); } } public static void writeNumeric(System.IO.BinaryWriter out_Renamed, long val) { writeNumeric(out_Renamed, val, new ExtWrapIntEncodingUniform()); } //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'" public static void writeNumeric(System.IO.BinaryWriter out_Renamed, long val, ExtWrapIntEncoding encoding) { write(out_Renamed, encoding.clone((System.Object)val)); } //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'" public static void writeChar(System.IO.BinaryWriter out_Renamed, char val) { out_Renamed.Write((System.Char)val); } //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'" public static void writeDecimal(System.IO.BinaryWriter out_Renamed, double val) { out_Renamed.Write(val); } //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'" public static void writeBool(System.IO.BinaryWriter out_Renamed, bool val) { out_Renamed.Write(val); } public static void writeString(System.IO.BinaryWriter out_Renamed, System.String val) { //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.writeUTF' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioDataOutputStreamwriteUTF_javalangString'" out_Renamed.Write(val); //we could easily come up with more efficient default encoding for string } public static void writeDate(System.IO.BinaryWriter out_Renamed, ref System.DateTime val) { //UPGRADE_TODO: Method 'java.util.Date.getTime' was converted to 'System.DateTime.Ticks' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilDategetTime'" writeNumeric(out_Renamed, val.Ticks); //time zone? } //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'" public static void writeBytes(System.IO.BinaryWriter out_Renamed, sbyte[] bytes) { ExtUtil.writeNumeric(out_Renamed, bytes.Length); if (bytes.Length > 0) //i think writing zero-length array might close the stream out_Renamed.Write((byte[])(Array)bytes); } //functions like these are bad; they should use the built-in list serialization facilities //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'" public static void writeInts(System.IO.BinaryWriter out_Renamed, int[] ints) { ExtUtil.writeNumeric(out_Renamed, ints.Length); foreach (int i in ints) { ExtUtil.writeNumeric(out_Renamed, i); } } public static Object read(System.IO.BinaryReader in_Renamed, System.Type type) { return read(in_Renamed, type, null); } public static System.Object read(System.IO.BinaryReader in_Renamed, System.Type type, PrototypeFactory pf) { if (typeof(Externalizable).IsAssignableFrom(type)) { Externalizable ext = (Externalizable)PrototypeFactory.getInstance(type); ext.readExternal(in_Renamed, pf == null ? defaultPrototypes() : pf); return ext; } else if (type == typeof(System.SByte)) { return (sbyte)readByte(in_Renamed); } else if (type == typeof(System.Int16)) { return (short)readShort(in_Renamed); } else if (type == typeof(System.Int32)) { return (System.Int32)readInt(in_Renamed); } else if (type == typeof(System.Int64)) { return (long)readNumeric(in_Renamed); } else if (type == typeof(System.Char)) { return readChar(in_Renamed); } else if (type == typeof(System.Single)) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (float)readDecimal(in_Renamed); } else if (type == typeof(System.Double)) { return (double)readDecimal(in_Renamed); } else if (type == typeof(System.Boolean)) { return readBool(in_Renamed); } else if (type == typeof(System.String)) { return readString(in_Renamed); } else if (type == typeof(System.DateTime)) { return readDate(in_Renamed); } else if (type == typeof(sbyte[])) { return readBytes(in_Renamed); } else { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Class.getName' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new System.InvalidCastException("Not a deserializable datatype: " + type.FullName); } } public static Object read(BinaryReader in_r, ExternalizableWrapper ew) { return read(in_r, ew, null); } public static Object read(BinaryReader in_r, ExternalizableWrapper ew, PrototypeFactory pf) { ew.readExternal(in_r, pf == null ? defaultPrototypes() : pf); return ew.val; } //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" public static long readNumeric(System.IO.BinaryReader in_Renamed) { return readNumeric(in_Renamed, new ExtWrapIntEncodingUniform()); } //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" public static long readNumeric(System.IO.BinaryReader in_Renamed, ExtWrapIntEncoding encoding) { try { return (long)((System.Int64)read(in_Renamed, encoding)); } catch (DeserializationException de) { throw new System.SystemException("Shouldn't happen: Base-type encoding wrappers should never touch prototypes"); } } public static int readInt(BinaryReader in_r) { return toInt(readNumeric(in_r)); } public static short readShort(BinaryReader in_r) { return toShort(readNumeric(in_r)); } public static byte readByte(BinaryReader in_r) { return toByte(readNumeric(in_r)); } //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" public static char readChar(System.IO.BinaryReader in_Renamed) { return in_Renamed.ReadChar(); } //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" public static double readDecimal(System.IO.BinaryReader in_Renamed) { return in_Renamed.ReadDouble(); } //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" public static bool readBool(System.IO.BinaryReader in_Renamed) { return in_Renamed.ReadBoolean(); } //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" public static System.String readString(System.IO.BinaryReader in_Renamed) { //UPGRADE_ISSUE: Method 'java.io.DataInputStream.readUTF' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioDataInputStreamreadUTF'" System.String s = in_Renamed.ReadString(); return s; } //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" public static System.DateTime readDate(System.IO.BinaryReader in_Renamed) { //UPGRADE_TODO: Constructor 'java.util.Date.Date' was converted to 'System.DateTime.DateTime' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilDateDate_long'" return new System.DateTime(readNumeric(in_Renamed)); //time zone? } //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'" public static sbyte[] readBytes(System.IO.BinaryReader in_Renamed) { int size = (int)ExtUtil.readNumeric(in_Renamed); sbyte[] bytes = new sbyte[size]; int read = 0; int toread = size; while (read != size) { read = in_Renamed.Read((byte[])(Array)bytes, 0, toread); toread -= read; } return bytes; } //bad public static int[] readInts(BinaryReader in_r) { int size = (int)ExtUtil.readNumeric(in_r); int[] ints = new int[size]; for (int i = 0; i < size; ++i) { ints[i] = (int)ExtUtil.readNumeric(in_r); } return ints; } public static int toInt(long l) { if (l < int.MinValue || l > int.MaxValue) throw new ArithmeticException("Value (" + l + ") cannot fit into int"); return (int)l; } public static short toShort(long l) { if (l < short.MinValue || l > short.MaxValue) throw new ArithmeticException("Value (" + l + ") cannot fit into short"); return (short)l; } public static byte toByte(long l) { if (l < byte.MinValue || l > byte.MaxValue) throw new ArithmeticException("Value (" + l + ") cannot fit into byte"); return (byte)l; } public static long toLong(System.Object o) { if (o is System.SByte) { return (sbyte)((System.SByte)o); } else if (o is System.Int16) { return (short)((System.Int16)o); } else if (o is System.Int32) { return ((System.Int32)o); } else if (o is System.Int64) { return (long)((System.Int64)o); } else if (o is System.Char) { return ((System.Char)o); } else { throw new System.InvalidCastException(); } } public static byte[] nullIfEmpty(byte[] ba) { return (ba == null ? null : (ba.Length == 0 ? null : ba)); } public static String nullIfEmpty(String s) { return (s == null ? null : (s.Length == 0 ? null : s)); } public static ArrayList nullIfEmpty(ArrayList v) { return (v == null ? null : (v.Count == 0 ? null : v)); } public static List<SelectChoice> nullIfEmpty(List<SelectChoice> v) { return (v == null ? null : (v.Count == 0 ? null : v)); } public static Hashtable nullIfEmpty(Hashtable h) { return (h == null ? null : (h.Count == 0 ? null : h)); } public static byte[] emptyIfNull(byte[] ba) { return ba == null ? new byte[0] : ba; } public static String emptyIfNull(String s) { return s == null ? "" : s; } public static ArrayList emptyIfNull(ArrayList v) { return v == null ? new ArrayList() : v; } public static List<SelectChoice> emptyIfNull( List<SelectChoice> v) { return v == null ? new List<SelectChoice>() : v; } /*public static List<SelectChoice> emptyIfNull(List<SelectChoice> v) { return v == null ? new List<SelectChoice>() : v; }*/ public static Hashtable emptyIfNull(Hashtable h) { return h == null ? new Hashtable() : h; } public static Object unwrap(Object o) { return (o is ExternalizableWrapper ? ((ExternalizableWrapper)o).baseValue() : o); } public static Boolean Equals(Object a, Object b) { a = unwrap(a); b = unwrap(b); if (a == null) { return b == null; } else if (a is ArrayList) { return (b is ArrayList && vectorEquals((ArrayList)a, (ArrayList)b)); } else if (a is Hashtable) { return (b is Hashtable && hashtableEquals((Hashtable)a, (Hashtable)b)); } else { return a.Equals(b); } } public static Boolean vectorEquals(ArrayList a, ArrayList b) { if (a.Count != b.Count) { return false; } else { for (int i = 0; i < a.Count; i++) { if (!Equals(a[i], b[i])) { return false; } } return true; } } public static Boolean arrayEquals(Object[] a, Object[] b) { if (a.Length != b.Length) { return false; } else { for (int i = 0; i < a.Length; i++) { if (!Equals(a[i], b[i])) { return false; } } return true; } } public static Boolean hashtableEquals(Hashtable a, Hashtable b) { if (a.Count != b.Count) { return false; } else if (a is OrderedHashtable != b is OrderedHashtable) { return false; } else { for (IEnumerator ea = a.GetEnumerator(); ea.MoveNext(); ) { if (!Equals(a[ea], b[ea])) { return false; } } if (a is OrderedHashtable && b is OrderedHashtable) { IEnumerator ea = a.GetEnumerator(); IEnumerator eb = b.GetEnumerator(); while (ea.MoveNext()) { Object keyA = ea; Object keyB = eb.MoveNext(); if (!keyA.Equals(keyB)) { //must use built-in equals for keys, as that's what hashtable uses return false; } } } return true; } } public static String printBytes(byte[] data) { StringBuilder sb = new StringBuilder(); sb.Append("["); for (int i = 0; i < data.Length; i++) { String hex = data[i].ToString("X8"); if (hex.Length == 1) hex = "0" + hex; else hex = hex.Substring(hex.Length - 2); sb.Append(hex); if (i < data.Length - 1) { if ((i + 1) % 30 == 0) sb.Append("\n "); else if ((i + 1) % 10 == 0) sb.Append(" "); else sb.Append(" "); } } sb.Append("]"); return sb.ToString(); } } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_148 : MapLoop { public M_148() : base(null) { Content.AddRange(new MapBaseEntity[] { new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_NM1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_HL(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } //1000 public class L_NM1 : MapLoop { public L_NM1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new ACT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, }); } } //2000 public class L_HL : MapLoop { public L_HL(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new HL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new ACT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new FC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CRI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new EMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CRC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new VEH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NM1_1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999 }, new L_ESI(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 }, new L_LN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, new L_III(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_AD1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, }); } } //2100 public class L_NM1_1 : MapLoop { public L_NM1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new ACT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2200 public class L_ESI : MapLoop { public L_ESI(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ESI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CRC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new L_AIN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 }, }); } } //2210 public class L_AIN : MapLoop { public L_AIN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AIN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new WS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, }); } } //2300 public class L_LN : MapLoop { public L_LN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_VEH(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_AMT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 }, new L_NM1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2310 public class L_VEH : MapLoop { public L_VEH(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new VEH() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2320 public class L_AMT : MapLoop { public L_AMT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2330 public class L_NM1_2 : MapLoop { public L_NM1_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2400 public class L_III : MapLoop { public L_III(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new III() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new IMP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 6 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CRC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NM1_3(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, }); } } //2410 public class L_LM : MapLoop { public L_LM(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2420 public class L_NM1_3 : MapLoop { public L_NM1_3(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new ACT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2500 public class L_AD1 : MapLoop { public L_AD1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AD1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 30 }, new L_NM1_4(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 }, }); } } //2510 public class L_NM1_4 : MapLoop { public L_NM1_4(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new ACT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 }, }); } } //3000 public class L_LX : MapLoop { public L_LX(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 }, }); } } } }
//------------------------------------------------------------------------------ // <copyright file="WinInetCache.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.Win32 { using System; using System.Net; using System.Net.Cache; using System.Globalization; using System.IO; using System.Threading; using System.Collections.Specialized; using System.Security.Permissions; using System.Security.Principal; using System.ComponentModel; using System.Text; using System.Runtime.Versioning; using System.Diagnostics; // The class implements a RequestCache class contract on top of WinInet provider // Author: Alexei Vopilov 21-Dec-2002 // // Revision History: // // Jan 25 2004 - Changed the visibility of the class from public to internal. internal class WinInetCache: RequestCache { private const int _MaximumResponseHeadersLength = Int32.MaxValue; private bool async; internal const string c_SPARSE_ENTRY_HACK = "~SPARSE_ENTRY:"; private readonly static DateTime s_MinDateTimeUtcForFileTimeUtc = DateTime.FromFileTimeUtc(0L); internal readonly static TimeSpan s_MaxTimeSpanForInt32 = TimeSpan.FromSeconds((double)int.MaxValue); // private static readonly RequestCachePermission s_ReadPermission = new RequestCachePermission(RequestCacheActions.CacheRead); // private static readonly RequestCachePermission s_ReadWritePermission = new RequestCachePermission(RequestCacheActions.CacheReadWrite); /// <summary> A public constructor that demands CacheReadWrite flag for RequestCachePermission </summary> internal WinInetCache(bool isPrivateCache, bool canWrite, bool async): base (isPrivateCache, canWrite) { /*********** if (canWrite) { s_ReadWritePermission.Demand(); } else { s_ReadPermission.Demand(); } ***********/ // Per VsWhidbey#88276 it was decided to not enforce any cache metadata limits for WinInet cache provider. // ([....] 7/17 made this a const to avoid threading issues) //_MaximumResponseHeadersLength = Int32.MaxValue; this.async = async; /******** if (_MaximumResponseHeadersLength == 0) { NetConfiguration config = (NetConfiguration)System.Configuration.ConfigurationManager.GetSection("system.net/settings"); if (config != null) { if (config.maximumResponseHeadersLength < 0 && config.maximumResponseHeadersLength != -1) { throw new ArgumentOutOfRangeException(SR.GetString(SR.net_toosmall)); } _MaximumResponseHeadersLength = config.maximumResponseHeadersLength * 1024; } else { _MaximumResponseHeadersLength = 64 * 1024; } } ********/ } /// <summary> /// <para> /// Gets the data stream and the metadata associated with a IE cache entry. /// Returns Stream.Null if there is no entry found. /// </para> /// </summary> internal override Stream Retrieve(string key, out RequestCacheEntry cacheEntry) { return Lookup(key, out cacheEntry, true); } // internal override bool TryRetrieve(string key, out RequestCacheEntry cacheEntry, out Stream readStream) { readStream = Lookup(key, out cacheEntry, false); if (readStream == null) { return false; } return true; } // Returns a write stream associated with the IE cache string Key. // Passed parameters allow cache to update an entry metadata accordingly. // <remarks> The commit operation will happen upon the stream closure. </remarks> internal override Stream Store(string key, long contentLength, DateTime expiresUtc, DateTime lastModifiedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata) { return GetWriteStream(key, contentLength, expiresUtc, lastModifiedUtc, maxStale, entryMetadata, systemMetadata, true); } // Does not throw on an error internal override bool TryStore(string key, long contentLength, DateTime expiresUtc, DateTime lastModifiedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata, out Stream writeStream) { writeStream = GetWriteStream(key, contentLength, expiresUtc, lastModifiedUtc, maxStale, entryMetadata, systemMetadata, false); if (writeStream == null) { return false; } return true; } /// <summary> /// <para> /// Removes an item from the IE cache. Throws Win32Excpetion if failed /// </para> /// </summary> internal override void Remove(string key) { if (key == null) { throw new ArgumentNullException("key"); } if (!CanWrite) { if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_operation_failed_with_error, "WinInetCache.Remove()", SR.GetString(SR.net_cache_access_denied, "Write"))); return ; } _WinInetCache.Entry entry = new _WinInetCache.Entry(key, _MaximumResponseHeadersLength); if (_WinInetCache.Remove(entry) != _WinInetCache.Status.Success && entry.Error != _WinInetCache.Status.FileNotFound) { Win32Exception win32Exception = new Win32Exception((int)entry.Error); if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_cannot_remove, "WinInetCache.Remove()", key, win32Exception.Message)); throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, win32Exception.Message), win32Exception); } if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_key_status, "WinInetCache.Remove(), ", key, entry.Error.ToString())); } // // Tries to remove an item from the cache, possible by applying unsafe entry unlocking. // Returns true if successful, false otherwise internal override bool TryRemove(string key) { return TryRemove(key, false); } // // Purges Wininet Cache Entry by Unlocking it's file until zero count (if forceRemove is set). // internal bool TryRemove(string key, bool forceRemove) { if (key == null) { throw new ArgumentNullException("key"); } if (!CanWrite) { if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_operation_failed_with_error, "WinInetCache.TryRemove()", SR.GetString(SR.net_cache_access_denied, "Write"))); return false; } _WinInetCache.Entry entry = new _WinInetCache.Entry(key, _MaximumResponseHeadersLength); if (_WinInetCache.Remove(entry) == _WinInetCache.Status.Success || entry.Error == _WinInetCache.Status.FileNotFound) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_key_status, "WinInetCache.TryRemove()", key, entry.Error.ToString())); return true; } else if (!forceRemove) { if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_key_remove_failed_status, "WinInetCache.TryRemove()", key, entry.Error.ToString())); return false; } _WinInetCache.Status status = _WinInetCache.LookupInfo(entry); if (status == _WinInetCache.Status.Success) { while (entry.Info.UseCount != 0) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_key_status, "WinInetCache.TryRemove()", key, entry.Error.ToString())); if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_usecount_file, "WinInetCache.TryRemove()", entry.Info.UseCount, entry.Filename)); if (!UnsafeNclNativeMethods.UnsafeWinInetCache.UnlockUrlCacheEntryFileW(key, 0)) { break; } status = _WinInetCache.LookupInfo(entry); } } _WinInetCache.Remove(entry); if (entry.Error != _WinInetCache.Status.Success && _WinInetCache.LookupInfo(entry) == _WinInetCache.Status.FileNotFound) { entry.Error = _WinInetCache.Status.Success; } if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_key_status, "WinInetCache.TryRemove()", key, entry.Error.ToString())); return entry.Error == _WinInetCache.Status.Success; } /// <summary> /// <para> /// Updates only the metadata associated with IE cached entry. /// </para> /// </summary> internal override void Update(string key, DateTime expiresUtc, DateTime lastModifiedUtc, DateTime lastSynchronizedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata) { UpdateInfo(key, expiresUtc, lastModifiedUtc, lastSynchronizedUtc, maxStale, entryMetadata, systemMetadata, true); } // Does not throw on an error internal override bool TryUpdate(string key, DateTime expiresUtc, DateTime lastModifiedUtc, DateTime lastSynchronizedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata) { return UpdateInfo(key, expiresUtc, lastModifiedUtc, lastSynchronizedUtc, maxStale, entryMetadata, systemMetadata, false); } // // Once the entry is unlocked it must not be updated // There is a design flaw in current RequestCache contract, it should allow detection of already replaced entry when updating one. // internal override void UnlockEntry(Stream stream) { ReadStream readStream = stream as ReadStream; if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_stream, "WinInetCache.UnlockEntry", (stream == null ? "<null>" : stream.GetType().FullName))); // could be wrapped by some other stream, that's ok because the entry is unlocked on stream.Close anyway if (readStream == null) return; readStream.UnlockEntry(); } // // // private Stream Lookup(string key, out RequestCacheEntry cacheEntry, bool isThrow) { if(Logging.On) Logging.Enter(Logging.RequestCache, "WinInetCache.Retrieve", "key = " + key); if (key == null) { throw new ArgumentNullException("key"); } Stream result = Stream.Null; SafeUnlockUrlCacheEntryFile handle = null; _WinInetCache.Entry entry = new _WinInetCache.Entry(key, _MaximumResponseHeadersLength); try { handle = _WinInetCache.LookupFile(entry); if (entry.Error == _WinInetCache.Status.Success) { if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_filename, "WinInetCache.Retrieve()", entry.Filename, entry.Error)); cacheEntry = new RequestCacheEntry(entry, IsPrivateCache); if (entry.MetaInfo != null && entry.MetaInfo.Length != 0) { // convert metadata to upto two string collections unsafe { int start = 0; int length = entry.MetaInfo.Length; StringCollection sc = new StringCollection(); fixed (char * ch = entry.MetaInfo) { int i; for (i = 0; i < length; ++i) { // WinInet specific block!! // The point here is that wininet scans for ~U: throughly with no regard to \r\n so we mimic the same behavior if (i == start && i+2 < length) { if (ch[i] == '~' && (ch[i+1] == 'U' || ch[i+1] == 'u') && ch[i+2] == ':') { //Security: don't report what the username is while(i < length && ch[++i] != '\n') {;} start = i+1; continue; } } // note a metadata entry must terminate with \r\n if ((i+1 == length) || (ch[i] == '\n')) { string value = entry.MetaInfo.Substring(start, (ch[i-1] == '\r'? (i-1):(i+1)) - start); if (value.Length == 0 && cacheEntry.EntryMetadata == null) { // done with headers, prepare for system metadata cacheEntry.EntryMetadata = sc; sc = new StringCollection(); } else { //WinInet specific block!! // HACK: if we are parsing system metadata and have found our hack, // then convert it to a sparse entry type (entry.Info.EntryType & _WinInetCache.EntryType.Sparse) if (cacheEntry.EntryMetadata != null && value.StartsWith(c_SPARSE_ENTRY_HACK, StringComparison.Ordinal)) cacheEntry.IsPartialEntry = true; else sc.Add(value); } start = i+1; } } } if (cacheEntry.EntryMetadata == null ) {cacheEntry.EntryMetadata = sc;} else {cacheEntry.SystemMetadata = sc;} } } result = new ReadStream(entry, handle, async); } else { if (handle != null) { handle.Close(); } cacheEntry = new RequestCacheEntry(); cacheEntry.IsPrivateEntry = IsPrivateCache; if (entry.Error != _WinInetCache.Status.FileNotFound) { if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_lookup_failed, "WinInetCache.Retrieve()", new Win32Exception((int)entry.Error).Message)); if(Logging.On)Logging.Exit(Logging.RequestCache, "WinInetCache.Retrieve()"); if(isThrow) { Win32Exception win32Exception = new Win32Exception((int)entry.Error); throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, win32Exception.Message), win32Exception); } return null; } } } catch (Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_exception, "WinInetCache.Retrieve()", exception.ToString())); if(Logging.On)Logging.Exit(Logging.RequestCache, "WinInetCache.Retrieve()"); if (handle != null) { handle.Close(); } result.Close(); result = Stream.Null; cacheEntry = new RequestCacheEntry(); cacheEntry.IsPrivateEntry = IsPrivateCache; if (isThrow) { throw; } return null; } if(Logging.On)Logging.Exit(Logging.RequestCache, "WinInetCache.Retrieve()", "Status = " + entry.Error.ToString()); return result; } // // // private string CombineMetaInfo(StringCollection entryMetadata, StringCollection systemMetadata) { if ((entryMetadata == null || entryMetadata.Count == 0) && (systemMetadata == null || systemMetadata.Count == 0)) return string.Empty; StringBuilder sb = new StringBuilder(100); int i; if (entryMetadata != null && entryMetadata.Count != 0) for (i = 0; i < entryMetadata.Count; ++i) { if (entryMetadata[i] == null || entryMetadata[i].Length == 0) continue; sb.Append(entryMetadata[i]).Append("\r\n"); } if (systemMetadata != null && systemMetadata.Count != 0) { // mark a start for system metadata sb.Append("\r\n"); for (i = 0; i < systemMetadata.Count; ++i) { if (systemMetadata[i] == null || systemMetadata[i].Length == 0) continue; sb.Append(systemMetadata[i]).Append("\r\n");} } return sb.ToString(); } // // private Stream GetWriteStream(string key, long contentLength, DateTime expiresUtc, DateTime lastModifiedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata, bool isThrow) { if(Logging.On) Logging.Enter(Logging.RequestCache, "WinInetCache.Store()", "Key = " + key); if (key == null) { throw new ArgumentNullException("key"); } if (!CanWrite) { if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_operation_failed_with_error, "WinInetCache.Store()", SR.GetString(SR.net_cache_access_denied, "Write"))); if(Logging.On) Logging.Exit(Logging.RequestCache, "WinInetCache.Store"); if(isThrow) { throw new InvalidOperationException(SR.GetString(SR.net_cache_access_denied, "Write")); } return null; } _WinInetCache.Entry entry = new _WinInetCache.Entry(key, _MaximumResponseHeadersLength); entry.Key = key; entry.OptionalLength = (contentLength < 0L)? 0: contentLength > Int32.MaxValue? Int32.MaxValue: (int)(contentLength); entry.Info.ExpireTime = _WinInetCache.FILETIME.Zero; if (expiresUtc != DateTime.MinValue && expiresUtc > s_MinDateTimeUtcForFileTimeUtc) { entry.Info.ExpireTime = new _WinInetCache.FILETIME(expiresUtc.ToFileTimeUtc()); } entry.Info.LastModifiedTime = _WinInetCache.FILETIME.Zero; if (lastModifiedUtc != DateTime.MinValue && lastModifiedUtc > s_MinDateTimeUtcForFileTimeUtc) { entry.Info.LastModifiedTime = new _WinInetCache.FILETIME(lastModifiedUtc.ToFileTimeUtc()); } entry.Info.EntryType = _WinInetCache.EntryType.NormalEntry; if (maxStale > TimeSpan.Zero) { if (maxStale >= s_MaxTimeSpanForInt32) { maxStale = s_MaxTimeSpanForInt32; } entry.Info.U.ExemptDelta = (int)maxStale.TotalSeconds; entry.Info.EntryType = _WinInetCache.EntryType.StickyEntry; } entry.MetaInfo = CombineMetaInfo(entryMetadata, systemMetadata); entry.FileExt = "cache"; if(Logging.On) { Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_expected_length, entry.OptionalLength)); Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_last_modified, (entry.Info.LastModifiedTime.IsNull? "0": DateTime.FromFileTimeUtc(entry.Info.LastModifiedTime.ToLong()).ToString("r")))); Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_expires, (entry.Info.ExpireTime.IsNull? "0": DateTime.FromFileTimeUtc(entry.Info.ExpireTime.ToLong()).ToString("r")))); Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_max_stale, (maxStale > TimeSpan.Zero? ((int)maxStale.TotalSeconds).ToString():"n/a"))); if (Logging.IsVerbose(Logging.RequestCache)) { Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_dumping_metadata)); if (entry.MetaInfo.Length == 0) { Logging.PrintInfo(Logging.RequestCache, "<null>"); } else { if (entryMetadata != null) { foreach (string s in entryMetadata) { Logging.PrintInfo(Logging.RequestCache, s.TrimEnd(LineSplits)); } } Logging.PrintInfo(Logging.RequestCache, "------"); if (systemMetadata != null) { foreach (string s in systemMetadata) { Logging.PrintInfo(Logging.RequestCache, s.TrimEnd(LineSplits)); } } } } } _WinInetCache.CreateFileName(entry); Stream result = Stream.Null; if (entry.Error != _WinInetCache.Status.Success) { if(Logging.On) { Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_create_failed, new Win32Exception((int)entry.Error).Message)); Logging.Exit(Logging.RequestCache, "WinInetCache.Store"); } if (isThrow) { Win32Exception win32Exception = new Win32Exception((int)entry.Error); throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, win32Exception.Message), win32Exception); } return null; } try { result = new WriteStream(entry, isThrow, contentLength, async); } catch (Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } if(Logging.On) { Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_exception, "WinInetCache.Store()", exception)); Logging.Exit(Logging.RequestCache, "WinInetCache.Store"); } if (isThrow) { throw; } return null; } if(Logging.On) Logging.Exit(Logging.RequestCache, "WinInetCache.Store", "Filename = " + entry.Filename); return result; } // // private bool UpdateInfo(string key, DateTime expiresUtc, DateTime lastModifiedUtc, DateTime lastSynchronizedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata, bool isThrow) { if (key == null) { throw new ArgumentNullException("key"); } if(Logging.On) Logging.Enter(Logging.RequestCache, "WinInetCache.Update", "Key = "+ key); if (!CanWrite) { if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_operation_failed_with_error, "WinInetCache.Update()", SR.GetString(SR.net_cache_access_denied, "Write"))); if(Logging.On) Logging.Exit(Logging.RequestCache, "WinInetCache.Update()"); if(isThrow) { throw new InvalidOperationException(SR.GetString(SR.net_cache_access_denied, "Write")); } return false; } _WinInetCache.Entry entry = new _WinInetCache.Entry(key, _MaximumResponseHeadersLength); _WinInetCache.Entry_FC attributes = _WinInetCache.Entry_FC.None; if (expiresUtc != DateTime.MinValue && expiresUtc > s_MinDateTimeUtcForFileTimeUtc) { attributes |= _WinInetCache.Entry_FC.Exptime; entry.Info.ExpireTime = new _WinInetCache.FILETIME(expiresUtc.ToFileTimeUtc()); if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_set_expires, expiresUtc.ToString("r"))); } if (lastModifiedUtc != DateTime.MinValue && lastModifiedUtc > s_MinDateTimeUtcForFileTimeUtc) { attributes |= _WinInetCache.Entry_FC.Modtime; entry.Info.LastModifiedTime = new _WinInetCache.FILETIME(lastModifiedUtc.ToFileTimeUtc()); if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_set_last_modified, lastModifiedUtc.ToString("r"))); } if (lastSynchronizedUtc != DateTime.MinValue && lastSynchronizedUtc > s_MinDateTimeUtcForFileTimeUtc) { attributes |= _WinInetCache.Entry_FC.Synctime; entry.Info.LastSyncTime = new _WinInetCache.FILETIME(lastSynchronizedUtc.ToFileTimeUtc()); if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_set_last_synchronized, lastSynchronizedUtc.ToString("r"))); } if (maxStale != TimeSpan.MinValue) { attributes |= _WinInetCache.Entry_FC.ExemptDelta|_WinInetCache.Entry_FC.Attribute; entry.Info.EntryType = _WinInetCache.EntryType.NormalEntry; if (maxStale >= TimeSpan.Zero) { if (maxStale >= s_MaxTimeSpanForInt32) { maxStale = s_MaxTimeSpanForInt32; } entry.Info.EntryType = _WinInetCache.EntryType.StickyEntry; entry.Info.U.ExemptDelta = (int)maxStale.TotalSeconds; if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_enable_max_stale, ((int)maxStale.TotalSeconds).ToString())); } else { entry.Info.U.ExemptDelta = 0; if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_disable_max_stale)); } } entry.MetaInfo = CombineMetaInfo(entryMetadata, systemMetadata); if (entry.MetaInfo.Length != 0) { attributes |= _WinInetCache.Entry_FC.Headerinfo; if(Logging.On) { Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_dumping)); if (Logging.IsVerbose(Logging.RequestCache)) { Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_dumping)); if (entryMetadata != null) { foreach (string s in entryMetadata) { Logging.PrintInfo(Logging.RequestCache, s.TrimEnd(LineSplits)); } } Logging.PrintInfo(Logging.RequestCache, "------"); if (systemMetadata != null) { foreach (string s in systemMetadata) { Logging.PrintInfo(Logging.RequestCache, s.TrimEnd(LineSplits)); } } } } } _WinInetCache.Update(entry, attributes) ; if (entry.Error != _WinInetCache.Status.Success) { if(Logging.On) { Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_update_failed, "WinInetCache.Update()", entry.Key, new Win32Exception((int)entry.Error).Message)); Logging.Exit(Logging.RequestCache, "WinInetCache.Update()"); } if (isThrow) { Win32Exception win32Exception = new Win32Exception((int)entry.Error); throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, win32Exception.Message), win32Exception); } return false; } if(Logging.On) Logging.Exit(Logging.RequestCache, "WinInetCache.Update()", "Status = " + entry.Error.ToString()); return true; } /// <summary> /// <para> /// This is a FileStream wrapper on top of WinInet cache entry. // The Close method will unlock the cached entry. /// </para> ///</summary> private class ReadStream: FileStream, ICloseEx, IRequestLifetimeTracker { private string m_Key; private int m_ReadTimeout; private int m_WriteTimeout; private SafeUnlockUrlCacheEntryFile m_Handle; private int m_Disposed; private int m_CallNesting; private ManualResetEvent m_Event; private bool m_Aborted; private RequestLifetimeSetter m_RequestLifetimeSetter; // // Construct a read stream out of WinInet given handle // [FileIOPermission(SecurityAction.Assert, Unrestricted=true)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal ReadStream(_WinInetCache.Entry entry, SafeUnlockUrlCacheEntryFile handle, bool async) : base(entry.Filename, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 4096, async) { m_Key = entry.Key; m_Handle = handle; m_ReadTimeout = m_WriteTimeout = System.Threading.Timeout.Infinite; } // // The stream will remain valid but after that call the entry can be replaced. // If the entry has been replaced then the physical file that this stream points to may be deleted on stream.Close() // internal void UnlockEntry() { m_Handle.Close(); } public override int Read(byte[] buffer, int offset, int count) { lock (m_Handle) { try { if (m_CallNesting != 0) throw new NotSupportedException(SR.GetString(SR.net_no_concurrent_io_allowed)); if (m_Aborted) throw ExceptionHelper.RequestAbortedException; if (m_Event != null) throw new ObjectDisposedException(GetType().FullName); m_CallNesting = 1; return base.Read(buffer, offset, count); } finally { m_CallNesting = 0; if (m_Event != null) m_Event.Set(); } } } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { lock (m_Handle) { if (m_CallNesting != 0) throw new NotSupportedException(SR.GetString(SR.net_no_concurrent_io_allowed)); if (m_Aborted) throw ExceptionHelper.RequestAbortedException; if (m_Event != null) throw new ObjectDisposedException(GetType().FullName); m_CallNesting = 1; try { return base.BeginRead(buffer, offset, count, callback, state); } catch { m_CallNesting = 0; throw; } } } public override int EndRead(IAsyncResult asyncResult) { lock (m_Handle) { try { return base.EndRead(asyncResult); } finally { m_CallNesting = 0; if (m_Event != null) try {m_Event.Set();} catch {} // the problem is he WaitHandle cannot tell if it is disposed or not } } } public void CloseEx(CloseExState closeState) { if ((closeState & CloseExState.Abort) != 0) m_Aborted = true; try { Close(); } catch { if ((closeState & CloseExState.Silent) == 0) throw; } } protected override void Dispose(bool disposing) { if (Interlocked.Exchange(ref m_Disposed, 1) == 0) { if (!disposing) { base.Dispose(false); } else { // if m_key is null, it means that the base constructor failed if (m_Key != null) { try { lock (m_Handle) { if (m_CallNesting == 0) base.Dispose(true); else m_Event = new ManualResetEvent(false); } RequestLifetimeSetter.Report(m_RequestLifetimeSetter); if (m_Event != null) { using (m_Event) { // This assumes that FileStream will never hang on read m_Event.WaitOne(); lock (m_Handle) { Debug.Assert(m_CallNesting == 0); } } base.Dispose(true); } } finally { if (Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_key, "WinInetReadStream.Close()", m_Key)); // note, the handle may have been closed earlier if CacheProtocol knew that cache metadata update will not happen. m_Handle.Close(); } } } } } public override bool CanTimeout { get { return true; } } public override int ReadTimeout { get { return m_ReadTimeout; } set { m_ReadTimeout = value; } } public override int WriteTimeout { get { return m_WriteTimeout; } set { m_WriteTimeout = value; } } void IRequestLifetimeTracker.TrackRequestLifetime(long requestStartTimestamp) { Debug.Assert(m_RequestLifetimeSetter == null, "TrackRequestLifetime called more than once."); m_RequestLifetimeSetter = new RequestLifetimeSetter(requestStartTimestamp); } } // // // private class WriteStream: FileStream, ICloseEx { private _WinInetCache.Entry m_Entry; private bool m_IsThrow; private long m_StreamSize; private bool m_Aborted; private int m_ReadTimeout; private int m_WriteTimeout; private int m_Disposed; private int m_CallNesting; private ManualResetEvent m_Event; private bool m_OneWriteSucceeded; [FileIOPermission(SecurityAction.Assert, Unrestricted=true)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal WriteStream(_WinInetCache.Entry entry, bool isThrow, long streamSize, bool async): base(entry.Filename, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, async) { m_Entry = entry; m_IsThrow = isThrow; m_StreamSize = streamSize; m_OneWriteSucceeded = streamSize == 0; //if 0 is expected or the lenght is unknonw we will commit even an emtpy stream. m_ReadTimeout = m_WriteTimeout = System.Threading.Timeout.Infinite; } // public override bool CanTimeout { get { return true; } } public override int ReadTimeout { get { return m_ReadTimeout; } set { m_ReadTimeout = value; } } public override int WriteTimeout { get { return m_WriteTimeout; } set { m_WriteTimeout = value; } } // public override void Write(byte[] buffer, int offset, int count) { lock (m_Entry) { if (m_Aborted) throw ExceptionHelper.RequestAbortedException; if (m_Event != null) throw new ObjectDisposedException(GetType().FullName); m_CallNesting = 1; try { base.Write(buffer, offset, count); if (m_StreamSize > 0) m_StreamSize -= count; if (!m_OneWriteSucceeded && count != 0) m_OneWriteSucceeded = true; } catch { m_Aborted = true; throw; } finally { m_CallNesting = 0; if (m_Event != null) m_Event.Set(); } } } // public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { lock (m_Entry) { if (m_CallNesting != 0) throw new NotSupportedException(SR.GetString(SR.net_no_concurrent_io_allowed)); if (m_Aborted) throw ExceptionHelper.RequestAbortedException; if (m_Event != null) throw new ObjectDisposedException(GetType().FullName); m_CallNesting = 1; try { if (m_StreamSize > 0) m_StreamSize -= count; return base.BeginWrite(buffer, offset, count, callback, state); } catch { m_Aborted = true; m_CallNesting = 0; throw; } } } // public override void EndWrite(IAsyncResult asyncResult) { lock (m_Entry) { try { base.EndWrite(asyncResult); if (!m_OneWriteSucceeded) m_OneWriteSucceeded = true; } catch { m_Aborted = true; throw; } finally { m_CallNesting = 0; if (m_Event != null) try {m_Event.Set();} catch {} // the problem is he WaitHandle cannot tell if it is disposed or not } } } // public void CloseEx(CloseExState closeState) { // For abnormal stream termination we will commit a partial cache entry if ((closeState & CloseExState.Abort) != 0) m_Aborted = true; try { Close(); } catch { if ((closeState & CloseExState.Silent) == 0) throw; } } // [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] protected override void Dispose(bool disposing) { //if m_Entry is null, it means that the base constructor failed if (Interlocked.Exchange(ref m_Disposed, 1) == 0 && m_Entry != null) { lock (m_Entry) { if (m_CallNesting == 0) base.Dispose(disposing); else m_Event = new ManualResetEvent(false); } // // This assumes the FileStream will never hang on write // if (disposing && m_Event != null) { using (m_Event) { m_Event.WaitOne(); lock (m_Entry) { Debug.Assert(m_CallNesting == 0); } } base.Dispose(disposing); } // We use TriState to indicate: // False: Delete // Unknown: Partial // True: Full TriState cacheCommitAction; if (m_StreamSize < 0) { if (m_Aborted) { if (m_OneWriteSucceeded) cacheCommitAction = TriState.Unspecified; // Partial else cacheCommitAction = TriState.False; // Delete } else { cacheCommitAction = TriState.True; // Full } } else { if (!m_OneWriteSucceeded) { cacheCommitAction = TriState.False; // Delete } else { if (m_StreamSize > 0) cacheCommitAction = TriState.Unspecified; // Partial else cacheCommitAction = TriState.True; // Full } } if (cacheCommitAction == TriState.False) { try { if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_no_commit, "WinInetWriteStream.Close()")); // Delete temp cache file File.Delete(m_Entry.Filename); } catch (Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_error_deleting_filename, "WinInetWriteStream.Close()", m_Entry.Filename)); } finally { //Delete an old entry if there was one _WinInetCache.Status errorStatus = _WinInetCache.Remove(m_Entry); if (errorStatus != _WinInetCache.Status.Success && errorStatus != _WinInetCache.Status.FileNotFound) { if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_delete_failed, "WinInetWriteStream.Close()", m_Entry.Key, new Win32Exception((int)m_Entry.Error).Message)); } m_Entry = null; } return; } m_Entry.OriginalUrl = null; // // ATTN: WinIent currently does NOT support _WinInetCache.EntryType.Sparse // USING a workaround // if (cacheCommitAction == TriState.Unspecified) { // WinInet will not report this entry back we set this flag // m_Entry.Info.EntryType |= _WinInetCache.EntryType.Sparse; // does not work for now // HACK: WinInet does not support SPARSE_ENTRY bit // We want to add c_SPARSE_ENTRY_HACK into the systemmetadata i.e. to the second block of strings separated by an empty line (\r\n). if (m_Entry.MetaInfo == null || m_Entry.MetaInfo.Length == 0 || (m_Entry.MetaInfo != "\r\n" && m_Entry.MetaInfo.IndexOf("\r\n\r\n", StringComparison.Ordinal) == -1)) { m_Entry.MetaInfo = "\r\n"+ WinInetCache.c_SPARSE_ENTRY_HACK+"\r\n"; } else { m_Entry.MetaInfo += WinInetCache.c_SPARSE_ENTRY_HACK+"\r\n"; } } if (_WinInetCache.Commit(m_Entry) != _WinInetCache.Status.Success) { if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_commit_failed, "WinInetWriteStream.Close()", m_Entry.Key, new Win32Exception((int)m_Entry.Error).Message)); try { // Delete temp cache file File.Delete(m_Entry.Filename); } catch (Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_error_deleting_filename, "WinInetWriteStream.Close()", m_Entry.Filename)); } if (m_IsThrow) { Win32Exception win32Exception = new Win32Exception((int)m_Entry.Error); throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, win32Exception.Message), win32Exception); } return; } if(Logging.On) { if (m_StreamSize > 0 || (m_StreamSize < 0 && m_Aborted)) Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_committed_as_partial, "WinInetWriteStream.Close()", m_Entry.Key, (m_StreamSize > 0 ? m_StreamSize.ToString(CultureInfo.CurrentCulture) : SR.GetString(SR.net_log_unknown)))); Logging.PrintInfo(Logging.RequestCache, "WinInetWriteStream.Close(), Key = " + m_Entry.Key + ", Commit Status = " + m_Entry.Error.ToString()); } if ((m_Entry.Info.EntryType & _WinInetCache.EntryType.StickyEntry) == _WinInetCache.EntryType.StickyEntry) { if (_WinInetCache.Update(m_Entry, _WinInetCache.Entry_FC.ExemptDelta) != _WinInetCache.Status.Success) { if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_update_failed, "WinInetWriteStream.Close(), Key = " + m_Entry.Key, new Win32Exception((int)m_Entry.Error).Message)); if (m_IsThrow) { Win32Exception win32Exception = new Win32Exception((int)m_Entry.Error); throw new IOException(SR.GetString(SR.net_cache_retrieve_failure, win32Exception.Message), win32Exception); } return; } if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_max_stale_and_update_status, "WinInetWriteFile.Close()", m_Entry.Info.U.ExemptDelta, m_Entry.Error.ToString())); } base.Dispose(disposing); } } } } }
using System; using System.Collections; using System.Linq; using UnityEditor; using UnityEngine; namespace AdvancedInspector { [CanEditMultipleObjects] [CustomEditor(typeof(Light), true)] public class LightEditor : InspectorEditor { private static Color disabledLightColor = new Color(0.5f, 0.45f, 0.2f, 0.5f); private static Color lightColor = new Color(0.95f, 0.95f, 0.5f, 0.5f); private SerializedProperty m_Lightmapping; protected override void RefreshFields() { Type type = typeof(Light); if (Instances == null || Instances.Length == 0) return; SerializedObject so = new SerializedObject(Instances.Cast<UnityEngine.Object>().ToArray()); Fields.Add(new InspectorField(type, Instances, type.GetProperty("type"), new DescriptorAttribute("Type", "The type of the light.", "http://docs.unity3d.com/ScriptReference/Light-type.html"))); m_Lightmapping = so.FindProperty("m_Lightmapping"); Fields.Add(new InspectorField(type, Instances, m_Lightmapping, new InspectAttribute(new InspectAttribute.InspectDelegate(IsNotArea)), new RestrictAttribute(new RestrictAttribute.RestrictDelegate(Baking)), new DescriptorAttribute("Baking", "How the light is handled versus lightmaps."))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("range"), new InspectAttribute(new InspectAttribute.InspectDelegate(IsPointOrSpot)), new DescriptorAttribute("Range", "The range of the light.", "http://docs.unity3d.com/ScriptReference/Light-range.html"))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("spotAngle"), new InspectAttribute(new InspectAttribute.InspectDelegate(IsSpot)), new DescriptorAttribute("Spot Angle", "The angle of the light's spotlight cone in degrees.", "http://docs.unity3d.com/ScriptReference/Light-spotAngle.html"))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("areaSize"), new InspectAttribute(new InspectAttribute.InspectDelegate(IsArea)), new DescriptorAttribute("Area Size", "The size of the area light. Editor only.", "http://docs.unity3d.com/ScriptReference/Light-areaSize.html"))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("color"), new DescriptorAttribute("Color", "The color of the light.", "http://docs.unity3d.com/ScriptReference/Light-color.html"))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("intensity"), new RangeValueAttribute(0f, 8f), new DescriptorAttribute("Intensity", "The Intensity of a light is multiplied with the Light color.", "http://docs.unity3d.com/ScriptReference/Light-intensity.html"))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("bounceIntensity"), new RangeValueAttribute(0f, 8f), new HelpAttribute(new HelpAttribute.HelpDelegate(HelpBouncedGI)), new DescriptorAttribute("Bounce Intensity", "The multiplier that defines the strength of the bounce lighting.", "http://docs.unity3d.com/ScriptReference/Light-bounceIntensity.html"))); //Acts like a group Fields.Add(new InspectorField(type, Instances, type.GetProperty("shadows"), new InspectAttribute(new InspectAttribute.InspectDelegate(IsNotArea)), new DescriptorAttribute("Shadow Type", "How this light casts shadows", "http://docs.unity3d.com/ScriptReference/Light-shadows.html"))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("shadowStrength"), new InspectAttribute(new InspectAttribute.InspectDelegate(HasShadow)), new DescriptorAttribute("Strength", "How this light casts shadows.", "http://docs.unity3d.com/ScriptReference/Light-shadowStrength.html"))); Fields.Add(new InspectorField(type, Instances, so.FindProperty("m_Shadows.m_Resolution"), new InspectAttribute(new InspectAttribute.InspectDelegate(HasShadow)), new DescriptorAttribute("Resolution", "The shadow's resolution."))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("shadowBias"), new InspectAttribute(new InspectAttribute.InspectDelegate(HasShadow)), new DescriptorAttribute("Bias", "Shadow mapping bias.", "http://docs.unity3d.com/ScriptReference/Light-shadowBias.html"))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("shadowNormalBias"), new InspectAttribute(new InspectAttribute.InspectDelegate(HasShadow)), new DescriptorAttribute("Normal Bias", "Shadow mapping normal-based bias.", "http://docs.unity3d.com/ScriptReference/Light-shadowNormalBias.html"))); Fields.Add(new InspectorField(type, Instances, so.FindProperty("m_DrawHalo"), new DescriptorAttribute("Draw Halo", "Draw a halo around the light. Now work with the Halo class."))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("cookie"), new DescriptorAttribute("Cookie", "The cookie texture projected by the light.", "http://docs.unity3d.com/ScriptReference/Light-cookie.html"))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("cookieSize"), new InspectAttribute(new InspectAttribute.InspectDelegate(IsDirectional)), new DescriptorAttribute("Cookie Size", "The size of a directional light's cookie.", "http://docs.unity3d.com/ScriptReference/Light-cookieSize.html"))); Fields.Add(new InspectorField(type, Instances, type.GetProperty("flare"), new DescriptorAttribute("Flare", "The flare asset to use for this light.", "http://docs.unity3d.com/ScriptReference/Light-flare.html"))); Fields.Add(new InspectorField(type, Instances, so.FindProperty("m_RenderMode"), new DescriptorAttribute("Render Mode", "The rendering path for the lights."))); Fields.Add(new InspectorField(type, Instances, so.FindProperty("m_CullingMask"), new HelpAttribute(new HelpAttribute.HelpDelegate(HelpSceneLighting)), new DescriptorAttribute("Culling Mask", "The object that are affected or ignored by the light."))); } private IList Baking() { return new DescriptionPair[] { new DescriptionPair(4, "Realtime", ""), new DescriptionPair(2, "Baked", ""), new DescriptionPair(1, "Mixed", "") }; } public bool IsPointOrSpot() { if (IsPoint() || IsSpot()) return true; return false; } public bool IsPoint() { return ((Light)Instances[0]).type == LightType.Point; } public bool IsSpot() { return ((Light)Instances[0]).type == LightType.Spot; } public bool IsDirectional() { return ((Light)Instances[0]).type == LightType.Directional; } public bool IsNotArea() { return !IsArea(); } public bool IsArea() { return ((Light)Instances[0]).type == LightType.Area; } public bool HasShadow() { Light light = (Light)Instances[0]; return IsNotArea() && (light.shadows == LightShadows.Hard || light.shadows == LightShadows.Soft); } public bool IsSoft() { return ((Light)Instances[0]).shadows == LightShadows.Soft; } public bool DoesAnyCameraUseDeferred() { Camera[] allCameras = Camera.allCameras; for (int i = 0; i < allCameras.Length; i++) if (allCameras[i].actualRenderingPath == RenderingPath.DeferredLighting) return true; return false; } public HelpItem HelpBouncedGI() { if (((Light)Instances[0]).bounceIntensity > 0 && IsPointOrSpot() && m_Lightmapping.intValue != 2) return new HelpItem(HelpType.Warning, "Currently realtime indirect bounce light shadowing for spot and point lights is not supported."); return null; } public HelpItem HelpSceneLighting() { if (SceneView.currentDrawingSceneView != null && !SceneView.currentDrawingSceneView.m_SceneLighting) return new HelpItem(HelpType.Warning, "One of your scene views has lighting disable, please keep this in mind when editing lighting."); return null; } protected override void OnSceneGUI() { base.OnSceneGUI(); if (Event.current.type == EventType.Used) return; Light light = (Light)target; Color color = Handles.color; if (light.enabled) Handles.color = lightColor; else Handles.color = disabledLightColor; float range = light.range; switch (light.type) { case LightType.Spot: { Color color2 = Handles.color; color2.a = Mathf.Clamp01(color.a * 2f); Handles.color = color2; Vector2 angleAndRange = new Vector2(light.spotAngle, light.range); angleAndRange = ConeHandle(light.transform.rotation, light.transform.position, angleAndRange, 1f, 1f, true); if (GUI.changed) { Undo.RecordObject(light, "Adjust Spot Light"); light.spotAngle = angleAndRange.x; light.range = Mathf.Max(angleAndRange.y, 0.01f); } break; } case LightType.Point: { range = Handles.RadiusHandle(Quaternion.identity, light.transform.position, range, true); if (GUI.changed) { Undo.RecordObject(light, "Adjust Point Light"); light.range = range; } break; } case LightType.Area: { EditorGUI.BeginChangeCheck(); Vector2 vector2 = RectHandles(light.transform.rotation, light.transform.position, light.areaSize); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(light, "Adjust Area Light"); light.areaSize = vector2; } break; } } Handles.color = color; } private Vector2 ConeHandle(Quaternion rotation, Vector3 position, Vector2 angleAndRange, float angleScale, float rangeScale, bool handlesOnly) { float x = angleAndRange.x; float y = angleAndRange.y; float r = y * rangeScale; Vector3 forward = rotation * Vector3.forward; Vector3 up = rotation * Vector3.up; Vector3 right = rotation * Vector3.right; bool changed = GUI.changed; GUI.changed = false; r = SizeSlider(position, forward, r); if (GUI.changed) y = Mathf.Max(0f, r / rangeScale); GUI.changed |= changed; changed = GUI.changed; GUI.changed = false; float angle = (r * Mathf.Tan((0.01745329f * x) / 2f)) * angleScale; angle = SizeSlider(position + (forward * r), up, angle); angle = SizeSlider(position + (forward * r), -up, angle); angle = SizeSlider(position + (forward * r), right, angle); angle = SizeSlider(position + (forward * r), -right, angle); if (GUI.changed) x = Mathf.Clamp((57.29578f * Mathf.Atan(angle / (r * angleScale))) * 2f, 0f, 179f); GUI.changed |= changed; if (!handlesOnly) { Handles.DrawLine(position, (position + (forward * r)) + (up * angle)); Handles.DrawLine(position, (position + (forward * r)) - (up * angle)); Handles.DrawLine(position, (position + (forward * r)) + (right * angle)); Handles.DrawLine(position, (position + (forward * r)) - (right * angle)); Handles.DrawWireDisc(position + r * forward, forward, angle); } return new Vector2(x, y); } private Vector2 RectHandles(Quaternion rotation, Vector3 position, Vector2 size) { Vector3 forward = rotation * Vector3.forward; Vector3 up = rotation * Vector3.up; Vector3 right = rotation * Vector3.right; float radiusX = 0.5f * size.x; float radiusY = 0.5f * size.y; Vector3 v1 = (position + (up * radiusY)) + (right * radiusX); Vector3 v2 = (position - (up * radiusY)) + (right * radiusX); Vector3 v3 = (position - (up * radiusY)) - (right * radiusX); Vector3 v4 = (position + (up * radiusY)) - (right * radiusX); Handles.DrawLine(v1, v2); Handles.DrawLine(v2, v3); Handles.DrawLine(v3, v4); Handles.DrawLine(v4, v1); Color color = Handles.color; color.a = Mathf.Clamp01(color.a * 2f); Handles.color = color; radiusY = SizeSlider(position, up, radiusY); radiusY = SizeSlider(position, -up, radiusY); radiusX = SizeSlider(position, right, radiusX); radiusX = SizeSlider(position, -right, radiusX); if (((Tools.current != Tool.Move) && (Tools.current != Tool.Scale)) || Tools.pivotRotation != PivotRotation.Local) Handles.DrawLine(position, position + forward); size.x = 2f * radiusX; size.y = 2f * radiusY; return size; } private float SizeSlider(Vector3 p, Vector3 direction, float radius) { Vector3 position = p + (direction * radius); float handleSize = HandleUtility.GetHandleSize(position); bool changed = GUI.changed; GUI.changed = false; #if UNITY_5_6 || UNITY_2017 position = Handles.Slider(position, direction, handleSize * 0.03f, new Handles.CapFunction(Handles.DotHandleCap), 0f); #else position = Handles.Slider(position, direction, handleSize * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); #endif if (GUI.changed) radius = Vector3.Dot(position - p, direction); GUI.changed |= changed; return radius; } } }
// 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.Globalization; /// <summary> /// UInt16.System.IConvertible.ToType(Type, IFormatProvider) /// Converts the current UInt16 value to an object of the specified type using /// the specified IFormatProvider object. /// </summary> public class UInt16IConvertibleToType { public static int Main() { UInt16IConvertibleToType testObj = new UInt16IConvertibleToType(); TestLibrary.TestFramework.BeginTestCase("for method: UInt16.System.IConvertible.ToType(Type, IFormatProvider)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; retVal = PosTest10() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_ID = "P001"; const string c_TEST_DESC = "PosTest1: Conversion to byte"; string errorDesc; byte b; object expectedObj; object actualObj; UInt16 uintA; b = TestLibrary.Generator.GetByte(-55); uintA = (UInt16)b; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { NumberFormatInfo numberFormat = new NumberFormatInfo(); IFormatProvider provider = numberFormat; IConvertible converter = uintA; expectedObj = b; actualObj = converter.ToType(typeof(byte), numberFormat); if (((byte)expectedObj != (byte)actualObj) || !(actualObj is byte)) { errorDesc = string.Format("Byte value of UInt16 {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_ID = "P002"; const string c_TEST_DESC = "PosTest2: Conversion to sbyte"; string errorDesc; sbyte sb; object expectedObj; object actualObj; UInt16 uintA; sb = (sbyte)(TestLibrary.Generator.GetByte(-55) % (sbyte.MaxValue + 1)); uintA = (UInt16)sb; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { NumberFormatInfo numberFormat = new NumberFormatInfo(); IFormatProvider provider = numberFormat; IConvertible converter = uintA; expectedObj = sb; actualObj = converter.ToType(typeof(sbyte), numberFormat); if (((sbyte)expectedObj != (sbyte)actualObj) || !(actualObj is sbyte)) { errorDesc = string.Format("SByte value of character {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_ID = "P003"; const string c_TEST_DESC = "PosTest3: Conversion to Int16"; string errorDesc; Int16 i; object expectedObj; object actualObj; UInt16 uintA; i = (Int16)(TestLibrary.Generator.GetInt32(-55) % (Int16.MaxValue + 1)); uintA = (UInt16)i; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { NumberFormatInfo numberFormat = new NumberFormatInfo(); IFormatProvider provider = numberFormat; IConvertible converter = uintA; expectedObj = i; actualObj = converter.ToType(typeof(Int16), numberFormat); if (((Int16)expectedObj != (Int16)actualObj) || !(actualObj is Int16)) { errorDesc = string.Format("Int16 value of character {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_ID = "P004"; const string c_TEST_DESC = "PosTest4: Conversion to UInt16"; string errorDesc; UInt16 i; object expectedObj; object actualObj; UInt16 uintA; i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1)); uintA = (UInt16)i; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { NumberFormatInfo numberFormat = new NumberFormatInfo(); IFormatProvider provider = numberFormat; IConvertible converter = uintA; expectedObj = i; actualObj = converter.ToType(typeof(UInt16), numberFormat); if (((UInt16)expectedObj != (UInt16)actualObj) || !(actualObj is UInt16)) { errorDesc = string.Format("UInt16 value of character {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_ID = "P005"; const string c_TEST_DESC = "PosTest5: Conversion to Int32"; string errorDesc; int i; object expectedObj; object actualObj; UInt16 uintA; i = TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1); uintA = (UInt16)i; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { NumberFormatInfo numberFormat = new NumberFormatInfo(); IFormatProvider provider = numberFormat; IConvertible converter = uintA; expectedObj = i; actualObj = converter.ToType(typeof(int), numberFormat); if (((int)expectedObj != (int)actualObj) || !(actualObj is int)) { errorDesc = string.Format("Int32 value of character {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; const string c_TEST_ID = "P006"; const string c_TEST_DESC = "PosTest6: Conversion to UInt32"; string errorDesc; UInt32 i; object expectedObj; object actualObj; UInt16 uintA; i = (UInt32)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1)); uintA = (UInt16)i; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { NumberFormatInfo numberFormat = new NumberFormatInfo(); IFormatProvider provider = numberFormat; IConvertible converter = uintA; expectedObj = i; actualObj = converter.ToType(typeof(UInt32), numberFormat); if (((UInt32)expectedObj != (UInt32)actualObj) || !(actualObj is UInt32)) { errorDesc = string.Format("UInt32 value of character {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; const string c_TEST_ID = "P007"; const string c_TEST_DESC = "PosTest7: Conversion to Int64"; string errorDesc; Int64 i; object expectedObj; object actualObj; UInt16 uintA; i = TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1); uintA = (UInt16)i; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { NumberFormatInfo numberFormat = new NumberFormatInfo(); IFormatProvider provider = numberFormat; IConvertible converter = uintA; expectedObj = i; actualObj = converter.ToType(typeof(Int64), numberFormat); if (((Int64)expectedObj != (Int64)actualObj) || !(actualObj is Int64)) { errorDesc = string.Format("Int64 value of character {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; const string c_TEST_ID = "P008"; const string c_TEST_DESC = "PosTest8: Conversion to UInt64"; string errorDesc; UInt64 i; object expectedObj; object actualObj; UInt16 uintA; i = (UInt64)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1)); uintA = (UInt16)i; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { NumberFormatInfo numberFormat = new NumberFormatInfo(); IFormatProvider provider = numberFormat; IConvertible converter = uintA; expectedObj = i; actualObj = converter.ToType(typeof(UInt64), numberFormat); if (((UInt64)expectedObj != (UInt64)actualObj) || !(actualObj is UInt64)) { errorDesc = string.Format("UInt64 value of character {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest9() { bool retVal = true; const string c_TEST_ID = "P009"; const string c_TEST_DESC = "PosTest9: Conversion to char"; string errorDesc; object expectedObj; object actualObj; UInt16 uintA; uintA = (UInt16)TestLibrary.Generator.GetChar(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { IConvertible converter = uintA; expectedObj = (char)uintA; actualObj = converter.ToType(typeof(char), null); if (((char)expectedObj != (char)actualObj) || !(actualObj is char)) { errorDesc = string.Format("char value of UInt16 {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("017" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("018" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest10() { bool retVal = true; const string c_TEST_ID = "P010"; const string c_TEST_DESC = "PosTest10: Conversion to string"; string errorDesc; object expectedObj; object actualObj; UInt16 uintA; uintA = (UInt16)TestLibrary.Generator.GetChar(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { IConvertible converter = uintA; expectedObj = uintA.ToString(); actualObj = converter.ToType(typeof(string), null); if (((string)expectedObj != (string)actualObj) || !(actualObj is string)) { errorDesc = string.Format("string value of UInt16 {0} is not ", uintA); errorDesc += expectedObj + " as expected: Actual(" + actualObj + ")"; TestLibrary.TestFramework.LogError("019" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("020" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion #region Negative tests //bug //ArgumentNullException public bool NegTest1() { bool retVal = true; const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: type is a null reference (Nothing in Visual Basic)."; string errorDesc; UInt16 uintA = (UInt16)TestLibrary.Generator.GetChar(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { IConvertible converter = uintA; converter.ToType(null, null); errorDesc = "ArgumentNullException is not thrown as expected."; errorDesc += string.Format("\nThe UInt16 value is {0}", uintA); TestLibrary.TestFramework.LogError("021" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe UInt16 value is {0}", uintA); TestLibrary.TestFramework.LogError("022" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //bug //InvalidCastException public bool NegTest2() { const string c_TEST_ID = "N002"; const string c_TEST_DESC = "NegTest2: type is DateTime"; return this.DoInvalidCastTest(c_TEST_ID, c_TEST_DESC, "023", "024", typeof(DateTime)); } //bug //OverflowException public bool NegTest3() { const string c_TEST_ID = "N003"; const string c_TEST_DESC = "NegTest3: Value is too large for destination type -- Int16"; return this.DoOverflowTest(c_TEST_ID, c_TEST_DESC, "025", typeof(Int16), Int16.MaxValue); } public bool NegTest4() { const string c_TEST_ID = "N004"; const string c_TEST_DESC = "NegTest4: Value is too large for destination type -- byte"; return this.DoOverflowTest(c_TEST_ID, c_TEST_DESC, "026", typeof(byte), byte.MaxValue); } public bool NegTest5() { const string c_TEST_ID = "N005"; const string c_TEST_DESC = "NegTest5: Value is too large for destination type -- sbyte"; return this.DoOverflowTest(c_TEST_ID, c_TEST_DESC, "027", typeof(sbyte), sbyte.MaxValue); } #endregion #region Helper methods for negative tests private bool DoInvalidCastTest(string testId, string testDesc, string errorNum1, string errorNum2, Type destType) { bool retVal = true; string errorDesc; UInt16 uintA = (UInt16)TestLibrary.Generator.GetChar(-55); TestLibrary.TestFramework.BeginScenario(testDesc); try { IConvertible converter = uintA; converter.ToType(destType, null); errorDesc = "InvalidCastException is not thrown as expected."; errorDesc += string.Format("\nThe UInt16 value is {0}", uintA); TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc); retVal = false; } catch (InvalidCastException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe character is {0}", uintA); TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc); retVal = false; } return retVal; } private bool DoOverflowTest(string testId, string testDesc, string errorNum, Type destType, int destTypeMaxValue) { bool retVal = true; string errorDesc; int i; UInt16 uintA; i = Int16.MaxValue + 1 + TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue - destTypeMaxValue); uintA = (UInt16)i; TestLibrary.TestFramework.BeginScenario(testDesc); try { IConvertible converter = uintA; converter.ToType(destType, null); } catch (OverflowException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe UInt16 value is {0}", uintA); TestLibrary.TestFramework.LogError(errorNum + " TestId-" + testId, errorDesc); retVal = false; } return retVal; } #endregion }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace DrawingEx.ColorManagement.ColorModels.Selection { public abstract class ColorSelectionModuleLAB:ColorSelectionModule { #region variables protected LAB _color; #endregion #region properties public override XYZ XYZ { get { return _color.ToXYZ(); } set { LAB newcolor=LAB.FromXYZ(value); if(newcolor==_color) return; _color=newcolor; //update controls UpdatePlaneImage(); UpdatePlanePosition(); UpdateFaderImage(); UpdateFaderPosition(); } } #endregion } public class ColorSelectionModuleLAB_L:ColorSelectionModuleLAB { #region colorfader protected override unsafe void OnUpdateFaderImage(Bitmap bmp) { if(bmp.PixelFormat!=PixelFormat.Format32bppArgb) return; BitmapData bd=bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.WriteOnly,PixelFormat.Format32bppArgb); ColorBgra* scan0=(ColorBgra*)bd.Scan0; //draw fader image LAB curr=new LAB(0.0,_color.a,_color.b); double delta_L=100.0/(double)bd.Width; for(int x=0; x<bd.Width; x++, scan0++,curr.L+=delta_L) { scan0[0]=ColorBgra.FromArgb(curr.ToXYZ().ToRGB()); } //end bmp.UnlockBits(bd); } protected override void OnUpdateFaderPosition(ColorSelectionFader fader) { fader.Position=_color.L/100.0; } protected override void OnFaderScroll(ColorSelectionFader fader) { double newL=fader.Position*100.0; if(newL==_color.L) return; _color.L=newL; RaiseColorChanged(); System.Windows.Forms.Application.DoEvents(); UpdatePlaneImage(); } #endregion #region colorplane protected override unsafe void OnUpdatePlaneImage(Bitmap bmp) { if(bmp.PixelFormat!=PixelFormat.Format32bppArgb) return; BitmapData bd=bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.WriteOnly,PixelFormat.Format32bppArgb); ColorBgra* scan0=(ColorBgra*)bd.Scan0; //draw plane image LAB curr=new LAB(_color.L,-128.0,127.0); double delta_a=255.0/(double)bd.Width, delta_b=-255.0/(double)bd.Height; for(int y=0; y<bd.Height; y++, curr.a=-128.0, curr.b+=delta_b) { for(int x=0; x<bd.Width; x++, scan0++,curr.a+=delta_a) { scan0[0]=ColorBgra.FromArgb(curr.ToXYZ().ToRGB()); } } //end bmp.UnlockBits(bd); } protected override void OnUpdatePlanePosition(ColorSelectionPlane plane) { plane.SetPosition((_color.a+128.0)/255.0, (127.0-_color.b)/255.0); } protected override void OnPlaneScroll(ColorSelectionPlane plane) { double newa=plane.PositionX*255.0-128.0, newb=127.0-plane.PositionY*255.0; if(newa==_color.a && newb==_color.b) return; _color.a=newa; _color.b=newb; UpdateFaderImage(); RaiseColorChanged(); } #endregion } public class ColorSelectionModuleLAB_a:ColorSelectionModuleLAB { #region colorfader protected override unsafe void OnUpdateFaderImage(Bitmap bmp) { if(bmp.PixelFormat!=PixelFormat.Format32bppArgb) return; BitmapData bd=bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.WriteOnly,PixelFormat.Format32bppArgb); ColorBgra* scan0=(ColorBgra*)bd.Scan0; //draw fader image LAB curr=new LAB(_color.L,-128.0,_color.b); double delta_a=255.0/(double)bd.Width; for(int x=0; x<bd.Width; x++, scan0++,curr.a+=delta_a) { scan0[0]=ColorBgra.FromArgb(curr.ToXYZ().ToRGB()); } //end bmp.UnlockBits(bd); } protected override void OnUpdateFaderPosition(ColorSelectionFader fader) { fader.Position=(_color.a+128.0)/255.0; } protected override void OnFaderScroll(ColorSelectionFader fader) { double newa=fader.Position*255.0-128.0; if(newa==_color.b) return; _color.a=newa; RaiseColorChanged(); System.Windows.Forms.Application.DoEvents(); UpdatePlaneImage(); } #endregion #region colorplane protected override unsafe void OnUpdatePlaneImage(Bitmap bmp) { if(bmp.PixelFormat!=PixelFormat.Format32bppArgb) return; BitmapData bd=bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.WriteOnly,PixelFormat.Format32bppArgb); ColorBgra* scan0=(ColorBgra*)bd.Scan0; //draw plane image LAB curr=new LAB(100.0,_color.a,-128.0); double delta_L=-100.0/(double)bd.Height, delta_b=255.0/(double)bd.Width; for(int y=0; y<bd.Height; y++, curr.b=-128.0, curr.L+=delta_L) { for(int x=0; x<bd.Width; x++, scan0++,curr.b+=delta_b) { scan0[0]=ColorBgra.FromArgb(curr.ToXYZ().ToRGB()); } } //end bmp.UnlockBits(bd); } protected override void OnUpdatePlanePosition(ColorSelectionPlane plane) { plane.SetPosition((_color.b+128.0)/255.0, 1.0-_color.L/100.0); } protected override void OnPlaneScroll(ColorSelectionPlane plane) { double newb=plane.PositionX*255.0-128.0, newL=(1.0-plane.PositionY)*100.0; if(newb==_color.b && newL==_color.L) return; _color.b=newb; _color.L=newL; UpdateFaderImage(); RaiseColorChanged(); } #endregion } public class ColorSelectionModuleLAB_b:ColorSelectionModuleLAB { #region colorfader protected override unsafe void OnUpdateFaderImage(Bitmap bmp) { if(bmp.PixelFormat!=PixelFormat.Format32bppArgb) return; BitmapData bd=bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.WriteOnly,PixelFormat.Format32bppArgb); ColorBgra* scan0=(ColorBgra*)bd.Scan0; //draw fader image LAB curr=new LAB(_color.L,_color.a,-128.0); double delta_b=255.0/(double)bd.Width; for(int x=0; x<bd.Width; x++, scan0++,curr.b+=delta_b) { scan0[0]=ColorBgra.FromArgb(curr.ToXYZ().ToRGB()); } //end bmp.UnlockBits(bd); } protected override void OnUpdateFaderPosition(ColorSelectionFader fader) { fader.Position=(_color.b+128.0)/255.0; } protected override void OnFaderScroll(ColorSelectionFader fader) { double newb=fader.Position*255.0-128.0; if(newb==_color.b) return; _color.b=newb; RaiseColorChanged(); System.Windows.Forms.Application.DoEvents(); UpdatePlaneImage(); } #endregion #region colorplane protected override unsafe void OnUpdatePlaneImage(Bitmap bmp) { if(bmp.PixelFormat!=PixelFormat.Format32bppArgb) return; BitmapData bd=bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.WriteOnly,PixelFormat.Format32bppArgb); ColorBgra* scan0=(ColorBgra*)bd.Scan0; //draw plane image LAB curr=new LAB(100.0,-128.0,_color.b); double delta_L=-100.0/(double)bd.Height, delta_a=255.0/(double)bd.Width; for(int y=0; y<bd.Height; y++, curr.a=-128.0, curr.L+=delta_L) { for(int x=0; x<bd.Width; x++, scan0++,curr.a+=delta_a) { scan0[0]=ColorBgra.FromArgb(curr.ToXYZ().ToRGB()); } } //end bmp.UnlockBits(bd); } protected override void OnUpdatePlanePosition(ColorSelectionPlane plane) { plane.SetPosition((_color.a+128.0)/255.0, 1.0-_color.L/100.0); } protected override void OnPlaneScroll(ColorSelectionPlane plane) { double newa=plane.PositionX*255.0-128.0, newL=(1.0-plane.PositionY)*100.0; if(newa==_color.a && newL==_color.L) return; _color.a=newa; _color.L=newL; UpdateFaderImage(); RaiseColorChanged(); } #endregion } }
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT License using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Options; using System; using System.Threading; using System.Threading.Tasks; namespace Pomelo.Extensions.Caching.MySql { /// <summary> /// Distributed cache implementation using Microsoft MySql Server database. /// </summary> public class MySqlCache : IDistributedCache { private static readonly TimeSpan MinimumExpiredItemsDeletionInterval = TimeSpan.FromMinutes(5); private static readonly TimeSpan DefaultExpiredItemsDeletionInterval = TimeSpan.FromMinutes(30); private readonly IDatabaseOperations _dbOperations; private readonly ISystemClock _systemClock; private readonly TimeSpan _expiredItemsDeletionInterval; private DateTimeOffset _lastExpirationScan; private readonly Func<Task<int>> _deleteExpiredCachedItemsDelegateAsync; private readonly Func<int> _deleteExpiredCachedItemsDelegate; private readonly TimeSpan _defaultSlidingExpiration; public MySqlCache(IOptions<MySqlCacheOptions> options) { var cacheOptions = options.Value; if (string.IsNullOrEmpty(cacheOptions.WriteConnectionString) && string.IsNullOrEmpty(cacheOptions.ConnectionString) && string.IsNullOrEmpty(cacheOptions.ReadConnectionString)) { throw new ArgumentException($"{nameof(cacheOptions.ReadConnectionString)} and {nameof(cacheOptions.WriteConnectionString)}" + $" and {nameof(cacheOptions.ConnectionString)} cannot be empty or null at the same time."); } if (string.IsNullOrEmpty(cacheOptions.SchemaName)) { throw new ArgumentException( $"{nameof(cacheOptions.SchemaName)} cannot be empty or null."); } if (string.IsNullOrEmpty(cacheOptions.TableName)) { throw new ArgumentException( $"{nameof(cacheOptions.TableName)} cannot be empty or null."); } if (cacheOptions.ExpiredItemsDeletionInterval.HasValue && cacheOptions.ExpiredItemsDeletionInterval.Value < MinimumExpiredItemsDeletionInterval) { throw new ArgumentException( $"{nameof(cacheOptions.ExpiredItemsDeletionInterval)} cannot be less the minimum " + $"value of {MinimumExpiredItemsDeletionInterval.TotalMinutes} minutes."); } if (cacheOptions.DefaultSlidingExpiration <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException( nameof(cacheOptions.DefaultSlidingExpiration), cacheOptions.DefaultSlidingExpiration, "The sliding expiration value must be positive."); } _systemClock = cacheOptions.SystemClock ?? new SystemClock(); _expiredItemsDeletionInterval = cacheOptions.ExpiredItemsDeletionInterval ?? DefaultExpiredItemsDeletionInterval; _defaultSlidingExpiration = cacheOptions.DefaultSlidingExpiration; // MySqlClient library on Mono doesn't have support for DateTimeOffset and also // it doesn't have support for apis like GetFieldValue, GetFieldValueAsync etc. // So we detect the platform to perform things differently for Mono vs. non-Mono platforms. if (PlatformHelper.IsMono) { _dbOperations = new MonoDatabaseOperations( cacheOptions.ReadConnectionString, cacheOptions.WriteConnectionString, cacheOptions.SchemaName, cacheOptions.TableName, _systemClock); } else { _dbOperations = new DatabaseOperations( cacheOptions.ReadConnectionString, cacheOptions.WriteConnectionString, cacheOptions.SchemaName, cacheOptions.TableName, _systemClock); } _deleteExpiredCachedItemsDelegateAsync = _dbOperations.DeleteExpiredCacheItemsAsync; _deleteExpiredCachedItemsDelegate = _dbOperations.DeleteExpiredCacheItems; } public byte[] Get(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var value = _dbOperations.GetCacheItem(key); ScanForExpiredItemsIfRequired(); return value; } public async Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } token.ThrowIfCancellationRequested(); var value = await _dbOperations.GetCacheItemAsync(key, token: token); await ScanForExpiredItemsIfRequiredAsync(); return value; } public void Refresh(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } _dbOperations.RefreshCacheItem(key); ScanForExpiredItemsIfRequired(); } public async Task RefreshAsync(string key, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } token.ThrowIfCancellationRequested(); await _dbOperations.RefreshCacheItemAsync(key, token: token); await ScanForExpiredItemsIfRequiredAsync(); } public void Remove(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } _dbOperations.DeleteCacheItem(key); ScanForExpiredItemsIfRequired(); } public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } token.ThrowIfCancellationRequested(); await _dbOperations.DeleteCacheItemAsync(key, token: token); await ScanForExpiredItemsIfRequiredAsync(); } public void Set(string key, byte[] value, DistributedCacheEntryOptions options) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } //GetOptions(ref options); _dbOperations.SetCacheItem(key, value, options); ScanForExpiredItemsIfRequired(); } public async Task SetAsync( string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } token.ThrowIfCancellationRequested(); //GetOptions(ref options); await _dbOperations.SetCacheItemAsync(key, value, options, token); await ScanForExpiredItemsIfRequiredAsync(); } // Called by multiple actions to see how long it's been since we last checked for expired items. // If sufficient time has elapsed then a scan is initiated on a background task. private async Task ScanForExpiredItemsIfRequiredAsync() { var utcNow = _systemClock.UtcNow; // TODO: Multiple threads could trigger this scan which leads to multiple calls to database. if ((utcNow - _lastExpirationScan) > _expiredItemsDeletionInterval) { _lastExpirationScan = utcNow; //await Task.Delay(1000); //await _deleteExpiredCachedItemsDelegateAsync(); //Task.Delay(1000); await Task.Run(_deleteExpiredCachedItemsDelegate); } } private void ScanForExpiredItemsIfRequired() { var utcNow = _systemClock.UtcNow; if ((utcNow - _lastExpirationScan) > _expiredItemsDeletionInterval) { _lastExpirationScan = utcNow; _deleteExpiredCachedItemsDelegate.Invoke(); } } private void GetOptions(ref DistributedCacheEntryOptions options) { if (!options.AbsoluteExpiration.HasValue && !options.AbsoluteExpirationRelativeToNow.HasValue && !options.SlidingExpiration.HasValue) { options = new DistributedCacheEntryOptions() { SlidingExpiration = _defaultSlidingExpiration }; } } } }
using Shouldly; using StructureMap.Pipeline; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget3; using System; using System.Linq; using Xunit; namespace StructureMap.Testing.Pipeline { public class SmartInstanceTester { private SmartInstance<T, T> For<T>() { var instance = new SmartInstance<T, T>(); return instance; } public T build<T>(Action<SmartInstance<T, T>> action) { var instance = For<T>(); action(instance); var container = new Container(r => r.For<T>().UseInstance(instance)); return container.GetInstance<T>(); } [Fact] public void specify_a_constructor_dependency() { var widget = new ColorWidget("Red"); build<ClassWithWidget>(instance => instance.Ctor<IWidget>("widget").IsSpecial(x => x.Object(widget))). Widget. ShouldBeTheSameAs(widget); } [Fact] public void specify_a_constructor_dependency_by_type() { var widget = new ColorWidget("Red"); build<ClassWithWidget>(i => i.Ctor<IWidget>().IsSpecial(x => x.Object(widget))).Widget.ShouldBeTheSameAs( widget); } [Fact] public void specify_a_non_simple_property_with_equal_to() { var widget = new ColorWidget("Red"); var container = new Container(x => x.For<ClassWithWidgetProperty>() .Use<ClassWithWidgetProperty>() .Setter(o => o.Widget).Is(widget)); widget.ShouldBeTheSameAs(container.GetInstance<ClassWithWidgetProperty>().Widget); } [Fact] public void specify_a_property_dependency() { var widget = new ColorWidget("Red"); build<ClassWithWidgetProperty>(i => i.Setter(x => x.Widget).IsSpecial(x => x.Object(widget))).Widget. ShouldBeTheSameAs(widget); var container = new Container(x => { x.ForConcreteType<ClassWithWidgetProperty>().Configure .Setter(o => o.Widget).IsSpecial(o => o.Object(new ColorWidget("Red"))); }); } [Fact] public void specify_a_simple_property() { build<SimplePropertyTarget>(instance => instance.SetProperty(x => x.Name = "Jeremy")).Name.ShouldBe( "Jeremy"); build<SimplePropertyTarget>(i => i.SetProperty(x => x.Age = 16)).Age.ShouldBe(16); var container = new Container(x => { x.ForConcreteType<SimplePropertyTarget>().Configure .SetProperty(target => { target.Name = "Max"; target.Age = 4; }); }); } [Fact] public void specify_a_simple_property_name_with_equal_to() { build<SimplePropertyTarget>(i => i.Setter(x => x.Name).Is("Scott")).Name.ShouldBe("Scott"); } [Fact] public void specify_a_simple_property_with_equal_to() { build<SimplePropertyTarget>(i => i.Setter(x => x.Name).Is("Bret")).Name.ShouldBe("Bret"); } [Fact] public void specify_an_array_as_a_constructor() { IWidget widget1 = new AWidget(); IWidget widget2 = new AWidget(); IWidget widget3 = new AWidget(); build<ClassWithWidgetArrayCtor>(i => i.EnumerableOf<IWidget>().Contains(x => { x.Object(widget1); x.Object(widget2); x.Object(widget3); })).Widgets.ShouldBe(new[] { widget1, widget2, widget3 }); } [Fact] public void specify_an_array_as_a_property() { IWidget widget1 = new AWidget(); IWidget widget2 = new AWidget(); IWidget widget3 = new AWidget(); build<ClassWithWidgetArraySetter>(i => i.EnumerableOf<IWidget>().Contains(x => { x.Object(widget1); x.Object(widget2); x.Object(widget3); })).Widgets.ShouldBe(new[] { widget1, widget2, widget3 }); } [Fact] public void specify_ctorarg_with_non_simple_argument() { var widget = new ColorWidget("Red"); var container = new Container(x => x.For<ClassWithWidget>() .Use<ClassWithWidget>() .Ctor<IWidget>().Is(widget)); widget.ShouldBeTheSameAs(container.GetInstance<ClassWithWidget>().Widget); } [Fact] public void successfully_specify_the_constructor_argument_of_a_string() { build<ColorRule>(i => i.Ctor<string>("color").Is("Red")).Color.ShouldBe("Red"); } [Fact] public void specify_a_constructor_dependency_by_name() { var container = new Container(r => { r.For<ClassA>().Use<ClassA>().Ctor<ClassB>().Named("classB"); r.For<ClassB>().Use<ClassB>().Named("classB").Ctor<string>("b").Is("named"); r.For<ClassB>().Use<ClassB>().Ctor<string>("b").Is("default"); }); container.GetInstance<ClassA>() .B.B.ShouldBe("named"); } [Fact] public void smart_instance_can_specify_the_constructor() { new SmartInstance<ClassWithMultipleConstructors>(() => new ClassWithMultipleConstructors(null)) .As<IConfiguredInstance>().Constructor.GetParameters().Select(x => x.ParameterType) .ShouldHaveTheSameElementsAs(typeof(IGateway)); new SmartInstance<ClassWithMultipleConstructors>(() => new ClassWithMultipleConstructors(null, null)) .As<IConfiguredInstance>().Constructor.GetParameters().Select(x => x.ParameterType) .ShouldHaveTheSameElementsAs(typeof(IGateway), typeof(IService)); } [Fact] public void integrated_building_with_distinct_ctor_selection() { var container = new Container(x => { x.For<ClassWithMultipleConstructors>().AddInstances(o => { o.Type<ClassWithMultipleConstructors>() .SelectConstructor(() => new ClassWithMultipleConstructors(null)) .Named("One"); o.Type<ClassWithMultipleConstructors>() .SelectConstructor(() => new ClassWithMultipleConstructors(null, null)) .Named("Two"); o.Type<ClassWithMultipleConstructors>().Named("Default"); }); x.For<IGateway>().Use<StubbedGateway>(); x.For<IService>().Use<WhateverService>(); x.For<IWidget>().Use<AWidget>(); }); container.GetInstance<ClassWithMultipleConstructors>("One") .CtorUsed.ShouldBe("One Arg"); container.GetInstance<ClassWithMultipleConstructors>("Two") .CtorUsed.ShouldBe("Two Args"); container.GetInstance<ClassWithMultipleConstructors>("Default") .CtorUsed.ShouldBe("Three Args"); } private class ClassA { public ClassB B { get; private set; } public ClassA(ClassB b) { B = b; } } private class ClassB { public string B { get; private set; } public ClassB(string b) { B = b; } } } public class ClassWithWidgetArrayCtor { private readonly IWidget[] _widgets; public ClassWithWidgetArrayCtor(IWidget[] widgets) { _widgets = widgets; } public IWidget[] Widgets { get { return _widgets; } } } public class ClassWithDoubleProperty { public double Double { get; set; } } public class ClassWithWidgetArraySetter { public IWidget[] Widgets { get; set; } } public class SimplePropertyTarget { public string Name { get; set; } public int Age { get; set; } } public class ClassWithWidget { private readonly IWidget _widget; public ClassWithWidget(IWidget widget) { _widget = widget; } public IWidget Widget { get { return _widget; } } } public class ClassWithWidgetProperty { public IWidget Widget { get; set; } } public class ClassWithMultipleConstructors { public string CtorUsed; public ClassWithMultipleConstructors(IGateway gateway, IService service, IWidget widget) { CtorUsed = "Three Args"; } public ClassWithMultipleConstructors(IGateway gateway, IService service) { CtorUsed = "Two Args"; } public ClassWithMultipleConstructors(IGateway gateway) { CtorUsed = "One Arg"; } } }
using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using LumiSoft.Net.STUN.Message; namespace LumiSoft.Net.STUN.Client { /// <summary> /// This class implements STUN client. Defined in RFC 3489. /// </summary> /// <example> /// <code> /// // Create new socket for STUN client. /// Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); /// socket.Bind(new IPEndPoint(IPAddress.Any,0)); /// /// // Query STUN server /// STUN_Result result = STUN_Client.Query("stunserver.org",3478,socket); /// if(result.NetType != STUN_NetType.UdpBlocked){ /// // UDP blocked or !!!! bad STUN server /// } /// else{ /// IPEndPoint publicEP = result.PublicEndPoint; /// // Do your stuff /// } /// </code> /// </example> public class STUN_Client { #region static method Query /// <summary> /// Gets NAT info from STUN server. /// </summary> /// <param name="host">STUN server name or IP.</param> /// <param name="port">STUN server port. Default port is 3478.</param> /// <param name="socket">UDP socket to use.</param> /// <returns>Returns UDP netwrok info.</returns> /// <exception cref="Exception">Throws exception if unexpected error happens.</exception> public static STUN_Result Query(string host,int port,Socket socket) { if(host == null){ throw new ArgumentNullException("host"); } if(socket == null){ throw new ArgumentNullException("socket"); } if(port < 1){ throw new ArgumentException("Port value must be >= 1 !"); } if(socket.ProtocolType != ProtocolType.Udp){ throw new ArgumentException("Socket must be UDP socket !"); } IPEndPoint remoteEndPoint = new IPEndPoint(System.Net.Dns.GetHostAddresses(host)[0],port); socket.ReceiveTimeout = 3000; socket.SendTimeout = 3000; /* In test I, the client sends a STUN Binding Request to a server, without any flags set in the CHANGE-REQUEST attribute, and without the RESPONSE-ADDRESS attribute. This causes the server to send the response back to the address and port that the request came from. In test II, the client sends a Binding Request with both the "change IP" and "change port" flags from the CHANGE-REQUEST attribute set. In test III, the client sends a Binding Request with only the "change port" flag set. +--------+ | Test | | I | +--------+ | | V /\ /\ N / \ Y / \ Y +--------+ UDP <-------/Resp\--------->/ IP \------------->| Test | Blocked \ ? / \Same/ | II | \ / \? / +--------+ \/ \/ | | N | | V V /\ +--------+ Sym. N / \ | Test | UDP <---/Resp\ | II | Firewall \ ? / +--------+ \ / | \/ V |Y /\ /\ | Symmetric N / \ +--------+ N / \ V NAT <--- / IP \<-----| Test |<--- /Resp\ Open \Same/ | I | \ ? / Internet \? / +--------+ \ / \/ \/ | |Y | | | V | Full | Cone V /\ +--------+ / \ Y | Test |------>/Resp\---->Restricted | III | \ ? / +--------+ \ / \/ |N | Port +------>Restricted */ // Test I STUN_Message test1 = new STUN_Message(); test1.Type = STUN_MessageType.BindingRequest; STUN_Message test1response = DoTransaction(test1,socket,remoteEndPoint); // UDP blocked. if(test1response == null){ return new STUN_Result(STUN_NetType.UdpBlocked,null); } else{ // Test II STUN_Message test2 = new STUN_Message(); test2.Type = STUN_MessageType.BindingRequest; test2.ChangeRequest = new STUN_t_ChangeRequest(true,true); // No NAT. if(socket.LocalEndPoint.Equals(test1response.MappedAddress)){ STUN_Message test2Response = DoTransaction(test2,socket,remoteEndPoint); // Open Internet. if(test2Response != null){ return new STUN_Result(STUN_NetType.OpenInternet,test1response.MappedAddress); } // Symmetric UDP firewall. else{ return new STUN_Result(STUN_NetType.SymmetricUdpFirewall,test1response.MappedAddress); } } // NAT else{ STUN_Message test2Response = DoTransaction(test2,socket,remoteEndPoint); // Full cone NAT. if(test2Response != null){ return new STUN_Result(STUN_NetType.FullCone,test1response.MappedAddress); } else{ /* If no response is received, it performs test I again, but this time, does so to the address and port from the CHANGED-ADDRESS attribute from the response to test I. */ // Test I(II) STUN_Message test12 = new STUN_Message(); test12.Type = STUN_MessageType.BindingRequest; STUN_Message test12Response = DoTransaction(test12,socket,test1response.ChangedAddress); if(test12Response == null){ throw new Exception("STUN Test I(II) dind't get resonse !"); } else{ // Symmetric NAT if(!test12Response.MappedAddress.Equals(test1response.MappedAddress)){ return new STUN_Result(STUN_NetType.Symmetric,test1response.MappedAddress); } else{ // Test III STUN_Message test3 = new STUN_Message(); test3.Type = STUN_MessageType.BindingRequest; test3.ChangeRequest = new STUN_t_ChangeRequest(false,true); STUN_Message test3Response = DoTransaction(test3,socket,test1response.ChangedAddress); // Restricted if(test3Response != null){ return new STUN_Result(STUN_NetType.RestrictedCone,test1response.MappedAddress); } // Port restricted else{ return new STUN_Result(STUN_NetType.PortRestrictedCone,test1response.MappedAddress); } } } } } } } #endregion #region method GetPublicIP /// <summary> /// Resolves local IP to public IP using STUN. /// </summary> /// <param name="stunServer">STUN server.</param> /// <param name="port">STUN server port. Default port is 3478.</param> /// <param name="localIP">Local IP address.</param> /// <returns>Returns public IP address.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stunServer</b> or <b>localIP</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="IOException">Is raised when no connection to STUN server.</exception> public static IPAddress GetPublicIP(string stunServer,int port,IPAddress localIP) { if(stunServer == null){ throw new ArgumentNullException("stunServer"); } if(stunServer == ""){ throw new ArgumentException("Argument 'stunServer' value must be specified."); } if(port < 1){ throw new ArgumentException("Invalid argument 'port' value."); } if(localIP == null){ throw new ArgumentNullException("localIP"); } if(!Core.IsPrivateIP(localIP)){ return localIP; } STUN_Result result = Query(stunServer,port,Core.CreateSocket(new IPEndPoint(localIP,0),ProtocolType.Udp)); if(result.PublicEndPoint != null){ return result.PublicEndPoint.Address; } else{ throw new IOException("Failed to STUN public IP address. STUN server name is invalid or firewall blocks STUN."); } } #endregion #region method GetSharedSecret private void GetSharedSecret() { /* *) Open TLS connection to STUN server. *) Send Shared Secret request. */ /* using(SocketEx socket = new SocketEx()){ socket.RawSocket.ReceiveTimeout = 5000; socket.RawSocket.SendTimeout = 5000; socket.Connect(host,port); socket.SwitchToSSL_AsClient(); // Send Shared Secret request. STUN_Message sharedSecretRequest = new STUN_Message(); sharedSecretRequest.Type = STUN_MessageType.SharedSecretRequest; socket.Write(sharedSecretRequest.ToByteData()); // TODO: Parse message // We must get "Shared Secret" or "Shared Secret Error" response. byte[] receiveBuffer = new byte[256]; socket.RawSocket.Receive(receiveBuffer); STUN_Message sharedSecretRequestResponse = new STUN_Message(); if(sharedSecretRequestResponse.Type == STUN_MessageType.SharedSecretResponse){ } // Shared Secret Error or Unknown response, just try again. else{ // TODO: Unknown response } }*/ } #endregion #region method DoTransaction /// <summary> /// Does STUN transaction. Returns transaction response or null if transaction failed. /// </summary> /// <param name="request">STUN message.</param> /// <param name="socket">Socket to use for send/receive.</param> /// <param name="remoteEndPoint">Remote end point.</param> /// <returns>Returns transaction response or null if transaction failed.</returns> private static STUN_Message DoTransaction(STUN_Message request,Socket socket,IPEndPoint remoteEndPoint) { byte[] requestBytes = request.ToByteData(); DateTime startTime = DateTime.Now; // We do it only 2 sec and retransmit with 100 ms. while(startTime.AddSeconds(2) > DateTime.Now){ try{ socket.SendTo(requestBytes,remoteEndPoint); // We got response. if(socket.Poll(100,SelectMode.SelectRead)){ byte[] receiveBuffer = new byte[512]; socket.Receive(receiveBuffer); // Parse message STUN_Message response = new STUN_Message(); response.Parse(receiveBuffer); // Check that transaction ID matches or not response what we want. if(request.TransactionID.Equals(response.TransactionID)){ return response; } } } catch{ } } return null; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This Class defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; using Internal.Runtime.CompilerServices; #if BIT64 using nuint = System.UInt64; using nint = System.Int64; #else // BIT64 using nuint = System.UInt32; using nint = System.Int32; #endif // BIT64 namespace System.Globalization { public partial class TextInfo : ICloneable, IDeserializationCallback { private enum Tristate : byte { NotInitialized = 0, False = 1, True = 2 } private string _listSeparator; private bool _isReadOnly = false; /* _cultureName is the name of the creating culture. _cultureData is the data that backs this class. _textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO) In the desktop, when we call the sorting dll, it doesn't know how to resolve custom locle names to sort ids so we have to have already resolved this. */ private readonly string _cultureName; // Name of the culture that created this text info private readonly CultureData _cultureData; // Data record for the culture that made us, not for this textinfo private readonly string _textInfoName; // Name of the text info we're using (ie: _cultureData.STEXTINFO) private Tristate _isAsciiCasingSameAsInvariant = Tristate.NotInitialized; // _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant private readonly bool _invariantMode = GlobalizationMode.Invariant; // Invariant text info internal static TextInfo Invariant { get { if (s_Invariant == null) s_Invariant = new TextInfo(CultureData.Invariant); return s_Invariant; } } internal volatile static TextInfo s_Invariant; ////////////////////////////////////////////////////////////////////////// //// //// TextInfo Constructors //// //// Implements CultureInfo.TextInfo. //// ////////////////////////////////////////////////////////////////////////// internal TextInfo(CultureData cultureData) { // This is our primary data source, we don't need most of the rest of this _cultureData = cultureData; _cultureName = _cultureData.CultureName; _textInfoName = _cultureData.STEXTINFO; FinishInitialization(); } void IDeserializationCallback.OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } public virtual int ANSICodePage => _cultureData.IDEFAULTANSICODEPAGE; public virtual int OEMCodePage => _cultureData.IDEFAULTOEMCODEPAGE; public virtual int MacCodePage => _cultureData.IDEFAULTMACCODEPAGE; public virtual int EBCDICCodePage => _cultureData.IDEFAULTEBCDICCODEPAGE; // Just use the LCID from our text info name public int LCID => CultureInfo.GetCultureInfo(_textInfoName).LCID; public string CultureName => _textInfoName; public bool IsReadOnly => _isReadOnly; ////////////////////////////////////////////////////////////////////////// //// //// Clone //// //// Is the implementation of ICloneable. //// ////////////////////////////////////////////////////////////////////////// public virtual object Clone() { object o = MemberwiseClone(); ((TextInfo)o).SetReadOnlyState(false); return o; } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// public static TextInfo ReadOnly(TextInfo textInfo) { if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); } if (textInfo.IsReadOnly) { return textInfo; } TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone()); clonedTextInfo.SetReadOnlyState(true); return clonedTextInfo; } private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } internal void SetReadOnlyState(bool readOnly) { _isReadOnly = readOnly; } //////////////////////////////////////////////////////////////////////// // // ListSeparator // // Returns the string used to separate items in a list. // //////////////////////////////////////////////////////////////////////// public virtual string ListSeparator { get { if (_listSeparator == null) { _listSeparator = _cultureData.SLIST; } return _listSeparator; } set { if (value == null) { throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } VerifyWritable(); _listSeparator = value; } } //////////////////////////////////////////////////////////////////////// // // ToLower // // Converts the character or string to lower case. Certain locales // have different casing semantics from the file systems in Win32. // //////////////////////////////////////////////////////////////////////// public virtual char ToLower(char c) { if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant)) { return ToLowerAsciiInvariant(c); } return ChangeCase(c, toUpper: false); } public virtual string ToLower(string str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } if (_invariantMode) { return ToLowerAsciiInvariant(str); } return ChangeCaseCommon<ToLowerConversion>(str); } private unsafe char ChangeCase(char c, bool toUpper) { Debug.Assert(!_invariantMode); char dst = default; ChangeCase(&c, 1, &dst, 1, toUpper); return dst; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ChangeCaseToLower(ReadOnlySpan<char> source, Span<char> destination) { Debug.Assert(destination.Length >= source.Length); ChangeCaseCommon<ToLowerConversion>(ref MemoryMarshal.GetReference(source), ref MemoryMarshal.GetReference(destination), source.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ChangeCaseToUpper(ReadOnlySpan<char> source, Span<char> destination) { Debug.Assert(destination.Length >= source.Length); ChangeCaseCommon<ToUpperConversion>(ref MemoryMarshal.GetReference(source), ref MemoryMarshal.GetReference(destination), source.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ChangeCaseCommon<TConversion>(ReadOnlySpan<char> source, Span<char> destination) where TConversion : struct { Debug.Assert(destination.Length >= source.Length); ChangeCaseCommon<TConversion>(ref MemoryMarshal.GetReference(source), ref MemoryMarshal.GetReference(destination), source.Length); } private unsafe void ChangeCaseCommon<TConversion>(ref char source, ref char destination, int charCount) where TConversion : struct { Debug.Assert(typeof(TConversion) == typeof(ToUpperConversion) || typeof(TConversion) == typeof(ToLowerConversion)); bool toUpper = typeof(TConversion) == typeof(ToUpperConversion); // JIT will treat this as a constant in release builds Debug.Assert(!_invariantMode); Debug.Assert(charCount >= 0); if (charCount == 0) { goto Return; } fixed (char* pSource = &source) fixed (char* pDestination = &destination) { nuint currIdx = 0; // in chars if (IsAsciiCasingSameAsInvariant) { // Read 4 chars (two 32-bit integers) at a time if (charCount >= 4) { nuint lastIndexWhereCanReadFourChars = (uint)charCount - 4; do { // This is a mostly branchless case change routine. Generally speaking, we assume that the majority // of input is ASCII, so the 'if' checks below should normally evaluate to false. However, within // the ASCII data, we expect that characters of either case might be about equally distributed, so // we want the case change operation itself to be branchless. This gives optimal performance in the // common case. We also expect that developers aren't passing very long (16+ character) strings into // this method, so we won't bother vectorizing until data shows us that it's worthwhile to do so. uint tempValue = Unsafe.ReadUnaligned<uint>(pSource + currIdx); if (!Utf16Utility.AllCharsInUInt32AreAscii(tempValue)) { goto NonAscii; } tempValue = (toUpper) ? Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(tempValue) : Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(tempValue); Unsafe.WriteUnaligned<uint>(pDestination + currIdx, tempValue); tempValue = Unsafe.ReadUnaligned<uint>(pSource + currIdx + 2); if (!Utf16Utility.AllCharsInUInt32AreAscii(tempValue)) { goto NonAsciiSkipTwoChars; } tempValue = (toUpper) ? Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(tempValue) : Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(tempValue); Unsafe.WriteUnaligned<uint>(pDestination + currIdx + 2, tempValue); currIdx += 4; } while (currIdx <= lastIndexWhereCanReadFourChars); // At this point, there are fewer than 4 characters remaining to convert. Debug.Assert((uint)charCount - currIdx < 4); } // If there are 2 or 3 characters left to convert, we'll convert 2 of them now. if ((charCount & 2) != 0) { uint tempValue = Unsafe.ReadUnaligned<uint>(pSource + currIdx); if (!Utf16Utility.AllCharsInUInt32AreAscii(tempValue)) { goto NonAscii; } tempValue = (toUpper) ? Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(tempValue) : Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(tempValue); Unsafe.WriteUnaligned<uint>(pDestination + currIdx, tempValue); currIdx += 2; } // If there's a single character left to convert, do it now. if ((charCount & 1) != 0) { uint tempValue = pSource[currIdx]; if (tempValue > 0x7Fu) { goto NonAscii; } tempValue = (toUpper) ? Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(tempValue) : Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(tempValue); pDestination[currIdx] = (char)tempValue; } // And we're finished! goto Return; // If we reached this point, we found non-ASCII data. // Fall back down the p/invoke code path. NonAsciiSkipTwoChars: currIdx += 2; NonAscii: Debug.Assert(currIdx < (uint)charCount, "We somehow read past the end of the buffer."); charCount -= (int)currIdx; } // We encountered non-ASCII data and therefore can't perform invariant case conversion; or the requested culture // has a case conversion that's different from the invariant culture, even for ASCII data (e.g., tr-TR converts // 'i' (U+0069) to Latin Capital Letter I With Dot Above (U+0130)). ChangeCase(pSource + currIdx, charCount, pDestination + currIdx, charCount, toUpper); } Return: return; } private unsafe string ChangeCaseCommon<TConversion>(string source) where TConversion : struct { Debug.Assert(typeof(TConversion) == typeof(ToUpperConversion) || typeof(TConversion) == typeof(ToLowerConversion)); bool toUpper = typeof(TConversion) == typeof(ToUpperConversion); // JIT will treat this as a constant in release builds Debug.Assert(!_invariantMode); Debug.Assert(source != null); // If the string is empty, we're done. if (source.Length == 0) { return string.Empty; } fixed (char* pSource = source) { nuint currIdx = 0; // in chars // If this culture's casing for ASCII is the same as invariant, try to take // a fast path that'll work in managed code and ASCII rather than calling out // to the OS for culture-aware casing. if (IsAsciiCasingSameAsInvariant) { // Read 2 chars (one 32-bit integer) at a time if (source.Length >= 2) { nuint lastIndexWhereCanReadTwoChars = (uint)source.Length - 2; do { // See the comments in ChangeCaseCommon<TConversion>(ROS<char>, Span<char>) for a full explanation of the below code. uint tempValue = Unsafe.ReadUnaligned<uint>(pSource + currIdx); if (!Utf16Utility.AllCharsInUInt32AreAscii(tempValue)) { goto NotAscii; } if ((toUpper) ? Utf16Utility.UInt32ContainsAnyLowercaseAsciiChar(tempValue) : Utf16Utility.UInt32ContainsAnyUppercaseAsciiChar(tempValue)) { goto AsciiMustChangeCase; } currIdx += 2; } while (currIdx <= lastIndexWhereCanReadTwoChars); } // If there's a single character left to convert, do it now. if ((source.Length & 1) != 0) { uint tempValue = pSource[currIdx]; if (tempValue > 0x7Fu) { goto NotAscii; } if ((toUpper) ? ((tempValue - 'a') <= (uint)('z' - 'a')) : ((tempValue - 'A') <= (uint)('Z' - 'A'))) { goto AsciiMustChangeCase; } } // We got through all characters without finding anything that needed to change - done! return source; AsciiMustChangeCase: { // We reached ASCII data that requires a case change. // This will necessarily allocate a new string, but let's try to stay within the managed (non-localization tables) // conversion code path if we can. string result = string.FastAllocateString(source.Length); // changing case uses simple folding: doesn't change UTF-16 code unit count // copy existing known-good data into the result Span<char> resultSpan = new Span<char>(ref result.GetRawStringData(), result.Length); source.AsSpan(0, (int)currIdx).CopyTo(resultSpan); // and re-run the fast span-based logic over the remainder of the data ChangeCaseCommon<TConversion>(source.AsSpan((int)currIdx), resultSpan.Slice((int)currIdx)); return result; } } NotAscii: { // We reached non-ASCII data *or* the requested culture doesn't map ASCII data the same way as the invariant culture. // In either case we need to fall back to the localization tables. string result = string.FastAllocateString(source.Length); // changing case uses simple folding: doesn't change UTF-16 code unit count if (currIdx > 0) { // copy existing known-good data into the result Span<char> resultSpan = new Span<char>(ref result.GetRawStringData(), result.Length); source.AsSpan(0, (int)currIdx).CopyTo(resultSpan); } // and run the culture-aware logic over the remainder of the data fixed (char* pResult = result) { ChangeCase(pSource + currIdx, source.Length - (int)currIdx, pResult + currIdx, result.Length - (int)currIdx, toUpper); } return result; } } } private static unsafe string ToLowerAsciiInvariant(string s) { if (s.Length == 0) { return string.Empty; } fixed (char* pSource = s) { int i = 0; while (i < s.Length) { if ((uint)(pSource[i] - 'A') <= (uint)('Z' - 'A')) { break; } i++; } if (i >= s.Length) { return s; } string result = string.FastAllocateString(s.Length); fixed (char* pResult = result) { for (int j = 0; j < i; j++) { pResult[j] = pSource[j]; } pResult[i] = (char)(pSource[i] | 0x20); i++; while (i < s.Length) { pResult[i] = ToLowerAsciiInvariant(pSource[i]); i++; } } return result; } } internal static void ToLowerAsciiInvariant(ReadOnlySpan<char> source, Span<char> destination) { Debug.Assert(destination.Length >= source.Length); for (int i = 0; i < source.Length; i++) { destination[i] = ToLowerAsciiInvariant(source[i]); } } private static unsafe string ToUpperAsciiInvariant(string s) { if (s.Length == 0) { return string.Empty; } fixed (char* pSource = s) { int i = 0; while (i < s.Length) { if ((uint)(pSource[i] - 'a') <= (uint)('z' - 'a')) { break; } i++; } if (i >= s.Length) { return s; } string result = string.FastAllocateString(s.Length); fixed (char* pResult = result) { for (int j = 0; j < i; j++) { pResult[j] = pSource[j]; } pResult[i] = (char)(pSource[i] & ~0x20); i++; while (i < s.Length) { pResult[i] = ToUpperAsciiInvariant(pSource[i]); i++; } } return result; } } internal static void ToUpperAsciiInvariant(ReadOnlySpan<char> source, Span<char> destination) { Debug.Assert(destination.Length >= source.Length); for (int i = 0; i < source.Length; i++) { destination[i] = ToUpperAsciiInvariant(source[i]); } } private static char ToLowerAsciiInvariant(char c) { if ((uint)(c - 'A') <= (uint)('Z' - 'A')) { c = (char)(c | 0x20); } return c; } //////////////////////////////////////////////////////////////////////// // // ToUpper // // Converts the character or string to upper case. Certain locales // have different casing semantics from the file systems in Win32. // //////////////////////////////////////////////////////////////////////// public virtual char ToUpper(char c) { if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant)) { return ToUpperAsciiInvariant(c); } return ChangeCase(c, toUpper: true); } public virtual string ToUpper(string str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } if (_invariantMode) { return ToUpperAsciiInvariant(str); } return ChangeCaseCommon<ToUpperConversion>(str); } internal static char ToUpperAsciiInvariant(char c) { if ((uint)(c - 'a') <= (uint)('z' - 'a')) { c = (char)(c & ~0x20); } return c; } private static bool IsAscii(char c) { return c < 0x80; } private bool IsAsciiCasingSameAsInvariant { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_isAsciiCasingSameAsInvariant == Tristate.NotInitialized) { PopulateIsAsciiCasingSameAsInvariant(); } Debug.Assert(_isAsciiCasingSameAsInvariant == Tristate.True || _isAsciiCasingSameAsInvariant == Tristate.False); return (_isAsciiCasingSameAsInvariant == Tristate.True); } } [MethodImpl(MethodImplOptions.NoInlining)] private void PopulateIsAsciiCasingSameAsInvariant() { bool compareResult = CultureInfo.GetCultureInfo(_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", CompareOptions.IgnoreCase) == 0; _isAsciiCasingSameAsInvariant = (compareResult) ? Tristate.True : Tristate.False; } // IsRightToLeft // // Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars // public bool IsRightToLeft => _cultureData.IsRightToLeft; //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same CultureInfo as the current instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(object obj) { TextInfo that = obj as TextInfo; if (that != null) { return CultureName.Equals(that.CultureName); } return false; } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for CultureInfo A // and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return CultureName.GetHashCode(); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // TextInfo. // //////////////////////////////////////////////////////////////////////// public override string ToString() { return "TextInfo - " + _cultureData.CultureName; } // // Titlecasing: // ----------- // Titlecasing refers to a casing practice wherein the first letter of a word is an uppercase letter // and the rest of the letters are lowercase. The choice of which words to titlecase in headings // and titles is dependent on language and local conventions. For example, "The Merry Wives of Windor" // is the appropriate titlecasing of that play's name in English, with the word "of" not titlecased. // In German, however, the title is "Die lustigen Weiber von Windsor," and both "lustigen" and "von" // are not titlecased. In French even fewer words are titlecased: "Les joyeuses commeres de Windsor." // // Moreover, the determination of what actually constitutes a word is language dependent, and this can // influence which letter or letters of a "word" are uppercased when titlecasing strings. For example // "l'arbre" is considered two words in French, whereas "can't" is considered one word in English. // public unsafe string ToTitleCase(string str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } if (str.Length == 0) { return str; } StringBuilder result = new StringBuilder(); string lowercaseData = null; // Store if the current culture is Dutch (special case) bool isDutchCulture = CultureName.StartsWith("nl-", StringComparison.OrdinalIgnoreCase); for (int i = 0; i < str.Length; i++) { UnicodeCategory charType; int charLen; charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen); if (char.CheckLetter(charType)) { // Special case to check for Dutch specific titlecasing with "IJ" characters // at the beginning of a word if (isDutchCulture && i < str.Length - 1 && (str[i] == 'i' || str[i] == 'I') && (str[i+1] == 'j' || str[i+1] == 'J')) { result.Append("IJ"); i += 2; } else { // Do the titlecasing for the first character of the word. i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1; } // // Convert the characters until the end of the this word // to lowercase. // int lowercaseStart = i; // // Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc) // This is in line with Word 2000 behavior of titlecasing. // bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter); // Use a loop to find all of the other letters following this letter. while (i < str.Length) { charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen); if (IsLetterCategory(charType)) { if (charType == UnicodeCategory.LowercaseLetter) { hasLowerCase = true; } i += charLen; } else if (str[i] == '\'') { i++; if (hasLowerCase) { if (lowercaseData == null) { lowercaseData = ToLower(str); } result.Append(lowercaseData, lowercaseStart, i - lowercaseStart); } else { result.Append(str, lowercaseStart, i - lowercaseStart); } lowercaseStart = i; hasLowerCase = true; } else if (!IsWordSeparator(charType)) { // This category is considered to be part of the word. // This is any category that is marked as false in wordSeprator array. i+= charLen; } else { // A word separator. Break out of the loop. break; } } int count = i - lowercaseStart; if (count > 0) { if (hasLowerCase) { if (lowercaseData == null) { lowercaseData = ToLower(str); } result.Append(lowercaseData, lowercaseStart, count); } else { result.Append(str, lowercaseStart, count); } } if (i < str.Length) { // not a letter, just append it i = AddNonLetter(ref result, ref str, i, charLen); } } else { // not a letter, just append it i = AddNonLetter(ref result, ref str, i, charLen); } } return result.ToString(); } private static int AddNonLetter(ref StringBuilder result, ref string input, int inputIndex, int charLen) { Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); if (charLen == 2) { // Surrogate pair result.Append(input[inputIndex++]); result.Append(input[inputIndex]); } else { result.Append(input[inputIndex]); } return inputIndex; } private int AddTitlecaseLetter(ref StringBuilder result, ref string input, int inputIndex, int charLen) { Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); if (charLen == 2) { // for surrogate pairs do a ToUpper operation on the substring ReadOnlySpan<char> src = input.AsSpan(inputIndex, 2); if (_invariantMode) { result.Append(src); // surrogate pair in invariant mode, so changing case is a nop } else { Span<char> dst = stackalloc char[2]; ChangeCaseToUpper(src, dst); result.Append(dst); } inputIndex++; } else { switch (input[inputIndex]) { // // For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below. case (char) 0x01C4: // DZ with Caron -> Dz with Caron case (char) 0x01C5: // Dz with Caron -> Dz with Caron case (char) 0x01C6: // dz with Caron -> Dz with Caron result.Append((char) 0x01C5); break; case (char) 0x01C7: // LJ -> Lj case (char) 0x01C8: // Lj -> Lj case (char) 0x01C9: // lj -> Lj result.Append((char) 0x01C8); break; case (char) 0x01CA: // NJ -> Nj case (char) 0x01CB: // Nj -> Nj case (char) 0x01CC: // nj -> Nj result.Append((char) 0x01CB); break; case (char) 0x01F1: // DZ -> Dz case (char) 0x01F2: // Dz -> Dz case (char) 0x01F3: // dz -> Dz result.Append((char) 0x01F2); break; default: result.Append(ToUpper(input[inputIndex])); break; } } return inputIndex; } // // Used in ToTitleCase(): // When we find a starting letter, the following array decides if a category should be // considered as word seprator or not. // private const int c_wordSeparatorMask = /* false */ (0 << 0) | // UppercaseLetter = 0, /* false */ (0 << 1) | // LowercaseLetter = 1, /* false */ (0 << 2) | // TitlecaseLetter = 2, /* false */ (0 << 3) | // ModifierLetter = 3, /* false */ (0 << 4) | // OtherLetter = 4, /* false */ (0 << 5) | // NonSpacingMark = 5, /* false */ (0 << 6) | // SpacingCombiningMark = 6, /* false */ (0 << 7) | // EnclosingMark = 7, /* false */ (0 << 8) | // DecimalDigitNumber = 8, /* false */ (0 << 9) | // LetterNumber = 9, /* false */ (0 << 10) | // OtherNumber = 10, /* true */ (1 << 11) | // SpaceSeparator = 11, /* true */ (1 << 12) | // LineSeparator = 12, /* true */ (1 << 13) | // ParagraphSeparator = 13, /* true */ (1 << 14) | // Control = 14, /* true */ (1 << 15) | // Format = 15, /* false */ (0 << 16) | // Surrogate = 16, /* false */ (0 << 17) | // PrivateUse = 17, /* true */ (1 << 18) | // ConnectorPunctuation = 18, /* true */ (1 << 19) | // DashPunctuation = 19, /* true */ (1 << 20) | // OpenPunctuation = 20, /* true */ (1 << 21) | // ClosePunctuation = 21, /* true */ (1 << 22) | // InitialQuotePunctuation = 22, /* true */ (1 << 23) | // FinalQuotePunctuation = 23, /* true */ (1 << 24) | // OtherPunctuation = 24, /* true */ (1 << 25) | // MathSymbol = 25, /* true */ (1 << 26) | // CurrencySymbol = 26, /* true */ (1 << 27) | // ModifierSymbol = 27, /* true */ (1 << 28) | // OtherSymbol = 28, /* false */ (0 << 29); // OtherNotAssigned = 29; private static bool IsWordSeparator(UnicodeCategory category) { return (c_wordSeparatorMask & (1 << (int) category)) != 0; } private static bool IsLetterCategory(UnicodeCategory uc) { return (uc == UnicodeCategory.UppercaseLetter || uc == UnicodeCategory.LowercaseLetter || uc == UnicodeCategory.TitlecaseLetter || uc == UnicodeCategory.ModifierLetter || uc == UnicodeCategory.OtherLetter); } // A dummy struct that is used for 'ToUpper' in generic parameters private readonly struct ToUpperConversion { } // A dummy struct that is used for 'ToLower' in generic parameters private readonly struct ToLowerConversion { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Threading.Tasks; using Obvs.Configuration; using Obvs.Extensions; using Obvs.Types; namespace Obvs { public interface IServiceBus : IServiceBusClient, IServiceBus<IMessage, ICommand, IEvent, IRequest, IResponse> { } public interface IServiceBus<TMessage, TCommand, TEvent, TRequest, TResponse> : IServiceBusClient<TMessage, TCommand, TEvent, TRequest, TResponse> where TMessage : class where TCommand : class, TMessage where TEvent : class, TMessage where TRequest : class, TMessage where TResponse : class, TMessage { IObservable<TRequest> Requests { get; } IObservable<TCommand> Commands { get; } Task PublishAsync(TEvent ev); Task ReplyAsync(TRequest request, TResponse response); } public class ServiceBus : IServiceBus, IDisposable { private readonly IServiceBus<IMessage, ICommand, IEvent, IRequest, IResponse> _serviceBus; // ReSharper disable once UnusedMember.Global public ServiceBus(IEnumerable<IServiceEndpointClient<IMessage, ICommand, IEvent, IRequest, IResponse>> endpointClients, IEnumerable<IServiceEndpoint<IMessage, ICommand, IEvent, IRequest, IResponse>> endpoints, IRequestCorrelationProvider<IRequest, IResponse> requestCorrelationProvider = null) : this(new ServiceBus<IMessage, ICommand, IEvent, IRequest, IResponse>(endpointClients, endpoints, requestCorrelationProvider ?? new DefaultRequestCorrelationProvider())) { } public ServiceBus(IServiceBus<IMessage, ICommand, IEvent, IRequest, IResponse> serviceBus) { _serviceBus = serviceBus; } // ReSharper disable once UnusedMember.Global public static ICanAddEndpoint<IMessage, ICommand, IEvent, IRequest, IResponse> Configure() { return new ServiceBusFluentCreator<IMessage, ICommand, IEvent, IRequest, IResponse>(new DefaultRequestCorrelationProvider()); } public IObservable<IEvent> Events => _serviceBus.Events; public Task SendAsync(ICommand command) { return _serviceBus.SendAsync(command); } public Task SendAsync(IEnumerable<ICommand> commands) { return _serviceBus.SendAsync(commands); } public IObservable<IResponse> GetResponses(IRequest request) { return _serviceBus.GetResponses(request); } public IObservable<T> GetResponses<T>(IRequest request) where T : IResponse { return _serviceBus.GetResponses<T>(request); } public IObservable<T> GetResponse<T>(IRequest request) where T : IResponse { return _serviceBus.GetResponse<T>(request); } public IObservable<Exception> Exceptions => _serviceBus.Exceptions; public IObservable<IRequest> Requests => _serviceBus.Requests; public IObservable<ICommand> Commands => _serviceBus.Commands; public Task PublishAsync(IEvent ev) { return _serviceBus.PublishAsync(ev); } public Task ReplyAsync(IRequest request, IResponse response) { return _serviceBus.ReplyAsync(request, response); } public void Dispose() { ((IDisposable)_serviceBus).Dispose(); } } public class ServiceBus<TMessage, TCommand, TEvent, TRequest, TResponse> : ServiceBusClient<TMessage, TCommand, TEvent, TRequest, TResponse>, IServiceBus<TMessage, TCommand, TEvent, TRequest, TResponse> where TMessage : class where TCommand : class, TMessage where TEvent : class, TMessage where TRequest : class, TMessage where TResponse : class, TMessage { private readonly IRequestCorrelationProvider<TRequest, TResponse> _requestCorrelationProvider; public ServiceBus(IEnumerable<IServiceEndpointClient<TMessage, TCommand, TEvent, TRequest, TResponse>> endpointClients, IEnumerable<IServiceEndpoint<TMessage, TCommand, TEvent, TRequest, TResponse>> endpoints, IRequestCorrelationProvider<TRequest, TResponse> requestCorrelationProvider, IServiceBus<TMessage, TCommand, TEvent, TRequest, TResponse> localBus = null, LocalBusOptions localBusOption = LocalBusOptions.MessagesWithNoEndpointClients) : base(endpointClients, endpoints, requestCorrelationProvider, localBus, localBusOption) { _requestCorrelationProvider = requestCorrelationProvider; Requests = Endpoints .Select(endpoint => endpoint.RequestsWithErrorHandling(_exceptions)) .Merge() .Merge(GetLocalRequests()) .PublishRefCountRetriable(); Commands = Endpoints .Select(endpoint => endpoint.CommandsWithErrorHandling(_exceptions)) .Merge() .Merge(GetLocalCommands()) .PublishRefCountRetriable(); } public IObservable<TRequest> Requests { get; } public IObservable<TCommand> Commands { get; } public Task PublishAsync(TEvent ev) { var exceptions = new List<Exception>(); var tasks = EndpointsThatCanHandle(ev) .Select(endpoint => Catch(() => endpoint.PublishAsync(ev), exceptions, EventErrorMessage(endpoint))) .Union(PublishLocal(ev, exceptions)) .ToArray(); if (exceptions.Any()) { throw new AggregateException(EventErrorMessage(ev), exceptions); } if (tasks.Length == 0) { throw new Exception( $"No endpoint or local bus configured for {ev}, please check your ServiceBus configuration."); } return Task.WhenAll(tasks); } public Task ReplyAsync(TRequest request, TResponse response) { if (_requestCorrelationProvider == null) { throw new InvalidOperationException("Please configure the ServiceBus with a IRequestCorrelationProvider using the fluent configuration extension method .CorrelatesRequestWith()"); } _requestCorrelationProvider.SetCorrelationIds(request, response); var exceptions = new List<Exception>(); var tasks = EndpointsThatCanHandle(response) .Select(endpoint => Catch(() => endpoint.ReplyAsync(request, response), exceptions, ReplyErrorMessage(endpoint))) .Union(ReplyLocal(request, response, exceptions)) .ToArray(); if (exceptions.Any()) { throw new AggregateException(ReplyErrorMessage(request, response), exceptions); } return Task.WhenAll(tasks); } // ReSharper disable once UnusedMember.Global public static ICanAddEndpoint<TMessage, TCommand, TEvent, TRequest, TResponse> Configure() { return new ServiceBusFluentCreator<TMessage, TCommand, TEvent, TRequest, TResponse>(); } private IEnumerable<IServiceEndpoint<TMessage, TCommand, TEvent, TRequest, TResponse>> EndpointsThatCanHandle(TMessage message) { return Endpoints.Where(endpoint => endpoint.CanHandle(message)).ToArray(); } public override void Dispose() { base.Dispose(); foreach (var endpoint in Endpoints) { endpoint.Dispose(); } } } }
// 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 Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.CompletionProviders.XmlDocCommentCompletion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.Completion.CompletionProviders.XmlDocCommentCompletion { [ExportCompletionProvider("DocCommentCompletionProvider", LanguageNames.CSharp)] internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider { public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options) { return text[characterPosition] == '<'; } protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>(); if (parentTrivia == null) { return null; } var items = new List<CompletionItem>(); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var span = CompletionUtilities.GetTextChangeSpan(text, position); var attachedToken = parentTrivia.ParentTrivia.Token; if (attachedToken.Kind() == SyntaxKind.None) { return null; } var semanticModel = await document.GetSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false); ISymbol declaredSymbol = null; var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken); } else { var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); } } if (declaredSymbol != null) { items.AddRange(GetTagsForSymbol(declaredSymbol, span, parentTrivia, token)); } if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText || (token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) || (token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement))) { if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement) { items.AddRange(GetNestedTags(span)); } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems(span)); } if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) & token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement)) { var element = (XmlElementSyntax)token.Parent.Parent.Parent; if (element.StartTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems(span)); } } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListHeaderTagName) { items.AddRange(GetListHeaderItems(span)); } if (token.Parent.Parent is DocumentationCommentTriviaSyntax) { items.AddRange(GetTopLevelSingleUseNames(parentTrivia, span)); items.AddRange(GetTopLevelRepeatableItems(span)); } } if (token.Parent.Kind() == SyntaxKind.XmlElementStartTag) { var startTag = (XmlElementStartTagSyntax)token.Parent; if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems(span)); } if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListHeaderTagName) { items.AddRange(GetListHeaderItems(span)); } } items.AddRange(GetAlwaysVisibleItems(span)); return items; } private IEnumerable<CompletionItem> GetTopLevelSingleUseNames(DocumentationCommentTriviaSyntax parentTrivia, TextSpan span) { var names = new HashSet<string>(new[] { SummaryTagName, RemarksTagName, ExampleTagName, CompletionListTagName }); RemoveExistingTags(parentTrivia, names, (x) => x.StartTag.Name.LocalName.ValueText); return names.Select(n => GetItem(n, span)); } private void RemoveExistingTags(DocumentationCommentTriviaSyntax parentTrivia, ISet<string> names, Func<XmlElementSyntax, string> selector) { if (parentTrivia != null) { foreach (var node in parentTrivia.Content) { var element = node as XmlElementSyntax; if (element != null) { names.Remove(selector(element)); } } } } private IEnumerable<CompletionItem> GetTagsForSymbol(ISymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { if (symbol is IMethodSymbol) { return GetTagsForMethod((IMethodSymbol)symbol, filterSpan, trivia, token); } if (symbol is IPropertySymbol) { return GetTagsForProperty((IPropertySymbol)symbol, filterSpan, trivia, token); } if (symbol is INamedTypeSymbol) { return GetTagsForType((INamedTypeSymbol)symbol, filterSpan, trivia); } return SpecializedCollections.EmptyEnumerable<CompletionItem>(); } private IEnumerable<CompletionItem> GetTagsForType(INamedTypeSymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia) { var items = new List<CompletionItem>(); var typeParameters = symbol.TypeParameters.Select(p => p.Name).ToSet(); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName)); items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter(TypeParamTagName, t), GetCompletionItemRules()))); return items; } private string AttributeSelector(XmlElementSyntax element, string attribute) { if (!element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; var nameAttribute = startTag.Attributes.OfType<XmlNameAttributeSyntax>().FirstOrDefault(a => a.Name.LocalName.ValueText == NameAttributeName); if (nameAttribute != null) { if (startTag.Name.LocalName.ValueText == attribute) { return nameAttribute.Identifier.Identifier.ValueText; } } } return null; } private IEnumerable<XmlDocCommentCompletionItem> GetTagsForProperty(IPropertySymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { var items = new List<XmlDocCommentCompletionItem>(); if (symbol.IsIndexer) { var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); // User is trying to write a name, try to suggest only names. if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) || (token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute))) { string parentElementName = null; var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>(); if (emptyElement != null) { parentElementName = emptyElement.Name.LocalName.Text; } // We're writing the name of a paramref if (parentElementName == ParamRefTagName) { items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, p, GetCompletionItemRules()))); } return items; } RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName)); items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter(ParamTagName, p), GetCompletionItemRules()))); } var typeParameters = symbol.GetTypeArguments().Select(p => p.Name).ToSet(); items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, TypeParamTagName, NameAttributeName, t, GetCompletionItemRules()))); items.Add(new XmlDocCommentCompletionItem(this, filterSpan, "value", GetCompletionItemRules())); return items; } private IEnumerable<CompletionItem> GetTagsForMethod(IMethodSymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { var items = new List<CompletionItem>(); var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); var typeParameters = symbol.TypeParameters.Select(t => t.Name).ToSet(); // User is trying to write a name, try to suggest only names. if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) || (token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute))) { string parentElementName = null; var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>(); if (emptyElement != null) { parentElementName = emptyElement.Name.LocalName.Text; } // We're writing the name of a paramref or typeparamref if (parentElementName == ParamRefTagName) { items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, p, GetCompletionItemRules()))); } else if (parentElementName == TypeParamRefTagName) { items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, t, GetCompletionItemRules()))); } return items; } var returns = true; RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName)); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName)); foreach (var node in trivia.Content) { var element = node as XmlElementSyntax; if (element != null && !element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; if (startTag.Name.LocalName.ValueText == ReturnsTagName) { returns = false; break; } } } items.AddRange(parameters.Select(p => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter(ParamTagName, p), GetCompletionItemRules()))); items.AddRange(typeParameters.Select(t => new XmlDocCommentCompletionItem(this, filterSpan, FormatParameter(TypeParamTagName, t), GetCompletionItemRules()))); if (returns && !symbol.ReturnsVoid) { items.Add(new XmlDocCommentCompletionItem(this, filterSpan, ReturnsTagName, GetCompletionItemRules())); } return items; } protected override AbstractXmlDocCommentCompletionItemRules GetCompletionItemRules() { return XmlDocCommentCompletionItemRules.Instance; } } }
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 #define UNITY_4 #endif #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 #define UNITY_LE_4_3 #endif using UnityEngine; using System.Collections.Generic; using UnityEditor; namespace Pathfinding { /** Simple GUIUtility functions */ public class GUIUtilityx { public static Color prevCol; public static void SetColor (Color col) { prevCol = GUI.color; GUI.color = col; } public static void ResetColor () { GUI.color = prevCol; } } /** Handles fading effects and also some custom GUI functions such as LayerMaskField */ public class EditorGUILayoutx { Rect fadeAreaRect; Rect lastAreaRect; //public static List<Rect> currentRects; //public static List<Rect> lastRects; //public static List<float> values; public Dictionary<string, FadeArea> fadeAreas; //public static Dictionary<string, Rect> lastRects; //public static Dictionary<string, float> values; //public static List<bool> open; public static int currentDepth = 0; public static int currentIndex = 0; public static bool isLayout = false; public static Editor editor; public static GUIStyle defaultAreaStyle; public static GUIStyle defaultLabelStyle; public static GUIStyle stretchStyle; public static GUIStyle stretchStyleThin; public static float speed = 6; public static bool fade = true; public static bool fancyEffects = true; public Stack<FadeArea> stack; public void RemoveID (string id) { if (fadeAreas == null) { return; } fadeAreas.Remove (id); } public bool DrawID (string id) { if (fadeAreas == null) { return false; } //Debug.Log ("Draw "+id+" "+fadeAreas[id].value.ToString ("0.00")); return fadeAreas[id].Show (); /*if (values == null) { return false; } return values[id] > 0.002F;*/ } public FadeArea BeginFadeArea (bool open,string label, string id) { return BeginFadeArea (open,label,id, defaultAreaStyle); } public FadeArea BeginFadeArea (bool open,string label, string id, GUIStyle areaStyle) { return BeginFadeArea (open, label, id, areaStyle, defaultLabelStyle); } public FadeArea BeginFadeArea (bool open,string label, string id, GUIStyle areaStyle, GUIStyle labelStyle) { //Rect r = EditorGUILayout.BeginVertical (areaStyle); Color tmp1 = GUI.color; FadeArea fadeArea = BeginFadeArea (open,id, 20,areaStyle); //GUI.Box (r,"",areaStyle); Color tmp2 = GUI.color; GUI.color = tmp1; if (label != "") { if (GUILayout.Button (label,labelStyle)) { fadeArea.open = !fadeArea.open; editor.Repaint (); } } GUI.color = tmp2; //EditorGUILayout.EndVertical (); return fadeArea; } public class FadeArea { public Rect currentRect; public Rect lastRect; public float value; public float lastUpdate; /** Is this area open. * This is not the same as if any contents are visible, use #Show for that. */ public bool open; public Color preFadeColor; /** Update the visibility in Layout to avoid complications with different events not drawing the same thing */ private bool visibleInLayout; public void Switch () { lastRect = currentRect; } public FadeArea (bool open) { value = open ? 1 : 0; } /** Should anything inside this FadeArea be drawn. * Should be called every frame ( in all events ) for best results. */ public bool Show () { bool v = open || value > 0F; if ( Event.current.type == EventType.Layout ) { visibleInLayout = v; } return visibleInLayout; } public static implicit operator bool (FadeArea o) { return o.open; } } public FadeArea BeginFadeArea (bool open, string id) { return BeginFadeArea (open,id,0); } //openMultiple is set to false if only 1 BeginVertical call needs to be made in the BeginFadeArea (open, id) function. //The EndFadeArea function always closes two BeginVerticals public FadeArea BeginFadeArea (bool open, string id, float minHeight) { return BeginFadeArea (open, id, minHeight, GUIStyle.none); } /** Make sure the stack is cleared at the start of a frame */ public void ClearStack () { if ( stack != null ) stack.Clear (); } public FadeArea BeginFadeArea (bool open, string id, float minHeight, GUIStyle areaStyle) { if (editor == null) { Debug.LogError ("You need to set the 'EditorGUIx.editor' variable before calling this function"); return null; } if (stretchStyle == null) { stretchStyle = new GUIStyle (); stretchStyle.stretchWidth = true; //stretchStyle.padding = new RectOffset (0,0,4,14); //stretchStyle.margin = new RectOffset (0,0,4,4); } if (stack == null) { stack = new Stack<FadeArea>(); } if (fadeAreas == null) { fadeAreas = new Dictionary<string, FadeArea> (); } if (!fadeAreas.ContainsKey (id)) { fadeAreas.Add (id,new FadeArea (open)); } FadeArea fadeArea = fadeAreas[id]; stack.Push (fadeArea); fadeArea.open = open; //Make sure the area fills the full width areaStyle.stretchWidth = true; Rect lastRect = fadeArea.lastRect; if (!fancyEffects) { fadeArea.value = open ? 1F : 0F; lastRect.height -= minHeight; lastRect.height = open ? lastRect.height : 0; lastRect.height += minHeight; } else { //GUILayout.Label (lastRect.ToString ()+"\n"+fadeArea.tmp.ToString (),EditorStyles.miniLabel); lastRect.height = lastRect.height < minHeight ? minHeight : lastRect.height; lastRect.height -= minHeight; float faded = Hermite (0F,1F,fadeArea.value); lastRect.height *= faded; lastRect.height += minHeight; lastRect.height = Mathf.Round (lastRect.height); //lastRect.height *= 2; //if (Event.current.type == EventType.Repaint) { // isLayout = false; //} } Rect gotLastRect = GUILayoutUtility.GetRect (new GUIContent (),areaStyle,GUILayout.Height (lastRect.height)); //The clipping area, also drawing background GUILayout.BeginArea (lastRect,areaStyle); Rect newRect = EditorGUILayout.BeginVertical (); if (Event.current.type == EventType.Repaint || Event.current.type == EventType.ScrollWheel) { newRect.x = gotLastRect.x; newRect.y = gotLastRect.y; newRect.width = gotLastRect.width;//stretchWidthRect.width; newRect.height += areaStyle.padding.top+ areaStyle.padding.bottom; fadeArea.currentRect = newRect; if (fadeArea.lastRect != newRect) { //@Fix - duplicate //fadeArea.lastUpdate = Time.realtimeSinceStartup; editor.Repaint (); } fadeArea.Switch (); } if (Event.current.type == EventType.Repaint) { float value = fadeArea.value; float targetValue = open ? 1F : 0F; float newRectHeight = fadeArea.lastRect.height; float deltaHeight = 400F / newRectHeight; float deltaTime = Mathf.Clamp (Time.realtimeSinceStartup-fadeAreas[id].lastUpdate,0.00001F,0.05F); deltaTime *= Mathf.Lerp (deltaHeight*deltaHeight*0.01F, 0.8F, 0.9F); fadeAreas[id].lastUpdate = Time.realtimeSinceStartup; //Useless, but fun feature if (Event.current.shift) { deltaTime *= 0.05F; } if (Mathf.Abs(targetValue-value) > 0.001F) { float time = Mathf.Clamp01 (deltaTime*speed); value += time*Mathf.Sign (targetValue-value); editor.Repaint (); } else { value = Mathf.Round (value); } fadeArea.value = Mathf.Clamp01 (value); //if (oldValue != value) { // editor.Repaint (); //} } if (fade) { Color c = GUI.color; fadeArea.preFadeColor = c; c.a *= fadeArea.value; GUI.color = c; } fadeArea.open = open; //GUILayout.Label ("Alpha : "+fadeArea.value); //GUILayout.Label ("Alpha : "+fadeArea.value);GUILayout.Label ("Alpha : "+fadeArea.value);GUILayout.Label ("Alpha : "+fadeArea.value);GUILayout.Label ("Alpha : "+fadeArea.value); /*GUILayout.Label ("Testing"); GUILayout.Label ("Testing"); GUILayout.Label ("Testing"); GUILayout.Label ("Testing");*/ return fadeArea; } public void EndFadeArea () { if (stack.Count <= 0) { Debug.LogError ("You are popping more Fade Areas than you are pushing, make sure they are balanced"); return; } FadeArea fadeArea = stack.Pop (); //Debug.Log (r); //fadeArea.tmp = r; //r.width = 10; //r.height = 10; //GUI.Box (r,""); //GUILayout.Label ("HEllo : "); EditorGUILayout.EndVertical (); GUILayout.EndArea (); if (fade) { GUI.color = fadeArea.preFadeColor; } //GUILayout.Label ("Outside"); /*currentDepth--; Rect r = GUILayoutUtility.GetRect (new GUIContent (),stretchStyle,GUILayout.Height (0)); if (Event.current.type == EventType.Repaint || Event.current.type == EventType.ScrollWheel) { Rect currentRect = currentRects[id]; Rect newRect = new Rect (currentRect.x,currentRect.y,currentRect.width,r.y-minHeight); currentRects[id] = newRect; if (lastRects[id] != newRect) { changedDelta = true; lastUpdate = Time.realtimeSinceStartup; editor.Repaint (); } } GUILayout.EndArea ();*/ } /*public static bool BeginFadeAreaSimple (bool open, string id) { if (editor == null) { Debug.LogError ("You need to set the 'EditorGUIx.editor' variable before calling this function"); return open; } if (stretchStyleThin == null) { stretchStyleThin = new GUIStyle (); stretchStyleThin.stretchWidth = true; //stretchStyle.padding = new RectOffset (0,0,4,14); //stretchStyleThin.margin = new RectOffset (0,0,4,4); } if (Event.current.type == EventType.Layout && !isLayout) { if (currentRects == null) { currentRects = new Dictionary<string, Rect> ();//new List<Rect>(); lastRects = new Dictionary<string, Rect> ();//new List<Rect>(); values = new Dictionary<string, float> ();//new List<float>(); //open = new List<bool>(); } if (changedDelta) { deltaTime = Mathf.Min (Time.realtimeSinceStartup-lastUpdate,0.1F); } else { deltaTime = 0.01F; } changedDelta = false; isLayout = true; currentDepth = 0; currentIndex = 0; Dictionary<string, Rect> tmp = lastRects; lastRects = currentRects; currentRects = tmp; currentRects.Clear (); } if (Event.current.type == EventType.Layout) { if (!currentRects.ContainsKey (id)) { currentRects.Add (id,new Rect ()); } } if (!lastRects.ContainsKey (id)) { lastRects.Add (id,new Rect ()); } if (!values.ContainsKey (id)) { values.Add (id, open ? 1.0F : 0.0F); //open.Add (false); } Rect newRect = GUILayoutUtility.GetRect (new GUIContent (),stretchStyleThin,GUILayout.Height (0)); Rect lastRect = lastRects[id]; lastRect.height *= Hermite (0F,1F,values[id]); GUILayoutUtility.GetRect (lastRect.width,lastRect.height); GUI.depth+= 10; GUILayout.BeginArea (lastRect); if (Event.current.type == EventType.Repaint) { isLayout = false; currentRects[id] = newRect; } if (Event.current.type == EventType.Layout) { float value = values[id]; float oldValue = value; float targetValue = open ? 1F : 0; if (Mathf.Abs(targetValue-value) > 0.001F) { float time = Mathf.Clamp01 (deltaTime*speed); value += time*Mathf.Sign (targetValue-value); } values[id] = Mathf.Clamp01 (value); if (oldValue != value) { changedDelta = true; lastUpdate = Time.realtimeSinceStartup; editor.Repaint (); } } return open; }*/ /*public static void EndFadeAreaSimple (string id) { if (editor == null) { Debug.LogError ("You need to set the 'EditorGUIx.editor' variable before calling this function"); return; } Rect r = GUILayoutUtility.GetRect (new GUIContent (),stretchStyleThin,GUILayout.Height (0)); if (Event.current.type == EventType.Repaint || Event.current.type == EventType.ScrollWheel) { Rect currentRect = currentRects[id]; Rect newRect = new Rect (currentRect.x,currentRect.y,currentRect.width,r.y); currentRects[id] = newRect; if (lastRects[id] != newRect) { changedDelta = true; lastUpdate = Time.realtimeSinceStartup; editor.Repaint (); } } GUILayout.EndArea (); }*/ public static void MenuCallback (System.Object ob) { Debug.Log ("Got Callback"); } /** Begin horizontal indent for the next control. * Fake "real" indent when using EditorGUIUtility.LookLikeControls.\n * Forumula used is 13+6*EditorGUI.indentLevel */ public static void BeginIndent () { GUILayout.BeginHorizontal (); GUILayout.Space (IndentWidth()); } /** Returns width of current editor indent. * Unity seems to use 13+6*EditorGUI.indentLevel in U3 * and 15*indent - (indent > 1 ? 2 : 0) or something like that in U4 */ public static int IndentWidth () { #if UNITY_4 //Works well for indent levels 0,1,2 at least return 15*EditorGUI.indentLevel - (EditorGUI.indentLevel > 1 ? 2 : 0); #else return 13+6*EditorGUI.indentLevel; #endif } /** End indent. * Actually just a EndHorizontal call. * \see BeginIndent */ public static void EndIndent () { GUILayout.EndHorizontal (); } public static int SingleTagField (string label, int value) { //GUILayout.BeginHorizontal (); //Debug.Log (value.ToString ()); //EditorGUIUtility.LookLikeControls(); ///EditorGUILayout.PrefixLabel (label,EditorStyles.layerMaskField); //GUILayout.FlexibleSpace (); //Rect r = GUILayoutUtility.GetLastRect (); string[] tagNames = AstarPath.FindTagNames (); value = value < 0 ? 0 : value; value = value >= tagNames.Length ? tagNames.Length-1 : value; //string text = tagNames[value]; /*if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { //Debug.Log ("pre"); GenericMenu menu = new GenericMenu (); for (int i=0;i<tagNames.Length;i++) { bool on = value == i; int result = i; menu.AddItem (new GUIContent (tagNames[i]),on,delegate (System.Object ob) { value = (int)ob; }, result); //value.SetValues (result); } menu.AddItem (new GUIContent ("Edit Tags..."),false,AstarPathEditor.EditTags); menu.ShowAsContext (); Event.current.Use (); //Debug.Log ("Post"); }*/ value = EditorGUILayout.IntPopup (label,value,tagNames,new int[] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}); //EditorGUIUtility.LookLikeInspector(); //GUILayout.EndHorizontal (); return value; } public static void SetTagField (GUIContent label, ref Pathfinding.TagMask value) { GUILayout.BeginHorizontal (); //Debug.Log (value.ToString ()); EditorGUIUtility.LookLikeControls(); EditorGUILayout.PrefixLabel (label,EditorStyles.layerMaskField); //GUILayout.FlexibleSpace (); //Rect r = GUILayoutUtility.GetLastRect (); string text = ""; if (value.tagsChange == 0) text = "Nothing"; else if (value.tagsChange == ~0) text = "Everything"; else { text = System.Convert.ToString (value.tagsChange,2); } string[] tagNames = AstarPath.FindTagNames (); if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { //Debug.Log ("pre"); GenericMenu menu = new GenericMenu (); menu.AddItem (new GUIContent ("Everything"),value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask (~0,value.tagsSet)); menu.AddItem (new GUIContent ("Nothing"),value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask (0,value.tagsSet)); for (int i=0;i<tagNames.Length;i++) { bool on = (value.tagsChange >> i & 0x1) != 0; Pathfinding.TagMask result = new Pathfinding.TagMask (on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1<<i,value.tagsSet); menu.AddItem (new GUIContent (tagNames[i]),on,value.SetValues, result); //value.SetValues (result); } menu.AddItem (new GUIContent ("Edit Tags..."),false,AstarPathEditor.EditTags); menu.ShowAsContext (); Event.current.Use (); //Debug.Log ("Post"); } #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector(); #endif GUILayout.EndHorizontal (); } public static void TagsMaskField (GUIContent changeLabel, GUIContent setLabel,ref Pathfinding.TagMask value) { GUILayout.BeginHorizontal (); //Debug.Log (value.ToString ()); EditorGUIUtility.LookLikeControls(); EditorGUILayout.PrefixLabel (changeLabel,EditorStyles.layerMaskField); //GUILayout.FlexibleSpace (); //Rect r = GUILayoutUtility.GetLastRect (); string text = ""; if (value.tagsChange == 0) text = "Nothing"; else if (value.tagsChange == ~0) text = "Everything"; else { text = System.Convert.ToString (value.tagsChange,2); } if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { //Debug.Log ("pre"); GenericMenu menu = new GenericMenu (); menu.AddItem (new GUIContent ("Everything"),value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask (~0,value.tagsSet)); menu.AddItem (new GUIContent ("Nothing"),value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask (0,value.tagsSet)); for (int i=0;i<32;i++) { bool on = (value.tagsChange >> i & 0x1) != 0; Pathfinding.TagMask result = new Pathfinding.TagMask (on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1<<i,value.tagsSet); menu.AddItem (new GUIContent (""+i),on,value.SetValues, result); //value.SetValues (result); } menu.ShowAsContext (); Event.current.Use (); //Debug.Log ("Post"); } #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector(); #endif GUILayout.EndHorizontal (); GUILayout.BeginHorizontal (); //Debug.Log (value.ToString ()); EditorGUIUtility.LookLikeControls(); EditorGUILayout.PrefixLabel (setLabel,EditorStyles.layerMaskField); //GUILayout.FlexibleSpace (); //r = GUILayoutUtility.GetLastRect (); text = ""; if (value.tagsSet == 0) text = "Nothing"; else if (value.tagsSet == ~0) text = "Everything"; else { text = System.Convert.ToString (value.tagsSet,2); } if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { //Debug.Log ("pre"); GenericMenu menu = new GenericMenu (); if (value.tagsChange != 0) menu.AddItem (new GUIContent ("Everything"),value.tagsSet == ~0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,~0)); else menu.AddDisabledItem (new GUIContent ("Everything")); menu.AddItem (new GUIContent ("Nothing"),value.tagsSet == 0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,0)); for (int i=0;i<32;i++) { bool enabled = (value.tagsChange >> i & 0x1) != 0; bool on = (value.tagsSet >> i & 0x1) != 0; Pathfinding.TagMask result = new Pathfinding.TagMask (value.tagsChange, on ? value.tagsSet & ~(1 << i) : value.tagsSet | 1<<i); if (enabled) menu.AddItem (new GUIContent (""+i),on,value.SetValues, result); else menu.AddDisabledItem (new GUIContent (""+i)); //value.SetValues (result); } menu.ShowAsContext (); Event.current.Use (); //Debug.Log ("Post"); } #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector(); #endif GUILayout.EndHorizontal (); //return value; } public static int UpDownArrows (GUIContent label, int value, GUIStyle labelStyle, GUIStyle upArrow, GUIStyle downArrow) { GUILayout.BeginHorizontal (); GUILayout.Space (EditorGUI.indentLevel*10); GUILayout.Label (label,labelStyle,GUILayout.Width (170)); if (downArrow == null || upArrow == null) { upArrow = GUI.skin.FindStyle ("Button");//EditorStyles.miniButton;// downArrow = upArrow;//GUI.skin.FindStyle ("Button"); } //GUILayout.BeginHorizontal (); //GUILayout.FlexibleSpace (); if (GUILayout.Button ("",upArrow,GUILayout.Width (16),GUILayout.Height (12))) { value++; } if (GUILayout.Button ("",downArrow,GUILayout.Width (16),GUILayout.Height (12))) { value--; } //GUILayout.EndHorizontal (); GUILayout.Space (100); GUILayout.EndHorizontal (); return value; } public static bool UnityTagMaskList (GUIContent label, bool foldout, List<string> tagMask) { if (tagMask == null) throw new System.ArgumentNullException ("tagMask"); if (EditorGUILayout.Foldout (foldout, label)) { EditorGUI.indentLevel++; GUILayout.BeginVertical(); for (int i=0;i<tagMask.Count;i++) { tagMask[i] = EditorGUILayout.TagField (tagMask[i]); } GUILayout.BeginHorizontal(); if (GUILayout.Button ("Add Tag")) tagMask.Add ("Untagged"); EditorGUI.BeginDisabledGroup (tagMask.Count == 0); if (GUILayout.Button ("Remove Last")) tagMask.RemoveAt (tagMask.Count-1); EditorGUI.EndDisabledGroup(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); EditorGUI.indentLevel--; return true; } return false; } public static LayerMask LayerMaskField (string label, LayerMask selected) { return LayerMaskField (label,selected,true); } public static List<string> layers; public static List<int> layerNumbers; public static string[] layerNames; public static long lastUpdateTick; /** Displays a LayerMask field. * \param label Label to display * \param showSpecial Use the Nothing and Everything selections * \param selected Current LayerMask * \note Unity 3.5 and up will use the EditorGUILayout.MaskField instead of a custom written one. */ public static LayerMask LayerMaskField (string label, LayerMask selected, bool showSpecial) { #if !UNITY_3_4 //Unity 3.5 and up if (layers == null || (System.DateTime.UtcNow.Ticks - lastUpdateTick > 10000000L && Event.current.type == EventType.Layout)) { lastUpdateTick = System.DateTime.UtcNow.Ticks; if (layers == null) { layers = new List<string>(); layerNumbers = new List<int>(); layerNames = new string[4]; } else { layers.Clear (); layerNumbers.Clear (); } int emptyLayers = 0; for (int i=0;i<32;i++) { string layerName = LayerMask.LayerToName (i); if (layerName != "") { for (;emptyLayers>0;emptyLayers--) layers.Add ("Layer "+(i-emptyLayers)); layerNumbers.Add (i); layers.Add (layerName); } else { emptyLayers++; } } if (layerNames.Length != layers.Count) { layerNames = new string[layers.Count]; } for (int i=0;i<layerNames.Length;i++) layerNames[i] = layers[i]; } selected.value = EditorGUILayout.MaskField (label,selected.value,layerNames); return selected; #else if (layers == null) { layers = new List<string>(); layerNumbers = new List<int>(); } else { layers.Clear (); layerNumbers.Clear (); } string selectedLayers = ""; for (int i=0;i<32;i++) { string layerName = LayerMask.LayerToName (i); if (layerName != "") { if (selected == (selected | (1 << i))) { if (selectedLayers == "") { selectedLayers = layerName; } else { selectedLayers = "Mixed"; } } } } if (Event.current.type != EventType.MouseDown && Event.current.type != EventType.ExecuteCommand) { if (selected.value == 0) { layers.Add ("Nothing"); } else if (selected.value == -1) { layers.Add ("Everything"); } else { layers.Add (selectedLayers); } layerNumbers.Add (-1); } if (showSpecial) { layers.Add ((selected.value == 0 ? "[X] " : " ") + "Nothing"); layerNumbers.Add (-2); layers.Add ((selected.value == -1 ? "[X] " : " ") + "Everything"); layerNumbers.Add (-3); } for (int i=0;i<32;i++) { string layerName = LayerMask.LayerToName (i); if (layerName != "") { if (selected == (selected | (1 << i))) { layers.Add ("[X] "+layerName); } else { layers.Add (" "+layerName); } layerNumbers.Add (i); } } bool preChange = GUI.changed; GUI.changed = false; int newSelected = 0; if (Event.current.type == EventType.MouseDown) { newSelected = -1; } newSelected = EditorGUILayout.Popup (label,newSelected,layers.ToArray(),EditorStyles.layerMaskField); if (GUI.changed && newSelected >= 0) { int preSelected = selected; if (showSpecial && newSelected == 0) { selected = 0; } else if (showSpecial && newSelected == 1) { selected = -1; } else { if (selected == (selected | (1 << layerNumbers[newSelected]))) { selected &= ~(1 << layerNumbers[newSelected]); //Debug.Log ("Set Layer "+LayerMask.LayerToName (LayerNumbers[newSelected]) + " To False "+selected.value); } else { //Debug.Log ("Set Layer "+LayerMask.LayerToName (LayerNumbers[newSelected]) + " To True "+selected.value); selected = selected | (1 << layerNumbers[newSelected]); } } if (selected == preSelected) { GUI.changed = false; } else { //Debug.Log ("Difference made"); } } GUI.changed = preChange || GUI.changed; return selected; #endif } public static float Hermite(float start, float end, float value) { return Mathf.Lerp(start, end, value * value * (3.0f - 2.0f * value)); } public static float Sinerp(float start, float end, float value) { return Mathf.Lerp(start, end, Mathf.Sin(value * Mathf.PI * 0.5f)); } public static float Coserp(float start, float end, float value) { return Mathf.Lerp(start, end, 1.0f - Mathf.Cos(value * Mathf.PI * 0.5f)); } public static float Berp(float start, float end, float value) { value = Mathf.Clamp01(value); value = (Mathf.Sin(value * Mathf.PI * (0.2f + 2.5f * value * value * value)) * Mathf.Pow(1f - value, 2.2f) + value) * (1f + (1.2f * (1f - value))); return start + (end - start) * value; } } }
using System; using System.IO; using System.Collections.Generic; using System.Xml.XPath; using System.Xml; using System.Web.UI; using Hydra.Framework.XmlSerialization.Common.XPath; namespace Hydra.Framework.XmlSerialization.Exslt { // //********************************************************************** /// <summary> /// This class implements the EXSLT functions in the http://exslt.org/sets namespace. /// </summary> //********************************************************************** // public class ExsltSets { // //********************************************************************** /// <summary> /// Implements the following function /// node-set difference(node-set, node-set) /// </summary> /// <param name="nodeset1">An input nodeset</param> /// <param name="nodeset2">Another input nodeset</param> /// <returns>The those nodes that are in the node set /// passed as the first argument that are not in the node set /// passed as the second argument.</returns> //********************************************************************** // public XPathNodeIterator difference(XPathNodeIterator nodeset1, XPathNodeIterator nodeset2) { if (nodeset2.Count > 166) return difference2(nodeset1, nodeset2); //else XPathNavigatorIterator nodelist1 = new XPathNavigatorIterator(nodeset1, true); XPathNavigatorIterator nodelist2 = new XPathNavigatorIterator(nodeset2); for (int i = 0; i < nodelist1.Count; i++) { XPathNavigator nav = nodelist1[i]; if (nodelist2.Contains(nav)) { nodelist1.RemoveAt(i); i--; } } nodelist1.Reset(); return nodelist1; } // //********************************************************************** /// <summary> /// Implements an optimized algorithm for the following function /// node-set difference(node-set, node-set) /// Uses document identification and binary search, /// based on the fact that a node-set is always in document order. /// </summary> /// <param name="nodeset1">An input nodeset</param> /// <param name="nodeset2">Another input nodeset</param> /// <returns>The those nodes that are in the node set /// passed as the first argument that are not in the node set /// passed as the second argument.</returns> //********************************************************************** // private XPathNodeIterator difference2(XPathNodeIterator nodeset1, XPathNodeIterator nodeset2) { List<Pair> arDocs = new List<Pair>(); List<XPathNavigator> arNodes2 = new List<XPathNavigator>(nodeset2.Count); while (nodeset2.MoveNext()) { arNodes2.Add(nodeset2.Current.Clone()); } auxEXSLT.findDocs(arNodes2, arDocs); XPathNavigatorIterator enlResult = new XPathNavigatorIterator(); while (nodeset1.MoveNext()) { XPathNavigator currNode = nodeset1.Current; if (!auxEXSLT.findNode(arNodes2, arDocs, currNode)) enlResult.Add(currNode.Clone()); } enlResult.Reset(); return enlResult; } // //********************************************************************** /// <summary> /// Implements the following function /// node-set distinct(node-set) /// </summary> /// <param name="nodeset">The input nodeset</param> /// <returns>Returns the nodes in the nodeset whose string value is /// distinct</returns> //********************************************************************** // public XPathNodeIterator distinct(XPathNodeIterator nodeset) { if (nodeset.Count > 15) return distinct2(nodeset); //else XPathNavigatorIterator nodelist = new XPathNavigatorIterator(); while (nodeset.MoveNext()) { if (!nodelist.ContainsValue(nodeset.Current.Value)) { nodelist.Add(nodeset.Current.Clone()); } } nodelist.Reset(); return nodelist; } // //********************************************************************** /// <summary> /// Implements the following function /// node-set distinct2(node-set) /// /// This implements an optimized algorithm /// using a Hashtable /// /// </summary> /// <param name="nodeset">The input nodeset</param> /// <returns>Returns the nodes in the nodeset whose string value is /// distinct</returns> //********************************************************************** // private XPathNodeIterator distinct2(XPathNodeIterator nodeset) { XPathNavigatorIterator nodelist = new XPathNavigatorIterator(); Dictionary<string, string> ht = new Dictionary<string, string>(nodeset.Count / 3); while (nodeset.MoveNext()) { string strVal = nodeset.Current.Value; if (!ht.ContainsKey(strVal)) { ht.Add(strVal, ""); nodelist.Add(nodeset.Current.Clone()); } } nodelist.Reset(); return nodelist; } // //********************************************************************** /// <summary> /// Implements /// boolean hassamenode(node-set, node-set) /// </summary> /// <param name="nodeset1"></param> /// <param name="nodeset2"></param> /// <returns>true if both nodeset contain at least one of the same node</returns> //********************************************************************** // public bool hasSameNode(XPathNodeIterator nodeset1, XPathNodeIterator nodeset2) { if (nodeset1.Count >= 250 || nodeset2.Count >= 250) return hasSameNode2(nodeset1, nodeset2); //else XPathNavigatorIterator nodelist1 = new XPathNavigatorIterator(nodeset1, true); XPathNavigatorIterator nodelist2 = new XPathNavigatorIterator(nodeset2, true); foreach (XPathNavigator nav in nodelist1) { if (nodelist2.Contains(nav)) { return true; } } return false; } // //********************************************************************** /// <summary> /// Implements /// boolean hassamenode2(node-set, node-set) /// /// Optimized by using a document identification and /// binary search algorithm /// </summary> /// <param name="nodeset1">The first nodeset</param> /// <param name="nodeset2">The second nodeset</param> /// <returns>true if both nodeset contain /// at least one of the same node</returns> //********************************************************************** // private bool hasSameNode2(XPathNodeIterator nodeset1, XPathNodeIterator nodeset2) { XPathNodeIterator it1 = (nodeset1.Count > nodeset2.Count) ? nodeset1 : nodeset2; XPathNodeIterator it2 = (nodeset1.Count > nodeset2.Count) ? nodeset2 : nodeset1; List<Pair> arDocs = new List<Pair>(); List<XPathNavigator> arNodes1 = new List<XPathNavigator>(it1.Count); while (it1.MoveNext()) { arNodes1.Add(it1.Current.Clone()); } auxEXSLT.findDocs(arNodes1, arDocs); XPathNavigatorIterator enlResult = new XPathNavigatorIterator(); while (it2.MoveNext()) { XPathNavigator currNode = it2.Current; if (auxEXSLT.findNode(arNodes1, arDocs, currNode)) return true; } return false; } // //********************************************************************** /// <summary> /// This wrapper method will be renamed during custom build /// to provide conformant EXSLT function name. /// </summary> //********************************************************************** // public bool hasSameNode_RENAME_ME(XPathNodeIterator nodeset1, XPathNodeIterator nodeset2) { return hasSameNode(nodeset1, nodeset2); } // //********************************************************************** /// <summary> /// Implements the following function /// node-set intersection(node-set, node-set) /// </summary> /// <param name="nodeset1">The first node-set</param> /// <param name="nodeset2">The second node-set</param> /// <returns>The node-set, which is the intersection /// of nodeset1 and nodeset2 /// </returns> //********************************************************************** // public XPathNodeIterator intersection(XPathNodeIterator nodeset1, XPathNodeIterator nodeset2) { if (nodeset1.Count >= 500 || nodeset2.Count >= 500) return intersection3(nodeset1, nodeset2); //else XPathNavigatorIterator nodelist1 = new XPathNavigatorIterator(nodeset1, true); XPathNavigatorIterator nodelist2 = new XPathNavigatorIterator(nodeset2); for (int i = 0; i < nodelist1.Count; i++) { XPathNavigator nav = nodelist1[i]; if (!nodelist2.Contains(nav)) { nodelist1.RemoveAt(i); i--; } } nodelist1.Reset(); return nodelist1; } // //********************************************************************** /// <summary> /// Implements the following function /// node-set intersection3(node-set, node-set) /// /// This is an optimisation of the initial implementation /// of intersection(). It uses a document identification /// and a binary search algorithm, based on the fact /// that a node-set is always in document order. /// </summary> /// <param name="nodeset1">The first node-set</param> /// <param name="nodeset2">The second node-set</param> /// <returns>The node-set, which is the intersection /// of nodeset1 and nodeset2 /// </returns> //********************************************************************** // private XPathNodeIterator intersection3(XPathNodeIterator nodeset1, XPathNodeIterator nodeset2) { XPathNodeIterator it1 = (nodeset1.Count > nodeset2.Count) ? nodeset1 : nodeset2; XPathNodeIterator it2 = (nodeset1.Count > nodeset2.Count) ? nodeset2 : nodeset1; List<Pair> arDocs = new List<Pair>(); List<XPathNavigator> arNodes1 = new List<XPathNavigator>(it1.Count); while (it1.MoveNext()) { arNodes1.Add(it1.Current.Clone()); } auxEXSLT.findDocs(arNodes1, arDocs); XPathNavigatorIterator enlResult = new XPathNavigatorIterator(); while (it2.MoveNext()) { XPathNavigator currNode = it2.Current; if (auxEXSLT.findNode(arNodes1, arDocs, currNode)) enlResult.Add(currNode.Clone()); } enlResult.Reset(); return enlResult; } // //********************************************************************** /// <summary> /// Implements the following function /// node-set leading(node-set, node-set) /// </summary> /// <param name="nodeset1"></param> /// <param name="nodeset2"></param> /// <returns>returns the nodes in the node set passed as the /// first argument that precede, in document order, the first node /// in the node set passed as the second argument</returns> //********************************************************************** // public XPathNodeIterator leading(XPathNodeIterator nodeset1, XPathNodeIterator nodeset2) { XPathNavigator leader = null; if (nodeset2.MoveNext()) { leader = nodeset2.Current; } else { return nodeset1; } XPathNavigatorIterator nodelist1 = new XPathNavigatorIterator(); while (nodeset1.MoveNext()) { if (nodeset1.Current.ComparePosition(leader) == XmlNodeOrder.Before) { nodelist1.Add(nodeset1.Current.Clone()); } } nodelist1.Reset(); return nodelist1; } // //********************************************************************** /// <summary> /// Implements the following function /// node-set trailing(node-set, node-set) /// </summary> /// <param name="nodeset1"></param> /// <param name="nodeset2"></param> /// <returns>returns the nodes in the node set passed as the /// first argument that follow, in document order, the first node /// in the node set passed as the second argument</returns> //********************************************************************** // public XPathNodeIterator trailing(XPathNodeIterator nodeset1, XPathNodeIterator nodeset2) { XPathNavigator leader = null; if (nodeset2.MoveNext()) { leader = nodeset2.Current; } else { return nodeset1; } XPathNavigatorIterator nodelist1 = new XPathNavigatorIterator(); while (nodeset1.MoveNext()) { if (nodeset1.Current.ComparePosition(leader) == XmlNodeOrder.After) { nodelist1.Add(nodeset1.Current.Clone()); } } nodelist1.Reset(); return nodelist1; } } // //********************************************************************** /// <summary> /// This class implements some auxiliary methods /// which should not be exposed in any namespace /// </summary> //********************************************************************** // internal class auxEXSLT { public static bool findNode(List<XPathNavigator> arNodes1, List<Pair> arDocs, XPathNavigator currNode) { // // 1. First, find the document of this node, return false if not found // 2. If the document for the node is found and the node is not an immediate // hit, then look for it using binsearch. // int start = -1, end = -1, mid; foreach (Pair p in arDocs) { XmlNodeOrder xOrder = ((XPathNavigator)arNodes1[(int)p.First]).ComparePosition(currNode); if (xOrder == XmlNodeOrder.Same) return true; //else if (xOrder != XmlNodeOrder.Unknown) { start = (int)p.First; end = (int)p.Second; break; } } if (start == -1) return false; //else perform a binary search in the range [start, end] while (end >= start) { mid = (start + end) / 2; XmlNodeOrder xOrder = ((XPathNavigator)arNodes1[mid]).ComparePosition(currNode); if (xOrder == XmlNodeOrder.Before) { start = mid + 1; } else if (xOrder == XmlNodeOrder.After) { end = mid - 1; } else return true; } return false; } public static void findDocs(List<XPathNavigator> arNodes, List<Pair> arDocs) { int count = arNodes.Count; int startDoc = 0; int endDoc; int start; int end; int mid; while (startDoc < count) { start = startDoc; endDoc = count - 1; end = endDoc; mid = (start + end) / 2; while (end > start) { if ( ((XPathNavigator)arNodes[start]).ComparePosition((XPathNavigator)arNodes[mid]) == XmlNodeOrder.Unknown ) { end = mid - 1; if (((XPathNavigator)arNodes[start]).ComparePosition((XPathNavigator)arNodes[end]) != XmlNodeOrder.Unknown) { endDoc = end; break; } } else { if (((XPathNavigator)arNodes[mid]).ComparePosition((XPathNavigator)arNodes[mid + 1]) == XmlNodeOrder.Unknown) { endDoc = mid; break; } start = mid + 1; } mid = (start + end) / 2; } //here we know startDoc and endDoc Pair DocRange = new Pair(startDoc, endDoc); arDocs.Add(DocRange); startDoc = endDoc + 1; } } } }
namespace dotless.Core.Parser.Tree { using System; using System.Collections.Generic; using System.Linq; using Exceptions; using Infrastructure; using Infrastructure.Nodes; using Utils; using Plugins; public class MixinCall : Node { public List<NamedArgument> Arguments { get; set; } public Selector Selector { get; set; } public bool Important { get; set; } public MixinCall(NodeList<Element> elements, List<NamedArgument> arguments, bool important) { Important = important; Selector = new Selector(elements); Arguments = arguments; } protected override Node CloneCore() { return new MixinCall( new NodeList<Element>(Selector.Elements.Select(e => e.Clone())), Arguments, Important); } public override Node Evaluate(Env env) { var closures = env.FindRulesets(Selector); if (closures == null) throw new ParsingException(Selector.ToCSS(env).Trim() + " is undefined", Location); env.Rule = this; var rules = new NodeList(); if (PreComments) rules.AddRange(PreComments); var rulesetList = closures.ToList(); // To address bug https://github.com/dotless/dotless/issues/136, where a mixin and ruleset selector may have the same name, we // need to favour matching a MixinDefinition with the required Selector and only fall back to considering other Ruleset types // if no match is found. // However, in order to support having a regular ruleset with the same name as a parameterized // mixin (see https://github.com/dotless/dotless/issues/387), we need to take argument counts into account, so we make the // decision after evaluating for argument match. var mixins = rulesetList.Where(c => c.Ruleset is MixinDefinition).ToList(); var defaults = new List<Closure>(); bool foundMatches = false, foundExactMatches = false, foundDefaultMatches = false; foreach (var closure in mixins) { var ruleset = (MixinDefinition)closure.Ruleset; var matchType = ruleset.MatchArguments(Arguments, env); if (matchType == MixinMatch.ArgumentMismatch) { continue; } if (matchType == MixinMatch.Default) { defaults.Add(closure); foundDefaultMatches = true; continue; } foundMatches = true; if (matchType == MixinMatch.GuardFail) { continue; } foundExactMatches = true; try { var closureEnvironment = env.CreateChildEnvWithClosure(closure); rules.AddRange(ruleset.Evaluate(Arguments, closureEnvironment).Rules); } catch (ParsingException e) { throw new ParsingException(e.Message, e.Location, Location); } } if (!foundExactMatches && foundDefaultMatches) { foreach (var closure in defaults) { try { var closureEnvironment = env.CreateChildEnvWithClosure(closure); var ruleset = (MixinDefinition) closure.Ruleset; rules.AddRange(ruleset.Evaluate(Arguments, closureEnvironment).Rules); } catch (ParsingException e) { throw new ParsingException(e.Message, e.Location, Location); } } foundMatches = true; } if (!foundMatches) { var regularRulesets = rulesetList.Except(mixins); foreach (var closure in regularRulesets) { if (closure.Ruleset.Rules != null) { var nodes = (NodeList)closure.Ruleset.Rules.Clone(); NodeHelper.ExpandNodes<MixinCall>(env, nodes); rules.AddRange(nodes); } foundMatches = true; } } if (PostComments) rules.AddRange(PostComments); env.Rule = null; if (!foundMatches) { var message = String.Format("No matching definition was found for `{0}({1})`", Selector.ToCSS(env).Trim(), Arguments.Select(a => a.Value.ToCSS(env)).JoinStrings(env.Compress ? "," : ", ")); throw new ParsingException(message, Location); } rules.Accept(new ReferenceVisitor(IsReference)); if (Important) { return MakeRulesImportant(rules); } return rules; } public override void Accept(IVisitor visitor) { Selector = VisitAndReplace(Selector, visitor); foreach (var a in Arguments) { a.Value = VisitAndReplace(a.Value, visitor); } } private Ruleset MakeRulesetImportant(Ruleset ruleset) { return new Ruleset(ruleset.Selectors, MakeRulesImportant(ruleset.Rules)).ReducedFrom<Ruleset>(ruleset); } private NodeList MakeRulesImportant(NodeList rules) { var importantRules = new NodeList(); foreach (var node in rules) { if (node is MixinCall) { var original = (MixinCall)node; importantRules.Add(new MixinCall(original.Selector.Elements, new List<NamedArgument>(original.Arguments), true).ReducedFrom<MixinCall>(node)); } else if (node is Rule) { importantRules.Add(MakeRuleImportant((Rule) node)); } else if (node is Ruleset) { importantRules.Add(MakeRulesetImportant((Ruleset) node)); } else { importantRules.Add(node); } } return importantRules; } private Rule MakeRuleImportant(Rule rule) { var valueNode = rule.Value; var value = valueNode as Value; value = value != null ? new Value(value.Values, "!important").ReducedFrom<Value>(value) : new Value(new NodeList {valueNode}, "!important"); var importantRule = new Rule(rule.Name, value).ReducedFrom<Rule>(rule); return importantRule; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.IO { public static class __TextWriter { public static IObservable<System.Reactive.Unit> Close(this IObservable<System.IO.TextWriter> TextWriterValue) { return Observable.Do(TextWriterValue, (TextWriterValueLambda) => TextWriterValueLambda.Close()).ToUnit(); } public static IObservable<System.Reactive.Unit> Dispose(this IObservable<System.IO.TextWriter> TextWriterValue) { return Observable.Do(TextWriterValue, (TextWriterValueLambda) => TextWriterValueLambda.Dispose()).ToUnit(); } public static IObservable<System.Reactive.Unit> Flush(this IObservable<System.IO.TextWriter> TextWriterValue) { return Observable.Do(TextWriterValue, (TextWriterValueLambda) => TextWriterValueLambda.Flush()).ToUnit(); } public static IObservable<System.IO.TextWriter> Synchronized(IObservable<System.IO.TextWriter> writer) { return Observable.Select(writer, (writerLambda) => System.IO.TextWriter.Synchronized(writerLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char[]> buffer) { return ObservableExt.ZipExecute(TextWriterValue, buffer, (TextWriterValueLambda, bufferLambda) => TextWriterValueLambda.Write(bufferLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char[]> buffer, IObservable<System.Int32> index, IObservable<System.Int32> count) { return ObservableExt.ZipExecute(TextWriterValue, buffer, index, count, (TextWriterValueLambda, bufferLambda, indexLambda, countLambda) => TextWriterValueLambda.Write(bufferLambda, indexLambda, countLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Int32> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.UInt32> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Int64> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.UInt64> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Single> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Double> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Decimal> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Object> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.Write(valueLambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> format, IObservable<System.Object> arg0) { return ObservableExt.ZipExecute(TextWriterValue, format, arg0, (TextWriterValueLambda, formatLambda, arg0Lambda) => TextWriterValueLambda.Write(formatLambda, arg0Lambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> format, IObservable<System.Object> arg0, IObservable<System.Object> arg1) { return ObservableExt.ZipExecute(TextWriterValue, format, arg0, arg1, (TextWriterValueLambda, formatLambda, arg0Lambda, arg1Lambda) => TextWriterValueLambda.Write(formatLambda, arg0Lambda, arg1Lambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> format, IObservable<System.Object> arg0, IObservable<System.Object> arg1, IObservable<System.Object> arg2) { return ObservableExt.ZipExecute(TextWriterValue, format, arg0, arg1, arg2, (TextWriterValueLambda, formatLambda, arg0Lambda, arg1Lambda, arg2Lambda) => TextWriterValueLambda.Write(formatLambda, arg0Lambda, arg1Lambda, arg2Lambda)); } public static IObservable<System.Reactive.Unit> Write(this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> format, IObservable<System.Object[]> arg) { return ObservableExt.ZipExecute(TextWriterValue, format, arg, (TextWriterValueLambda, formatLambda, argLambda) => TextWriterValueLambda.Write(formatLambda, argLambda)); } public static IObservable<System.Reactive.Unit> WriteLine(this IObservable<System.IO.TextWriter> TextWriterValue) { return Observable.Do(TextWriterValue, (TextWriterValueLambda) => TextWriterValueLambda.WriteLine()).ToUnit(); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char[]> buffer) { return ObservableExt.ZipExecute(TextWriterValue, buffer, (TextWriterValueLambda, bufferLambda) => TextWriterValueLambda.WriteLine(bufferLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char[]> buffer, IObservable<System.Int32> index, IObservable<System.Int32> count) { return ObservableExt.ZipExecute(TextWriterValue, buffer, index, count, (TextWriterValueLambda, bufferLambda, indexLambda, countLambda) => TextWriterValueLambda.WriteLine(bufferLambda, indexLambda, countLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Int32> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.UInt32> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Int64> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.UInt64> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Single> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Double> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Decimal> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Object> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLine(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> format, IObservable<System.Object> arg0) { return ObservableExt.ZipExecute(TextWriterValue, format, arg0, (TextWriterValueLambda, formatLambda, arg0Lambda) => TextWriterValueLambda.WriteLine(formatLambda, arg0Lambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> format, IObservable<System.Object> arg0, IObservable<System.Object> arg1) { return ObservableExt.ZipExecute(TextWriterValue, format, arg0, arg1, (TextWriterValueLambda, formatLambda, arg0Lambda, arg1Lambda) => TextWriterValueLambda.WriteLine(formatLambda, arg0Lambda, arg1Lambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> format, IObservable<System.Object> arg0, IObservable<System.Object> arg1, IObservable<System.Object> arg2) { return ObservableExt.ZipExecute(TextWriterValue, format, arg0, arg1, arg2, (TextWriterValueLambda, formatLambda, arg0Lambda, arg1Lambda, arg2Lambda) => TextWriterValueLambda.WriteLine(formatLambda, arg0Lambda, arg1Lambda, arg2Lambda)); } public static IObservable<System.Reactive.Unit> WriteLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> format, IObservable<System.Object[]> arg) { return ObservableExt.ZipExecute(TextWriterValue, format, arg, (TextWriterValueLambda, formatLambda, argLambda) => TextWriterValueLambda.WriteLine(formatLambda, argLambda)); } public static IObservable<System.Reactive.Unit> WriteAsync( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char> value) { return Observable.Zip(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteAsync(valueLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> WriteAsync( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> value) { return Observable.Zip(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteAsync(valueLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> WriteAsync( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char[]> buffer) { return Observable.Zip(TextWriterValue, buffer, (TextWriterValueLambda, bufferLambda) => TextWriterValueLambda.WriteAsync(bufferLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> WriteAsync( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char[]> buffer, IObservable<System.Int32> index, IObservable<System.Int32> count) { return Observable.Zip(TextWriterValue, buffer, index, count, (TextWriterValueLambda, bufferLambda, indexLambda, countLambda) => TextWriterValueLambda.WriteAsync(bufferLambda, indexLambda, countLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> WriteLineAsync( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char> value) { return Observable.Zip(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLineAsync(valueLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> WriteLineAsync( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> value) { return Observable.Zip(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.WriteLineAsync(valueLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> WriteLineAsync( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char[]> buffer) { return Observable.Zip(TextWriterValue, buffer, (TextWriterValueLambda, bufferLambda) => TextWriterValueLambda.WriteLineAsync(bufferLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> WriteLineAsync( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.Char[]> buffer, IObservable<System.Int32> index, IObservable<System.Int32> count) { return Observable.Zip(TextWriterValue, buffer, index, count, (TextWriterValueLambda, bufferLambda, indexLambda, countLambda) => TextWriterValueLambda.WriteLineAsync(bufferLambda, indexLambda, countLambda).ToObservable()) .Flatten(); } public static IObservable<System.Reactive.Unit> WriteLineAsync( this IObservable<System.IO.TextWriter> TextWriterValue) { return Observable.Select(TextWriterValue, (TextWriterValueLambda) => TextWriterValueLambda.WriteLineAsync().ToObservable()).Flatten().ToUnit(); } public static IObservable<System.Reactive.Unit> FlushAsync( this IObservable<System.IO.TextWriter> TextWriterValue) { return Observable.Select(TextWriterValue, (TextWriterValueLambda) => TextWriterValueLambda.FlushAsync().ToObservable()).Flatten().ToUnit(); } public static IObservable<System.IFormatProvider> get_FormatProvider( this IObservable<System.IO.TextWriter> TextWriterValue) { return Observable.Select(TextWriterValue, (TextWriterValueLambda) => TextWriterValueLambda.FormatProvider); } public static IObservable<System.Text.Encoding> get_Encoding( this IObservable<System.IO.TextWriter> TextWriterValue) { return Observable.Select(TextWriterValue, (TextWriterValueLambda) => TextWriterValueLambda.Encoding); } public static IObservable<System.String> get_NewLine(this IObservable<System.IO.TextWriter> TextWriterValue) { return Observable.Select(TextWriterValue, (TextWriterValueLambda) => TextWriterValueLambda.NewLine); } public static IObservable<System.Reactive.Unit> set_NewLine( this IObservable<System.IO.TextWriter> TextWriterValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(TextWriterValue, value, (TextWriterValueLambda, valueLambda) => TextWriterValueLambda.NewLine = valueLambda); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; namespace MFMetaDataProcessor { /// <summary> /// Encaplulates logic related for writing correct byte code and calculating stack size. /// </summary> /// <remarks> /// This class initially copy-pasted from Mono.Cecil codebase but changed a lot. /// </remarks> internal sealed class CodeWriter { /// <summary> /// Original method body information in Mono.Cecil format. /// </summary> private readonly MethodBody _body; /// <summary> /// Binary writer for writing byte code in correct endianess. /// </summary> private readonly TinyBinaryWriter _writer; /// <summary> /// String literals table (used for obtaining string literal ID). /// </summary> private readonly TinyStringTable _stringTable; /// <summary> /// Assembly tables context - contains all tables used for building target assembly. /// </summary> private readonly TinyTablesContext _context; /// <summary> /// Creates new instance of <see cref="Mono.Cecil.Cil.CodeWriter"/> object. /// </summary> /// <param name="method">Original method body in Mono.Cecil format.</param> /// <param name="writer">Binary writer for writing byte code in correct endianess.</param> /// <param name="stringTable">String references table (for obtaining string ID).</param> /// <param name="context"> /// Assembly tables context - contains all tables used for building target assembly. /// </param> public CodeWriter( MethodDefinition method, TinyBinaryWriter writer, TinyStringTable stringTable, TinyTablesContext context) { _stringTable = stringTable; _body = method.Body; _context = context; _writer = writer; } /// <summary> /// Writes method body into binary writer originally passed into constructor. /// </summary> public void WriteMethodBody() { foreach (var instruction in _body.Instructions) { WriteOpCode(instruction.OpCode); WriteOperand(instruction); } WriteExceptionsTable(); } /// <summary> /// Fixes instructions offsets according .NET Micro Framework operands sizes. /// </summary> /// <param name="methodDefinition">Target method for fixing offsets</param> /// <param name="stringTable">String table for populating strings from method.</param> public static IEnumerable<Tuple<UInt32, UInt32>> PreProcessMethod( MethodDefinition methodDefinition, TinyStringTable stringTable) { if (!methodDefinition.HasBody) { yield break; } var offset = 0; var offsetChanged = true; foreach (var instruction in methodDefinition.Body.Instructions) { if (offset != 0) { if (offsetChanged) { yield return new Tuple<UInt32, UInt32>( (UInt32)instruction.Offset, (UInt32)(instruction.Offset + offset)); offsetChanged = false; } instruction.Offset += offset; } switch (instruction.OpCode.OperandType) { case OperandType.InlineSwitch: var targets = (Instruction[]) instruction.Operand; offset -= 3; // One bye used instead of Int32 offset -= 2 * targets.Length; // each target use Int16 instead of Int32 offsetChanged = true; break; case OperandType.InlineString: stringTable.GetOrCreateStringId((String) instruction.Operand, false); offset -= 2; offsetChanged = true; break; case OperandType.InlineMethod: case OperandType.InlineField: case OperandType.InlineType: case OperandType.InlineBrTarget: // In full .NET these instructions followed by double word operand // but in .NET Micro Framework these instruction's operand are word offset -= 2; offsetChanged = true; break; } } } /// <summary> /// Calculates method stack size for passed <paramref name="methodBody"/> method. /// </summary> /// <param name="methodBody">Method body in Mono.Cecil format.</param> /// <returns>Maximal evaluated stack size for passed method body.</returns> public static Byte CalculateStackSize( MethodBody methodBody) { if (methodBody == null) { return 0; } IDictionary<Int32, Int32> offsets = new Dictionary<Int32, Int32>(); var size = 0; var maxSize = 0; foreach (var instruction in methodBody.Instructions) { Int32 correctedStackSize; if (offsets.TryGetValue(instruction.Offset, out correctedStackSize)) { size = correctedStackSize; } switch (instruction.OpCode.Code) { case Code.Throw: case Code.Endfinally: case Code.Endfilter: case Code.Leave_S: case Code.Br_S: case Code.Leave: size = 0; continue; case Code.Newobj: { var method = (MethodReference)instruction.Operand; size -= method.Parameters.Count; } break; case Code.Callvirt: case Code.Call: { var method = (MethodReference)instruction.Operand; if (method.HasThis) { --size; } size -= method.Parameters.Count; if (method.ReturnType.FullName != "System.Void") { ++size; } } break; } size = CorrectStackDepthByPushes(instruction, size); size = CorrectStackDepthByPops(instruction, size); if (instruction.OpCode.OperandType == OperandType.ShortInlineBrTarget || instruction.OpCode.OperandType == OperandType.InlineBrTarget) { Int32 stackSize; var target = (Instruction)instruction.Operand; offsets.TryGetValue(target.Offset, out stackSize); offsets[target.Offset] = Math.Max(stackSize, size); } maxSize = Math.Max(maxSize, size); } return (Byte)maxSize; } private static Int32 CorrectStackDepthByPushes( Instruction instruction, Int32 size) { switch (instruction.OpCode.StackBehaviourPush) { case StackBehaviour.Push1: case StackBehaviour.Pushi: case StackBehaviour.Pushi8: case StackBehaviour.Pushr4: case StackBehaviour.Pushr8: case StackBehaviour.Pushref: ++size; break; case StackBehaviour.Push1_push1: size += 2; break; } return size; } private static Int32 CorrectStackDepthByPops( Instruction instruction, Int32 size) { switch (instruction.OpCode.StackBehaviourPop) { case StackBehaviour.Pop1: case StackBehaviour.Popi: case StackBehaviour.Popref: --size; break; case StackBehaviour.Pop1_pop1: case StackBehaviour.Popi_pop1: case StackBehaviour.Popi_popi: case StackBehaviour.Popi_popi8: case StackBehaviour.Popi_popr4: case StackBehaviour.Popi_popr8: case StackBehaviour.Popref_pop1: case StackBehaviour.Popref_popi: size -= 2; break; case StackBehaviour.Popi_popi_popi: case StackBehaviour.Popref_popi_popi: case StackBehaviour.Popref_popi_popi8: case StackBehaviour.Popref_popi_popr4: case StackBehaviour.Popref_popi_popr8: case StackBehaviour.Popref_popi_popref: size -= 3; break; } return size; } private void WriteExceptionsTable() { if (!_body.HasExceptionHandlers) { return; } foreach (var handler in _body.ExceptionHandlers .OrderBy(item => item.HandlerStart.Offset)) { switch (handler.HandlerType) { case ExceptionHandlerType.Catch: _writer.WriteUInt16(0x0000); _writer.WriteUInt16(GetTypeReferenceId(handler.CatchType, 0x8000)); break; case ExceptionHandlerType.Fault: _writer.WriteUInt16(0x0001); _writer.WriteUInt16(0x0000); break; case ExceptionHandlerType.Finally: _writer.WriteUInt16(0x0002); _writer.WriteUInt16(0x0000); break; case ExceptionHandlerType.Filter: _writer.WriteUInt16(0x0003); _writer.WriteUInt16((UInt16)handler.FilterStart.Offset); break; } _writer.WriteUInt16((UInt16)handler.TryStart.Offset); _writer.WriteUInt16((UInt16)handler.TryEnd.Offset); _writer.WriteUInt16((UInt16)handler.HandlerStart.Offset); if (handler.HandlerEnd == null) { _writer.WriteUInt16((UInt16)_body.Instructions.Last().Offset); } else { _writer.WriteUInt16((UInt16)handler.HandlerEnd.Offset); } } _writer.WriteByte((Byte)_body.ExceptionHandlers.Count); } private void WriteOpCode ( OpCode opcode) { if (opcode.Size == 1) { _writer.WriteByte(opcode.Op2); } else { _writer.WriteByte(opcode.Op1); _writer.WriteByte(opcode.Op2); } } private void WriteOperand ( Instruction instruction) { var opcode = instruction.OpCode; var operandType = opcode.OperandType; if (operandType == OperandType.InlineNone) { return; } var operand = instruction.Operand; if (operand == null) { throw new ArgumentException(); } switch (operandType) { case OperandType.InlineSwitch: { var targets = (Instruction[]) operand; _writer.WriteByte((Byte)targets.Length); var diff = instruction.Offset + opcode.Size + 2 * targets.Length + 1; foreach (var item in targets) { _writer.WriteInt16((Int16)(GetTargetOffset(item) - diff)); } break; } case OperandType.ShortInlineBrTarget: { var target = (Instruction) operand; _writer.WriteSByte((SByte) (GetTargetOffset(target) - (instruction.Offset + opcode.Size + 1))); break; } case OperandType.InlineBrTarget: { var target = (Instruction) operand; _writer.WriteInt16((Int16) (GetTargetOffset(target) - (instruction.Offset + opcode.Size + 2))); break; } case OperandType.ShortInlineVar: _writer.WriteByte((byte)GetVariableIndex((VariableDefinition)operand)); break; case OperandType.ShortInlineArg: _writer.WriteByte((byte)GetParameterIndex((ParameterDefinition)operand)); break; case OperandType.InlineVar: _writer.WriteInt16((short)GetVariableIndex((VariableDefinition)operand)); break; case OperandType.InlineArg: _writer.WriteInt16((short)GetParameterIndex((ParameterDefinition)operand)); break; case OperandType.InlineSig: // TODO: implement this properly after finding when such code is generated //WriteMetadataToken (GetStandAloneSignature ((CallSite) operand)); break; case OperandType.ShortInlineI: if (opcode == OpCodes.Ldc_I4_S) { _writer.WriteSByte((SByte)operand); } else { _writer.WriteByte((Byte)operand); } break; case OperandType.InlineI: _writer.WriteInt32((Int32)operand); break; case OperandType.InlineI8: _writer.WriteInt64((Int64)operand); break; case OperandType.ShortInlineR: _writer.WriteSingle((Single)operand); break; case OperandType.InlineR: _writer.WriteDouble((Double)operand); break; case OperandType.InlineString: var stringReferenceId = _stringTable.GetOrCreateStringId((String) operand, false); _writer.WriteUInt16(stringReferenceId); break; case OperandType.InlineMethod: _writer.WriteUInt16(_context.GetMethodReferenceId((MethodReference)operand)); break; case OperandType.InlineType: _writer.WriteUInt16(GetTypeReferenceId((TypeReference)operand)); break; case OperandType.InlineField: _writer.WriteUInt16(GetFieldReferenceId((FieldReference)operand)); break; case OperandType.InlineTok: _writer.WriteUInt32(GetMetadataToken((IMetadataTokenProvider)operand)); break; default: throw new ArgumentException(); } } private UInt32 GetMetadataToken( IMetadataTokenProvider token) { UInt16 referenceId; switch (token.MetadataToken.TokenType) { case TokenType.TypeRef: _context.TypeReferencesTable.TryGetTypeReferenceId((TypeReference)token, out referenceId); return (UInt32)0x01000000 | referenceId; case TokenType.TypeDef: _context.TypeDefinitionTable.TryGetTypeReferenceId((TypeDefinition)token, out referenceId); return (UInt32)0x04000000 | referenceId; case TokenType.TypeSpec: _context.TypeSpecificationsTable.TryGetTypeReferenceId((TypeReference) token, out referenceId); return (UInt32)0x08000000 | referenceId; case TokenType.Field: _context.FieldsTable.TryGetFieldReferenceId((FieldDefinition) token, false, out referenceId); return (UInt32)0x05000000 | referenceId; } return 0U; } private UInt16 GetFieldReferenceId( FieldReference fieldReference) { UInt16 referenceId; if (_context.FieldReferencesTable.TryGetFieldReferenceId(fieldReference, out referenceId)) { referenceId |= 0x8000; // External field reference } else { _context.FieldsTable.TryGetFieldReferenceId(fieldReference.Resolve(), false, out referenceId); } return referenceId; } private UInt16 GetTypeReferenceId( TypeReference typeReference, UInt16 typeReferenceMask = 0x4000) { UInt16 referenceId; if (_context.TypeReferencesTable.TryGetTypeReferenceId(typeReference, out referenceId)) { referenceId |= typeReferenceMask; // External type reference } else { if (!_context.TypeDefinitionTable.TryGetTypeReferenceId(typeReference.Resolve(), out referenceId)) { return 0x8000; } } return referenceId; } private Int32 GetTargetOffset ( Instruction instruction) { if (instruction == null) { var last = _body.Instructions[_body.Instructions.Count - 1]; return last.Offset + last.GetSize (); } return instruction.Offset; } private static Int32 GetVariableIndex ( VariableDefinition variable) { return variable.Index; } private Int32 GetParameterIndex ( ParameterDefinition parameter) { if (_body.Method.HasThis) { if (parameter == _body.ThisParameter) return 0; return parameter.Index + 1; } return parameter.Index; } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2009 Stephen M. McKamey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*---------------------------------------------------------------------------------*/ #endregion License using System; using System.Runtime.Serialization; namespace JsonFx.BuildTools { public enum ParseExceptionType { Warning, Error } [Serializable] public abstract class ParseException : ApplicationException { #region Constants // this cannot change every char is important or VS2005 will not list as error/warning private const string VS2005ErrorFormat = "{0}({1},{2}): {3} {4}: {5}"; #endregion Constants #region Fields private string file; private int line; private int column; private int code = 0; #endregion Fields #region Init public ParseException(string message, string file, int line, int column) : base(message) { this.file = file; this.line = line; this.column = column; } public ParseException(string message, string file, int line, int column, Exception innerException) : base(message, innerException) { this.file = file; this.line = line; this.column = column; } #endregion Init #region Properties public abstract ParseExceptionType Type { get; } public virtual int Code { get { return this.code; } } public string ErrorCode { get { string ext = System.IO.Path.GetExtension(file); if (ext == null || ext.Length < 2) { return null; } return ext.Substring(1).ToUpperInvariant()+this.Code.ToString("####0000"); } } public string File { get { return this.file; } } public int Line { get { return this.line; } } public int Column { get { return this.column; } } #endregion Properties #region Methods public virtual string GetCompilerMessage() { return this.GetCompilerMessage(this.Type == ParseExceptionType.Warning); } public virtual string GetCompilerMessage(bool isWarning) { // format exception as a VS2005 error/warning return String.Format( ParseException.VS2005ErrorFormat, this.File, (this.Line > 0) ? this.Line : 1, (this.Column > 0) ? this.Column : 1, isWarning ? "warning" : "error", this.ErrorCode, this.Message); } #endregion Methods } [Serializable] public class ParseWarning : ParseException { #region Init public ParseWarning(string message, string file, int line, int column) : base(message, file, line, column) { } public ParseWarning(string message, string file, int line, int column, Exception innerException) : base(message, file, line, column, innerException) { } #endregion Init #region Properties public override ParseExceptionType Type { get { return ParseExceptionType.Warning; } } #endregion Properties } [Serializable] public class ParseError : ParseException { #region Init public ParseError(string message, string file, int line, int column) : base(message, file, line, column) { } public ParseError(string message, string file, int line, int column, Exception innerException) : base(message, file, line, column, innerException) { } #endregion Init #region Properties public override ParseExceptionType Type { get { return ParseExceptionType.Error; } } #endregion Properties } [Serializable] public class UnexpectedEndOfFile : ParseError { #region Init public UnexpectedEndOfFile(string message, string file, int line, int column) : base(message, file, line, column) { } public UnexpectedEndOfFile(string message, string file, int line, int column, Exception innerException) : base(message, file, line, column, innerException) { } #endregion Init } [Serializable] public class FileError : ParseWarning { #region Init public FileError(string message, string file, int line, int column) : base(message, file, line, column) { } public FileError(string message, string file, int line, int column, Exception innerException) : base(message, file, line, column, innerException) { } #endregion Init } [Serializable] public class SyntaxError : ParseError { #region Init public SyntaxError(string message, string file, int line, int column) : base(message, file, line, column) { } public SyntaxError(string message, string file, int line, int column, Exception innerException) : base(message, file, line, column, innerException) { } #endregion Init } }
// Copyright 2007-2011 The Apache Software Foundation. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.Logging { using System; using Internal; using NLog; /// <summary> /// A logger that wraps to NLog. See http://stackoverflow.com/questions/7412156/how-to-retain-callsite-information-when-wrapping-nlog /// </summary> public class NLogLog : ILog { readonly NLog.Logger _log; /// <summary> /// Create a new NLog logger instance. /// </summary> /// <param name="name">Name of type to log as.</param> public NLogLog([NotNull] NLog.Logger log, [NotNull] string name) { if (name == null) throw new ArgumentNullException("name"); _log = log; _log.Debug(() => ""); } public bool IsDebugEnabled { get { return _log.IsDebugEnabled; } } public bool IsInfoEnabled { get { return _log.IsInfoEnabled; } } public bool IsWarnEnabled { get { return _log.IsWarnEnabled; } } public bool IsErrorEnabled { get { return _log.IsErrorEnabled; } } public bool IsFatalEnabled { get { return _log.IsFatalEnabled; } } public void Log(LogLevel level, object obj) { _log.Log(GetNLogLevel(level), obj); } public void Log(LogLevel level, object obj, Exception exception) { _log.Log(GetNLogLevel(level), obj == null ? "" : obj.ToString(), exception); } public void Log(LogLevel level, LogOutputProvider messageProvider) { _log.Log(GetNLogLevel(level), ToGenerator(messageProvider)); } public void LogFormat(LogLevel level, IFormatProvider formatProvider, string format, params object[] args) { _log.Log(GetNLogLevel(level), formatProvider, format, args); } public void LogFormat(LogLevel level, string format, params object[] args) { _log.Log(GetNLogLevel(level), format, args); } public void Debug(object obj) { _log.Log(NLog.LogLevel.Debug, obj); } public void Debug(object obj, Exception exception) { _log.Log(NLog.LogLevel.Debug, obj == null ? "" : obj.ToString(), exception); } public void Debug(LogOutputProvider messageProvider) { _log.Debug(ToGenerator(messageProvider)); } public void Info(object obj) { _log.Log(NLog.LogLevel.Info, obj); } public void Info(object obj, Exception exception) { _log.Log(NLog.LogLevel.Info, obj == null ? "" : obj.ToString(), exception); } public void Info(LogOutputProvider messageProvider) { _log.Info(ToGenerator(messageProvider)); } public void Warn(object obj) { _log.Log(NLog.LogLevel.Warn, obj); } public void Warn(object obj, Exception exception) { _log.Log(NLog.LogLevel.Warn, obj == null ? "" : obj.ToString(), exception); } public void Warn(LogOutputProvider messageProvider) { _log.Warn(ToGenerator(messageProvider)); } public void Error(object obj) { _log.Log(NLog.LogLevel.Error, obj); } public void Error(object obj, Exception exception) { _log.Log(NLog.LogLevel.Error, obj == null ? "" : obj.ToString(), exception); } public void Error(LogOutputProvider messageProvider) { _log.Error(ToGenerator(messageProvider)); } public void Fatal(object obj) { _log.Log(NLog.LogLevel.Fatal, obj); } public void Fatal(object obj, Exception exception) { _log.Log(NLog.LogLevel.Fatal, obj == null ? "" : obj.ToString(), exception); } public void Fatal(LogOutputProvider messageProvider) { _log.Fatal(ToGenerator(messageProvider)); } public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Debug, formatProvider, format, args); } public void DebugFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Debug, format, args); } public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Info, formatProvider, format, args); } public void InfoFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Info, format, args); } public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Warn, formatProvider, format, args); } public void WarnFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Warn, format, args); } public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Error, formatProvider, format, args); } public void ErrorFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Error, format, args); } public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Fatal, formatProvider, format, args); } public void FatalFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Fatal, format, args); } NLog.LogLevel GetNLogLevel(LogLevel level) { if (level == LogLevel.Fatal) return NLog.LogLevel.Fatal; if (level == LogLevel.Error) return NLog.LogLevel.Error; if (level == LogLevel.Warn) return NLog.LogLevel.Warn; if (level == LogLevel.Info) return NLog.LogLevel.Info; if (level == LogLevel.Debug) return NLog.LogLevel.Debug; if (level == LogLevel.All) return NLog.LogLevel.Trace; return NLog.LogLevel.Off; } LogMessageGenerator ToGenerator(LogOutputProvider provider) { return () => { object obj = provider(); return obj == null ? "" : obj.ToString(); }; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A toystore. /// </summary> public class ToyStore_Core : TypeCore, IStore { public ToyStore_Core() { this._TypeId = 270; this._Id = "ToyStore"; this._Schema_Org_Url = "http://schema.org/ToyStore"; string label = ""; GetLabel(out label, "ToyStore", typeof(ToyStore_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,252}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{252}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Diagnostics; using System.Text; namespace System.Data.SQLite { using sqlite3_callback = Sqlite3.dxCallback; using sqlite3_stmt = Sqlite3.Vdbe; public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Main file for the SQLite library. The routines in this file ** implement the programmer interface to the library. Routines in ** other files are for internal use by SQLite and should not be ** accessed by users of the library. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" /* ** Execute SQL code. Return one of the SQLITE_ success/failure ** codes. Also write an error message into memory obtained from ** malloc() and make pzErrMsg point to that message. ** ** If the SQL is a query, then for each row in the query result ** the xCallback() function is called. pArg becomes the first ** argument to xCallback(). If xCallback=NULL then no callback ** is invoked, even for queries. */ //C# Alias static public int exec(sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ int NoCallback, int NoArgs, int NoErrors) { string Errors = ""; return sqlite3_exec(db, zSql, null, null, ref Errors); } static public int exec(sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ int NoErrors) { string Errors = ""; return sqlite3_exec(db, zSql, xCallback, pArg, ref Errors); } static public int exec(sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ ref string pzErrMsg /* Write error messages here */) { return sqlite3_exec(db, zSql, xCallback, pArg, ref pzErrMsg); } //OVERLOADS static public int sqlite3_exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ int NoCallback, int NoArgs, int NoErrors ) { string Errors = ""; return sqlite3_exec(db, zSql, null, null, ref Errors); } static public int sqlite3_exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ int NoErrors ) { string Errors = ""; return sqlite3_exec(db, zSql, xCallback, pArg, ref Errors); } static public int sqlite3_exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ ref string pzErrMsg /* Write error messages here */ ) { int rc = SQLITE_OK; /* Return code */ string zLeftover = ""; /* Tail of unprocessed SQL */ sqlite3_stmt pStmt = null; /* The current SQL statement */ string[] azCols = null; /* Names of result columns */ int nRetry = 0; /* Number of retry attempts */ int callbackIsInit; /* True if callback data is initialized */ if (!sqlite3SafetyCheckOk(db)) return SQLITE_MISUSE_BKPT(); if (zSql == null) zSql = ""; sqlite3_mutex_enter(db.mutex); sqlite3Error(db, SQLITE_OK, 0); while ((rc == SQLITE_OK || (rc == SQLITE_SCHEMA && (++nRetry) < 2)) && zSql != "") { int nCol; string[] azVals = null; pStmt = null; rc = sqlite3_prepare(db, zSql, -1, ref pStmt, ref zLeftover); Debug.Assert(rc == SQLITE_OK || pStmt == null); if (rc != SQLITE_OK) { continue; } if (pStmt == null) { /* this happens for a comment or white-space */ zSql = zLeftover; continue; } callbackIsInit = 0; nCol = sqlite3_column_count(pStmt); while (true) { int i; rc = sqlite3_step(pStmt); /* Invoke the callback function if required */ if (xCallback != null && (SQLITE_ROW == rc || (SQLITE_DONE == rc && callbackIsInit == 0 && (db.flags & SQLITE_NullCallback) != 0))) { if (0 == callbackIsInit) { azCols = new string[nCol];//sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); //if ( azCols == null ) //{ // goto exec_out; //} for (i = 0; i < nCol; i++) { azCols[i] = sqlite3_column_name(pStmt, i); /* sqlite3VdbeSetColName() installs column names as UTF8 ** strings so there is no way for sqlite3_column_name() to fail. */ Debug.Assert(azCols[i] != null); } callbackIsInit = 1; } if (rc == SQLITE_ROW) { azVals = new string[nCol];// azCols[nCol]; for (i = 0; i < nCol; i++) { azVals[i] = sqlite3_column_text(pStmt, i); if (azVals[i] == null && sqlite3_column_type(pStmt, i) != SQLITE_NULL) { //db.mallocFailed = 1; //goto exec_out; } } } if (xCallback(pArg, nCol, azVals, azCols) != 0) { rc = SQLITE_ABORT; sqlite3VdbeFinalize(ref pStmt); pStmt = null; sqlite3Error(db, SQLITE_ABORT, 0); goto exec_out; } } if (rc != SQLITE_ROW) { rc = sqlite3VdbeFinalize(ref pStmt); pStmt = null; if (rc != SQLITE_SCHEMA) { nRetry = 0; if ((zSql = zLeftover) != "") { int zindex = 0; while (zindex < zSql.Length && sqlite3Isspace(zSql[zindex])) zindex++; if (zindex != 0) zSql = zindex < zSql.Length ? zSql.Substring(zindex) : ""; } } break; } } sqlite3DbFree(db, ref azCols); azCols = null; } exec_out: if (pStmt != null) sqlite3VdbeFinalize(ref pStmt); sqlite3DbFree(db, ref azCols); rc = sqlite3ApiExit(db, rc); if (rc != SQLITE_OK && ALWAYS(rc == sqlite3_errcode(db)) && pzErrMsg != null) { //int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db)); //pzErrMsg = sqlite3Malloc(nErrMsg); //if (pzErrMsg) //{ // memcpy(pzErrMsg, sqlite3_errmsg(db), nErrMsg); //}else{ //rc = SQLITE_NOMEM; //sqlite3Error(db, SQLITE_NOMEM, 0); //} pzErrMsg = sqlite3_errmsg(db); } else if (pzErrMsg != "") { pzErrMsg = ""; } Debug.Assert((rc & db.errMask) == rc); sqlite3_mutex_leave(db.mutex); return rc; } } }
namespace System.Data.Odbc { public sealed partial class OdbcCommand : System.Data.Common.DbCommand, System.ICloneable { public OdbcCommand() { } public OdbcCommand(string cmdText) { } public OdbcCommand(string cmdText, System.Data.Odbc.OdbcConnection connection) { } public OdbcCommand(string cmdText, System.Data.Odbc.OdbcConnection connection, System.Data.Odbc.OdbcTransaction transaction) { } public override string CommandText { get { throw null; } set { } } public override int CommandTimeout { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute((System.Data.CommandType)(1))] public override System.Data.CommandType CommandType { get { throw null; } set { } } public new System.Data.Odbc.OdbcConnection Connection { get { throw null; } set { } } protected override System.Data.Common.DbConnection DbConnection { get { throw null; } set { } } protected override System.Data.Common.DbParameterCollection DbParameterCollection { get { throw null; } } protected override System.Data.Common.DbTransaction DbTransaction { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DefaultValueAttribute(true)] [System.ComponentModel.DesignOnlyAttribute(true)] [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public override bool DesignTimeVisible { get { throw null; } set { } } [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(2))] public new System.Data.Odbc.OdbcParameterCollection Parameters { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] public new System.Data.Odbc.OdbcTransaction Transaction { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute((System.Data.UpdateRowSource)(3))] public override System.Data.UpdateRowSource UpdatedRowSource { get { throw null; } set { } } public override void Cancel() { } protected override System.Data.Common.DbParameter CreateDbParameter() { throw null; } public new System.Data.Odbc.OdbcParameter CreateParameter() { throw null; } protected override void Dispose(bool disposing) { } protected override System.Data.Common.DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior behavior) { throw null; } public override int ExecuteNonQuery() { throw null; } public new System.Data.Odbc.OdbcDataReader ExecuteReader() { throw null; } public new System.Data.Odbc.OdbcDataReader ExecuteReader(System.Data.CommandBehavior behavior) { throw null; } public override object ExecuteScalar() { throw null; } public override void Prepare() { } public void ResetCommandTimeout() { } object System.ICloneable.Clone() { throw null; } } public sealed partial class OdbcCommandBuilder : System.Data.Common.DbCommandBuilder { public OdbcCommandBuilder() { } public OdbcCommandBuilder(System.Data.Odbc.OdbcDataAdapter adapter) { } public new System.Data.Odbc.OdbcDataAdapter DataAdapter { get { throw null; } set { } } protected override void ApplyParameterInfo(System.Data.Common.DbParameter parameter, System.Data.DataRow datarow, System.Data.StatementType statementType, bool whereClause) { } public static void DeriveParameters(System.Data.Odbc.OdbcCommand command) { } public new System.Data.Odbc.OdbcCommand GetDeleteCommand() { throw null; } public new System.Data.Odbc.OdbcCommand GetDeleteCommand(bool useColumnsForParameterNames) { throw null; } public new System.Data.Odbc.OdbcCommand GetInsertCommand() { throw null; } public new System.Data.Odbc.OdbcCommand GetInsertCommand(bool useColumnsForParameterNames) { throw null; } protected override string GetParameterName(int parameterOrdinal) { throw null; } protected override string GetParameterName(string parameterName) { throw null; } protected override string GetParameterPlaceholder(int parameterOrdinal) { throw null; } public new System.Data.Odbc.OdbcCommand GetUpdateCommand() { throw null; } public new System.Data.Odbc.OdbcCommand GetUpdateCommand(bool useColumnsForParameterNames) { throw null; } public override string QuoteIdentifier(string unquotedIdentifier) { throw null; } public string QuoteIdentifier(string unquotedIdentifier, System.Data.Odbc.OdbcConnection connection) { throw null; } protected override void SetRowUpdatingHandler(System.Data.Common.DbDataAdapter adapter) { } public override string UnquoteIdentifier(string quotedIdentifier) { throw null; } public string UnquoteIdentifier(string quotedIdentifier, System.Data.Odbc.OdbcConnection connection) { throw null; } } public sealed partial class OdbcConnection : System.Data.Common.DbConnection, System.ICloneable { public OdbcConnection() { } public OdbcConnection(string connectionString) { } public override string ConnectionString { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute(15)] [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] public new int ConnectionTimeout { get { throw null; } set { } } [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] public override string Database { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] public override string DataSource { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] public string Driver { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] public override string ServerVersion { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] public override System.Data.ConnectionState State { get { throw null; } } public event System.Data.Odbc.OdbcInfoMessageEventHandler InfoMessage { add { } remove { } } protected override System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { throw null; } public new System.Data.Odbc.OdbcTransaction BeginTransaction() { throw null; } public new System.Data.Odbc.OdbcTransaction BeginTransaction(System.Data.IsolationLevel isolevel) { throw null; } public override void ChangeDatabase(string value) { } public override void Close() { } public new System.Data.Odbc.OdbcCommand CreateCommand() { throw null; } protected override System.Data.Common.DbCommand CreateDbCommand() { throw null; } protected override void Dispose(bool disposing) { } public override void Open() { } public static void ReleaseObjectPool() { } object System.ICloneable.Clone() { throw null; } } public sealed partial class OdbcConnectionStringBuilder : System.Data.Common.DbConnectionStringBuilder { public OdbcConnectionStringBuilder() { } public OdbcConnectionStringBuilder(string connectionString) { } [System.ComponentModel.DisplayNameAttribute("Driver")] public string Driver { get { throw null; } set { } } [System.ComponentModel.DisplayNameAttribute("Dsn")] public string Dsn { get { throw null; } set { } } public override object this[string keyword] { get { throw null; } set { } } public override System.Collections.ICollection Keys { get { throw null; } } public override void Clear() { } public override bool ContainsKey(string keyword) { throw null; } public override bool Remove(string keyword) { throw null; } public override bool TryGetValue(string keyword, out object value) { value = default(object); throw null; } } public sealed partial class OdbcDataAdapter : System.Data.Common.DbDataAdapter, System.Data.IDataAdapter, System.Data.IDbDataAdapter, System.ICloneable { public OdbcDataAdapter() { } public OdbcDataAdapter(System.Data.Odbc.OdbcCommand selectCommand) { } public OdbcDataAdapter(string selectCommandText, System.Data.Odbc.OdbcConnection selectConnection) { } public OdbcDataAdapter(string selectCommandText, string selectConnectionString) { } public new System.Data.Odbc.OdbcCommand DeleteCommand { get { throw null; } set { } } public new System.Data.Odbc.OdbcCommand InsertCommand { get { throw null; } set { } } public new System.Data.Odbc.OdbcCommand SelectCommand { get { throw null; } set { } } System.Data.IDbCommand System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } } System.Data.IDbCommand System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } } System.Data.IDbCommand System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } } System.Data.IDbCommand System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } } public new System.Data.Odbc.OdbcCommand UpdateCommand { get { throw null; } set { } } public event System.Data.Odbc.OdbcRowUpdatedEventHandler RowUpdated { add { } remove { } } public event System.Data.Odbc.OdbcRowUpdatingEventHandler RowUpdating { add { } remove { } } protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(System.Data.DataRow dataRow, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) { throw null; } protected override void OnRowUpdated(System.Data.Common.RowUpdatedEventArgs value) { } protected override void OnRowUpdating(System.Data.Common.RowUpdatingEventArgs value) { } object System.ICloneable.Clone() { throw null; } } public sealed partial class OdbcDataReader : System.Data.Common.DbDataReader { internal OdbcDataReader() { } public override int Depth { get { throw null; } } public override int FieldCount { get { throw null; } } public override bool HasRows { get { throw null; } } public override bool IsClosed { get { throw null; } } public override object this[int i] { get { throw null; } } public override object this[string value] { get { throw null; } } public override int RecordsAffected { get { throw null; } } public override void Close() { } protected override void Dispose(bool disposing) { } public override bool GetBoolean(int i) { throw null; } public override byte GetByte(int i) { throw null; } public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { throw null; } public override char GetChar(int i) { throw null; } public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) { throw null; } public override string GetDataTypeName(int i) { throw null; } public System.DateTime GetDate(int i) { throw null; } public override System.DateTime GetDateTime(int i) { throw null; } public override decimal GetDecimal(int i) { throw null; } public override double GetDouble(int i) { throw null; } public override System.Collections.IEnumerator GetEnumerator() { throw null; } public override System.Type GetFieldType(int i) { throw null; } public override float GetFloat(int i) { throw null; } public override System.Guid GetGuid(int i) { throw null; } public override short GetInt16(int i) { throw null; } public override int GetInt32(int i) { throw null; } public override long GetInt64(int i) { throw null; } public override string GetName(int i) { throw null; } public override int GetOrdinal(string value) { throw null; } public override System.Data.DataTable GetSchemaTable() { throw null; } public override string GetString(int i) { throw null; } public System.TimeSpan GetTime(int i) { throw null; } public override object GetValue(int i) { throw null; } public override int GetValues(object[] values) { throw null; } public override bool IsDBNull(int i) { throw null; } public override bool NextResult() { throw null; } public override bool Read() { throw null; } } public sealed partial class OdbcError { internal OdbcError() { } public string Message { get { throw null; } } public int NativeError { get { throw null; } } public string Source { get { throw null; } } public string SQLState { get { throw null; } } public override string ToString() { throw null; } } public sealed partial class OdbcErrorCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal OdbcErrorCollection() { } public int Count { get { throw null; } } public System.Data.Odbc.OdbcError this[int i] { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void CopyTo(System.Array array, int i) { } public void CopyTo(System.Data.Odbc.OdbcError[] array, int i) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } } public sealed partial class OdbcException : System.Data.Common.DbException { internal OdbcException() { } public System.Data.Odbc.OdbcErrorCollection Errors { get { throw null; } } public override string Source { get { throw null; } } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=(System.Security.Permissions.SecurityPermissionFlag)(128))] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { } } public sealed partial class OdbcFactory : System.Data.Common.DbProviderFactory { internal OdbcFactory() { } public static readonly System.Data.Odbc.OdbcFactory Instance; public override System.Data.Common.DbCommand CreateCommand() { throw null; } public override System.Data.Common.DbCommandBuilder CreateCommandBuilder() { throw null; } public override System.Data.Common.DbConnection CreateConnection() { throw null; } public override System.Data.Common.DbConnectionStringBuilder CreateConnectionStringBuilder() { throw null; } public override System.Data.Common.DbDataAdapter CreateDataAdapter() { throw null; } public override System.Data.Common.DbParameter CreateParameter() { throw null; } } public sealed partial class OdbcInfoMessageEventArgs : System.EventArgs { internal OdbcInfoMessageEventArgs() { } public System.Data.Odbc.OdbcErrorCollection Errors { get { throw null; } } public string Message { get { throw null; } } public override string ToString() { throw null; } } public delegate void OdbcInfoMessageEventHandler(object sender, System.Data.Odbc.OdbcInfoMessageEventArgs e); public static partial class OdbcMetaDataCollectionNames { public static readonly string Columns; public static readonly string Indexes; public static readonly string ProcedureColumns; public static readonly string ProcedureParameters; public static readonly string Procedures; public static readonly string Tables; public static readonly string Views; } public static partial class OdbcMetaDataColumnNames { public static readonly string BooleanFalseLiteral; public static readonly string BooleanTrueLiteral; public static readonly string SQLType; } public sealed partial class OdbcParameter : System.Data.Common.DbParameter, System.Data.IDataParameter, System.Data.IDbDataParameter, System.ICloneable { public OdbcParameter() { } public OdbcParameter(string name, System.Data.Odbc.OdbcType type) { } public OdbcParameter(string name, System.Data.Odbc.OdbcType type, int size) { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(2))] public OdbcParameter(string parameterName, System.Data.Odbc.OdbcType odbcType, int size, System.Data.ParameterDirection parameterDirection, bool isNullable, byte precision, byte scale, string srcColumn, System.Data.DataRowVersion srcVersion, object value) { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(2))] public OdbcParameter(string parameterName, System.Data.Odbc.OdbcType odbcType, int size, System.Data.ParameterDirection parameterDirection, byte precision, byte scale, string sourceColumn, System.Data.DataRowVersion sourceVersion, bool sourceColumnNullMapping, object value) { } public OdbcParameter(string name, System.Data.Odbc.OdbcType type, int size, string sourcecolumn) { } public OdbcParameter(string name, object value) { } public override System.Data.DbType DbType { get { throw null; } set { } } public override System.Data.ParameterDirection Direction { get { throw null; } set { } } public override bool IsNullable { get { throw null; } set { } } [System.ComponentModel.DefaultValueAttribute((System.Data.Odbc.OdbcType)(11))] [System.Data.Common.DbProviderSpecificTypePropertyAttribute(true)] public System.Data.Odbc.OdbcType OdbcType { get { throw null; } set { } } public override string ParameterName { get { throw null; } set { } } public new byte Precision { get { throw null; } set { } } public new byte Scale { get { throw null; } set { } } public override int Size { get { throw null; } set { } } public override string SourceColumn { get { throw null; } set { } } public override bool SourceColumnNullMapping { get { throw null; } set { } } public override System.Data.DataRowVersion SourceVersion { get { throw null; } set { } } public override object Value { get { throw null; } set { } } public override void ResetDbType() { } public void ResetOdbcType() { } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } } public sealed partial class OdbcParameterCollection : System.Data.Common.DbParameterCollection { internal OdbcParameterCollection() { } public override int Count { get { throw null; } } public override bool IsFixedSize { get { throw null; } } public override bool IsReadOnly { get { throw null; } } public override bool IsSynchronized { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] public new System.Data.Odbc.OdbcParameter this[int index] { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))] public new System.Data.Odbc.OdbcParameter this[string parameterName] { get { throw null; } set { } } public override object SyncRoot { get { throw null; } } public System.Data.Odbc.OdbcParameter Add(System.Data.Odbc.OdbcParameter value) { throw null; } public override int Add(object value) { throw null; } public System.Data.Odbc.OdbcParameter Add(string parameterName, System.Data.Odbc.OdbcType odbcType) { throw null; } public System.Data.Odbc.OdbcParameter Add(string parameterName, System.Data.Odbc.OdbcType odbcType, int size) { throw null; } public System.Data.Odbc.OdbcParameter Add(string parameterName, System.Data.Odbc.OdbcType odbcType, int size, string sourceColumn) { throw null; } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value). http://go.microsoft.com/fwlink/?linkid=14202", false)] public System.Data.Odbc.OdbcParameter Add(string parameterName, object value) { throw null; } public override void AddRange(System.Array values) { } public void AddRange(System.Data.Odbc.OdbcParameter[] values) { } public System.Data.Odbc.OdbcParameter AddWithValue(string parameterName, object value) { throw null; } public override void Clear() { } public bool Contains(System.Data.Odbc.OdbcParameter value) { throw null; } public override bool Contains(object value) { throw null; } public override bool Contains(string value) { throw null; } public override void CopyTo(System.Array array, int index) { } public void CopyTo(System.Data.Odbc.OdbcParameter[] array, int index) { } public override System.Collections.IEnumerator GetEnumerator() { throw null; } protected override System.Data.Common.DbParameter GetParameter(int index) { throw null; } protected override System.Data.Common.DbParameter GetParameter(string parameterName) { throw null; } public int IndexOf(System.Data.Odbc.OdbcParameter value) { throw null; } public override int IndexOf(object value) { throw null; } public override int IndexOf(string parameterName) { throw null; } public void Insert(int index, System.Data.Odbc.OdbcParameter value) { } public override void Insert(int index, object value) { } public void Remove(System.Data.Odbc.OdbcParameter value) { } public override void Remove(object value) { } public override void RemoveAt(int index) { } public override void RemoveAt(string parameterName) { } protected override void SetParameter(int index, System.Data.Common.DbParameter value) { } protected override void SetParameter(string parameterName, System.Data.Common.DbParameter value) { } } public sealed partial class OdbcRowUpdatedEventArgs : System.Data.Common.RowUpdatedEventArgs { public OdbcRowUpdatedEventArgs(System.Data.DataRow row, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { } public new System.Data.Odbc.OdbcCommand Command { get { throw null; } } } public delegate void OdbcRowUpdatedEventHandler(object sender, System.Data.Odbc.OdbcRowUpdatedEventArgs e); public sealed partial class OdbcRowUpdatingEventArgs : System.Data.Common.RowUpdatingEventArgs { public OdbcRowUpdatingEventArgs(System.Data.DataRow row, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { } protected override System.Data.IDbCommand BaseCommand { get { throw null; } set { } } public new System.Data.Odbc.OdbcCommand Command { get { throw null; } set { } } } public delegate void OdbcRowUpdatingEventHandler(object sender, System.Data.Odbc.OdbcRowUpdatingEventArgs e); public sealed partial class OdbcTransaction : System.Data.Common.DbTransaction { internal OdbcTransaction() { } public new System.Data.Odbc.OdbcConnection Connection { get { throw null; } } protected override System.Data.Common.DbConnection DbConnection { get { throw null; } } public override System.Data.IsolationLevel IsolationLevel { get { throw null; } } public override void Commit() { } protected override void Dispose(bool disposing) { } public override void Rollback() { } } public enum OdbcType { BigInt = 1, Binary = 2, Bit = 3, Char = 4, Date = 23, DateTime = 5, Decimal = 6, Double = 8, Image = 9, Int = 10, NChar = 11, NText = 12, Numeric = 7, NVarChar = 13, Real = 14, SmallDateTime = 16, SmallInt = 17, Text = 18, Time = 24, Timestamp = 19, TinyInt = 20, UniqueIdentifier = 15, VarBinary = 21, VarChar = 22, } }
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.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 pb.locationIntelligence.Model { /// <summary> /// FloodZone /// </summary> [DataContract] public partial class FloodZone : IEquatable<FloodZone> { /// <summary> /// Initializes a new instance of the <see cref="FloodZone" /> class. /// </summary> /// <param name="Code">Code.</param> /// <param name="AreaType">AreaType.</param> /// <param name="RiskLevel">RiskLevel.</param> /// <param name="PrimaryZone">PrimaryZone.</param> /// <param name="BaseFloodElevation">BaseFloodElevation.</param> /// <param name="AdditionalInfo">AdditionalInfo.</param> public FloodZone(string Code = null, string AreaType = null, string RiskLevel = null, PrimaryZone PrimaryZone = null, BaseFloodElevation BaseFloodElevation = null, string AdditionalInfo = null) { this.Code = Code; this.AreaType = AreaType; this.RiskLevel = RiskLevel; this.PrimaryZone = PrimaryZone; this.BaseFloodElevation = BaseFloodElevation; this.AdditionalInfo = AdditionalInfo; } /// <summary> /// Gets or Sets Code /// </summary> [DataMember(Name="code", EmitDefaultValue=false)] public string Code { get; set; } /// <summary> /// Gets or Sets AreaType /// </summary> [DataMember(Name="areaType", EmitDefaultValue=false)] public string AreaType { get; set; } /// <summary> /// Gets or Sets RiskLevel /// </summary> [DataMember(Name="riskLevel", EmitDefaultValue=false)] public string RiskLevel { get; set; } /// <summary> /// Gets or Sets PrimaryZone /// </summary> [DataMember(Name="primaryZone", EmitDefaultValue=false)] public PrimaryZone PrimaryZone { get; set; } /// <summary> /// Gets or Sets BaseFloodElevation /// </summary> [DataMember(Name="baseFloodElevation", EmitDefaultValue=false)] public BaseFloodElevation BaseFloodElevation { get; set; } /// <summary> /// Gets or Sets AdditionalInfo /// </summary> [DataMember(Name="additionalInfo", EmitDefaultValue=false)] public string AdditionalInfo { 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 FloodZone {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" AreaType: ").Append(AreaType).Append("\n"); sb.Append(" RiskLevel: ").Append(RiskLevel).Append("\n"); sb.Append(" PrimaryZone: ").Append(PrimaryZone).Append("\n"); sb.Append(" BaseFloodElevation: ").Append(BaseFloodElevation).Append("\n"); sb.Append(" AdditionalInfo: ").Append(AdditionalInfo).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 FloodZone); } /// <summary> /// Returns true if FloodZone instances are equal /// </summary> /// <param name="other">Instance of FloodZone to be compared</param> /// <returns>Boolean</returns> public bool Equals(FloodZone other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Code == other.Code || this.Code != null && this.Code.Equals(other.Code) ) && ( this.AreaType == other.AreaType || this.AreaType != null && this.AreaType.Equals(other.AreaType) ) && ( this.RiskLevel == other.RiskLevel || this.RiskLevel != null && this.RiskLevel.Equals(other.RiskLevel) ) && ( this.PrimaryZone == other.PrimaryZone || this.PrimaryZone != null && this.PrimaryZone.Equals(other.PrimaryZone) ) && ( this.BaseFloodElevation == other.BaseFloodElevation || this.BaseFloodElevation != null && this.BaseFloodElevation.Equals(other.BaseFloodElevation) ) && ( this.AdditionalInfo == other.AdditionalInfo || this.AdditionalInfo != null && this.AdditionalInfo.Equals(other.AdditionalInfo) ); } /// <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.Code != null) hash = hash * 59 + this.Code.GetHashCode(); if (this.AreaType != null) hash = hash * 59 + this.AreaType.GetHashCode(); if (this.RiskLevel != null) hash = hash * 59 + this.RiskLevel.GetHashCode(); if (this.PrimaryZone != null) hash = hash * 59 + this.PrimaryZone.GetHashCode(); if (this.BaseFloodElevation != null) hash = hash * 59 + this.BaseFloodElevation.GetHashCode(); if (this.AdditionalInfo != null) hash = hash * 59 + this.AdditionalInfo.GetHashCode(); return hash; } } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, [email protected], FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Xml; using System.Xml.Serialization; using System.Collections; using System.Collections.Specialized; using System.Reflection; using System.IO; using FluorineFx.Messaging; namespace FluorineFx.Configuration { /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public class ConfigurationSection { } /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlRootAttribute("configuration")] public class ApplicationConfiguration { ApplicationHandlerConfiguration _applicationHandler; StreamFilenameGeneratorConfiguration _streamFilenameGenerator; SharedObjectServiceConfiguration _sharedObjectServiceConfiguration; ProviderServiceConfiguration _providerService; ConsumerServiceConfiguration _consumerServiceConfiguration; StreamServiceConfiguration _streamService; SharedObjectSecurityServiceConfiguration _sharedObjectSecurityService; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlElement("application-handler")] public ApplicationHandlerConfiguration ApplicationHandler { get { if (_applicationHandler == null) return _applicationHandler = new ApplicationHandlerConfiguration(); return _applicationHandler; } set { _applicationHandler = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlElement("streamFilenameGenerator")] public StreamFilenameGeneratorConfiguration StreamFilenameGenerator { get { if (_streamFilenameGenerator == null) return _streamFilenameGenerator = new StreamFilenameGeneratorConfiguration(); return _streamFilenameGenerator; } set { _streamFilenameGenerator = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlElement("sharedObjectService")] public SharedObjectServiceConfiguration SharedObjectServiceConfiguration { get { if (_sharedObjectServiceConfiguration == null) return _sharedObjectServiceConfiguration = new SharedObjectServiceConfiguration(); return _sharedObjectServiceConfiguration; } set { _sharedObjectServiceConfiguration = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlElement("streamService")] public StreamServiceConfiguration StreamService { get { if (_streamService == null) return _streamService = new StreamServiceConfiguration(); return _streamService; } set { _streamService = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlElement("providerService")] public ProviderServiceConfiguration ProviderServiceConfiguration { get { if (_providerService == null) return _providerService = new ProviderServiceConfiguration(); return _providerService; } set { _providerService = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlElement("consumerService")] public ConsumerServiceConfiguration ConsumerServiceConfiguration { get { if (_consumerServiceConfiguration == null) return _consumerServiceConfiguration = new ConsumerServiceConfiguration(); return _consumerServiceConfiguration; } set { _consumerServiceConfiguration = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlElement("sharedObjectSecurityService")] public SharedObjectSecurityServiceConfiguration SharedObjectSecurityService { get { if (_sharedObjectSecurityService == null) return _sharedObjectSecurityService = new SharedObjectSecurityServiceConfiguration(); return _sharedObjectSecurityService; } set { _sharedObjectSecurityService = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> /// <param name="path"></param> /// <returns></returns> public static ApplicationConfiguration Load(string path) { if (!File.Exists(path)) return new ApplicationConfiguration(); using (StreamReader streamReader = new StreamReader(path)) { XmlSerializer serializer = new XmlSerializer(typeof(ApplicationConfiguration)); ApplicationConfiguration config = serializer.Deserialize(streamReader) as ApplicationConfiguration; streamReader.Close(); return config; } } } /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public class ApplicationHandlerConfiguration : ConfigurationSection { string _type; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlAttribute("type")] public string Type { get { if( _type != null ) return _type; return typeof(FluorineFx.Messaging.Adapter.ApplicationAdapter).FullName; } set { _type = value; } } string _factory; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlAttribute("factory")] public string Factory { get { if (_factory != null) return _factory; return DotNetFactory.Id; } set { _factory = value; } } } /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public class StreamFilenameGeneratorConfiguration : ConfigurationSection { string _type; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlAttribute("type")] public string Type { get { if (_type != null) return _type; return typeof(FluorineFx.Messaging.Rtmp.Stream.DefaultStreamFilenameGenerator).FullName; } set { _type = value; } } } /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public class SharedObjectServiceConfiguration : ConfigurationSection { string _type; PersistenceStoreConfiguration _persistenceStore; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlAttribute("type")] public string Type { get { if (_type != null) return _type; return typeof(FluorineFx.Messaging.Rtmp.SO.SharedObjectService).FullName; } set { _type = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlElement("persistenceStore")] public PersistenceStoreConfiguration PersistenceStore { get { if (_persistenceStore == null) return _persistenceStore = new PersistenceStoreConfiguration(); return _persistenceStore; } set { _persistenceStore = value; } } } /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public class PersistenceStoreConfiguration { string _type; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlAttribute("type")] public string Type { get { if (_type != null) return _type; return typeof(FluorineFx.Messaging.Rtmp.Persistence.MemoryStore).FullName; } set { _type = value; } } } /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public class ProviderServiceConfiguration : ConfigurationSection { string _type; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlAttribute("type")] public string Type { get { if (_type != null) return _type; return typeof(FluorineFx.Messaging.Rtmp.Stream.ProviderService).FullName; } set { _type = value; } } } /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public class ConsumerServiceConfiguration : ConfigurationSection { string _type; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlAttribute("type")] public string Type { get { if (_type != null) return _type; return typeof(FluorineFx.Messaging.Rtmp.Stream.ConsumerService).FullName; } set { _type = value; } } } /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public class StreamServiceConfiguration : ConfigurationSection { string _type; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlAttribute("type")] public string Type { get { if (_type != null) return _type; return typeof(FluorineFx.Messaging.Rtmp.Stream.StreamService).FullName; } set { _type = value; } } } /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public class SharedObjectSecurityServiceConfiguration : ConfigurationSection { string _type; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [XmlAttribute("type")] public string Type { get { return _type; } set { _type = value; } } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Handlers; using OrchardCore.DisplayManagement; using OrchardCore.Media; using OrchardCore.Mvc.Core.Utilities; using OrchardCore.Seo.Models; using OrchardCore.Settings; namespace OrchardCore.Seo.Drivers { public class SeoMetaPartHandler : ContentPartHandler<SeoMetaPart> { private readonly IMediaFileStore _mediaFileStore; private readonly ISiteService _siteService; private readonly IActionContextAccessor _actionContextAccessor; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IUrlHelperFactory _urlHelperFactory; private readonly IContentManager _contentManager; public SeoMetaPartHandler( IMediaFileStore mediaFileStore, ISiteService siteService, IActionContextAccessor actionContextAccessor, IHttpContextAccessor httpContextAccessor, IUrlHelperFactory urlHelperFactory, IContentManager contentManager ) { _mediaFileStore = mediaFileStore; _siteService = siteService; _actionContextAccessor = actionContextAccessor; _httpContextAccessor = httpContextAccessor; _urlHelperFactory = urlHelperFactory; _contentManager = contentManager; } public override Task GetContentItemAspectAsync(ContentItemAspectContext context, SeoMetaPart part) { return context.ForAsync<SeoAspect>(async aspect => { aspect.Render = part.Render; if (!String.IsNullOrEmpty(part.PageTitle)) { aspect.PageTitle = part.PageTitle; } if (!String.IsNullOrEmpty(part.MetaDescription)) { aspect.MetaDescription = part.MetaDescription; } if (!String.IsNullOrEmpty(part.MetaKeywords)) { aspect.MetaKeywords = part.MetaKeywords; } if (!String.IsNullOrEmpty(part.MetaRobots)) { aspect.MetaRobots = part.MetaRobots; } aspect.CustomMetaTags = part.CustomMetaTags; var siteSettings = await _siteService.GetSiteSettingsAsync(); var actionContext = _actionContextAccessor.ActionContext; if (actionContext == null) { actionContext = await GetActionContextAsync(_httpContextAccessor.HttpContext); } var urlHelper = _urlHelperFactory.GetUrlHelper(actionContext); if (!String.IsNullOrEmpty(part.Canonical)) { aspect.Canonical = part.Canonical; } else { var contentItemMetadata = await _contentManager.PopulateAspectAsync<ContentItemMetadata>(part.ContentItem); var relativeUrl = urlHelper.RouteUrl(contentItemMetadata.DisplayRouteValues); aspect.Canonical = urlHelper.ToAbsoluteUrl(relativeUrl); } // OpenGraph if (part.OpenGraphImage?.Paths?.Length > 0) { aspect.OpenGraphImage = urlHelper.ToAbsoluteUrl(_mediaFileStore.MapPathToPublicUrl(part.OpenGraphImage.Paths[0])); } else if (part.DefaultSocialImage?.Paths?.Length > 0) { aspect.OpenGraphImage = urlHelper.ToAbsoluteUrl(_mediaFileStore.MapPathToPublicUrl(part.DefaultSocialImage.Paths[0])); } if (part.OpenGraphImage?.MediaTexts?.Length > 0) { aspect.OpenGraphImageAlt = part.OpenGraphImage.MediaTexts[0]; } else if (part.DefaultSocialImage?.MediaTexts?.Length > 0) { aspect.OpenGraphImageAlt = part.DefaultSocialImage.MediaTexts[0]; } if (!String.IsNullOrEmpty(part.OpenGraphTitle)) { aspect.OpenGraphTitle = part.OpenGraphTitle; } else { aspect.OpenGraphTitle = part.PageTitle; } if (!String.IsNullOrEmpty(part.OpenGraphDescription)) { aspect.OpenGraphDescription = part.OpenGraphDescription; } else { aspect.OpenGraphDescription = part.MetaDescription; } // Twitter if (part.TwitterImage?.Paths?.Length > 0) { aspect.TwitterImage = urlHelper.ToAbsoluteUrl(_mediaFileStore.MapPathToPublicUrl(part.TwitterImage.Paths[0])); } else if (part.DefaultSocialImage?.Paths?.Length > 0) { aspect.TwitterImage = urlHelper.ToAbsoluteUrl(_mediaFileStore.MapPathToPublicUrl(part.DefaultSocialImage.Paths[0])); } if (part.TwitterImage?.MediaTexts?.Length > 0) { aspect.TwitterImageAlt = part.TwitterImage.MediaTexts[0]; } else if (part.DefaultSocialImage?.MediaTexts?.Length > 0) { aspect.TwitterImageAlt = part.DefaultSocialImage.MediaTexts[0]; } if (!String.IsNullOrEmpty(part.TwitterTitle)) { aspect.TwitterTitle = part.TwitterTitle; } else { aspect.TwitterTitle = part.PageTitle; } if (!String.IsNullOrEmpty(part.TwitterDescription)) { aspect.TwitterDescription = part.TwitterDescription; } else { aspect.TwitterDescription = part.MetaDescription; } if (!String.IsNullOrEmpty(part.TwitterCard)) { aspect.TwitterCard = part.TwitterCard; } if (!String.IsNullOrEmpty(part.TwitterCreator)) { aspect.TwitterCreator = part.TwitterCreator; } if (!String.IsNullOrEmpty(part.TwitterSite)) { aspect.TwitterSite = part.TwitterSite; } aspect.GoogleSchema = part.GoogleSchema; }); } internal static async Task<ActionContext> GetActionContextAsync(HttpContext httpContext) { var routeData = new RouteData(); routeData.Routers.Add(new RouteCollection()); var actionContext = new ActionContext(httpContext, routeData, new ActionDescriptor()); var filters = httpContext.RequestServices.GetServices<IAsyncViewActionFilter>(); foreach (var filter in filters) { await filter.OnActionExecutionAsync(actionContext); } return actionContext; } } }
// // DeviceMediaCapabilities.cs // // Author: // Alex Launi <[email protected]> // // Copyright (c) 2010 Alex Launi // // 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. #if ENABLE_GIO_HARDWARE using System; using System.Collections.Generic; using System.Linq; using KeyFile; using Banshee.Base; using Banshee.Hardware; using Banshee.IO; namespace Banshee.Hardware.Gio { class DeviceMediaCapabilities : IDeviceMediaCapabilities { private GMpiFileInfo mpi; // TODO implement. The technique for this will be to write a private // MPI reader class that I can use to query the mpi file for `device'. // the MPI file is found using the ID_MEDIA_PLAYER udev property + .mpi // in /usr/[local/]share/. public DeviceMediaCapabilities (RawDevice device) { mpi = new GMpiFileInfo (device.IdMediaPlayer); } public string[] OutputFormats { get { return mpi.OutputFormats; } } #region IDeviceMediaCapabilities implementation public string[] AudioFolders { get { return mpi.AudioFolders; } } // FIXME // MPI has no property for this yet public string CoverArtFileName { get { return ""; } } // FIXME // MPI has no property for this yet public string CoverArtFileType { get { return ""; } } // FIXME // MPI has no property for this yet public int CoverArtSize { get { return -1; } } public int FolderDepth { get { return mpi.FolderDepth; } } public bool IsType (string type) { return mpi.AccessProtocols.Contains (type); } public string[] PlaybackMimeTypes { get { return mpi.OutputFormats; } } public string[] PlaylistFormats { get { return mpi.PlaylistFormats; } } public string PlaylistPath { get { return mpi.PlaylistPath; } } // FIXME // MPI has no property for this yet public string[] VideoFolders { get { return new string[] {""}; } } #endregion private class GMpiFileInfo { private const string MediaGroup = "Media"; private const string DeviceGroup = "Device"; private const string VendorGroup = "Vendor"; private const string StorageGroup = "storage"; private const string PlaylistGroup = "Playlist"; private GKeyFile mpi_file; public GMpiFileInfo (string mediaPlayerId) { try { mpi_file = new GKeyFile (); mpi_file.LoadFromDirs (String.Format ("{0}.mpi", mediaPlayerId), new string [] {"/usr/share/media-player-info", "/usr/local/share/media-player-info"}, null, Flags.None); } catch (GLib.GException) { Hyena.Log.WarningFormat ("Failed to load media-player-info file for {0}", mediaPlayerId); } LoadProperties (); } public string PlaylistPath { get; private set; } public string[] AudioFolders { get; private set; } public int FolderDepth { get; private set; } public string[] AccessProtocols { get; private set; } public string[] OutputFormats { get; private set; } public string[] InputFormats { get; private set; } public string[] PlaylistFormats { get; private set; } private void LoadProperties () { InitDefaults (); if (mpi_file == null) { return; } if (mpi_file.HasGroup (StorageGroup)) { if (mpi_file.HasKey (StorageGroup, "FolderDepth")) { FolderDepth = mpi_file.GetInteger (StorageGroup, "FolderDepth"); } if (mpi_file.HasKey (StorageGroup, "PlaylistPath")) { PlaylistPath = mpi_file.GetString (StorageGroup, "PlaylistPath"); } if (mpi_file.HasKey (StorageGroup, "AudioFolders")) { AudioFolders = mpi_file.GetStringList (StorageGroup, "AudioFolders"); } } if (mpi_file.HasGroup (MediaGroup)) { if (mpi_file.HasKey (MediaGroup, "InputFormats")) { InputFormats = mpi_file.GetStringList (MediaGroup, "InputFormats"); } if (mpi_file.HasKey (MediaGroup, "OutputFormats")) { OutputFormats = mpi_file.GetStringList (MediaGroup, "OutputFormats"); OutputFormats = OutputFormats[0].Split (';'); } } if (mpi_file.HasGroup (PlaylistGroup) && mpi_file.HasKey (PlaylistGroup, "Formats")) { PlaylistFormats = mpi_file.GetStringList (PlaylistGroup, "Formats") ?? new string [] {}; } if (mpi_file.HasGroup (DeviceGroup) && mpi_file.HasKey (DeviceGroup, "AccessProtocols")) { AccessProtocols = mpi_file.GetStringList (DeviceGroup, "AccessProtocols") ?? new string [] {}; } } private void InitDefaults () { FolderDepth = 0; PlaylistPath = ""; AudioFolders = new string[] {}; InputFormats = new string[] {}; OutputFormats = new string[] {}; PlaylistFormats = new string[] {}; AccessProtocols = new string[] {}; } } } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Globalization; using System.Linq; using Dbg = System.Management.Automation.Diagnostics; using System.Collections; using System.Reflection; namespace System.Management.Automation { /// <summary> /// This is used for automatic conversions to be performed in shell variables. /// </summary> internal sealed class ArgumentTypeConverterAttribute : ArgumentTransformationAttribute { /// <summary> /// This ctor form is used to initialize shell variables /// whose type is not permitted to change. /// </summary> /// <param name="types"></param> internal ArgumentTypeConverterAttribute(params Type[] types) { _convertTypes = types; } private Type[] _convertTypes; internal Type TargetType { get { return _convertTypes == null ? null : _convertTypes.LastOrDefault(); } } public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { return Transform(engineIntrinsics, inputData, false, false); } internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet) { if (_convertTypes == null) return inputData; object result = inputData; try { for (int i = 0; i < _convertTypes.Length; i++) { if (bindingParameters) { // We should not be doing a conversion here if [ref] is the last type. // When [ref] appears in an argument list, it is used for checking only. // No Conversion should be done. if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference))) { object temp; PSObject mshObject = result as PSObject; if (mshObject != null) temp = mshObject.BaseObject; else temp = result; PSReference reference = temp as PSReference; if (reference == null) { throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null, ExtendedTypeSystem.ReferenceTypeExpected); } } else { object temp; PSObject mshObject = result as PSObject; if (mshObject != null) temp = mshObject.BaseObject; else temp = result; // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference. PSReference reference = temp as PSReference; if (reference != null) { result = reference.Value; } if (bindingScriptCmdlet && _convertTypes[i] == typeof(string)) { // Don't allow conversion from array to string in script w/ cmdlet binding. Allow // the conversion for ordinary script parameter binding for V1 compatibility. temp = PSObject.Base(result); if (temp != null && temp.GetType().IsArray) { throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null, ExtendedTypeSystem.InvalidCastCannotRetrieveString); } } } } // BUGBUG // NTRAID#Windows Out of Band Releases - 930116 - 03/14/06 // handling special case for boolean, switchparameter and Nullable<bool> // These parameter types will not be converted if the incoming value types are not // one of the accepted categories - $true/$false or numbers (0 or otherwise) if (LanguagePrimitives.IsBoolOrSwitchParameterType(_convertTypes[i])) { CheckBoolValue(result, _convertTypes[i]); } if (bindingScriptCmdlet) { // Check for conversion to something like bool[] or ICollection<bool>, but only for cmdlet binding // to stay compatible with V1. ParameterCollectionTypeInformation collectionTypeInfo = new ParameterCollectionTypeInformation(_convertTypes[i]); if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection && LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType)) { IList currentValueAsIList = ParameterBinderBase.GetIList(result); if (currentValueAsIList != null) { foreach (object val in currentValueAsIList) { CheckBoolValue(val, collectionTypeInfo.ElementType); } } else { CheckBoolValue(result, collectionTypeInfo.ElementType); } } } result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture); // Do validation of invalid direct variable assignments which are allowed to // be used for parameters. // // Note - this is duplicated in ExecutionContext.cs as parameter binding for script cmdlets can avoid this code path. if ((!bindingScriptCmdlet) && (!bindingParameters)) { // ActionPreference of Suspend is not supported as a preference variable. We can only block "Suspend" // during variable assignment (here) - "Ignore" is blocked during variable retrieval. if (_convertTypes[i] == typeof(ActionPreference)) { ActionPreference resultPreference = (ActionPreference)result; if (resultPreference == ActionPreference.Suspend) { throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference); } } } } } catch (PSInvalidCastException e) { throw new ArgumentTransformationMetadataException(e.Message, e); } // Track the flow of untrusted object during the conversion when it's called directly from ParameterBinderBase. // When it's called from the override Transform method, the tracking is taken care of in the base type. if (bindingParameters || bindingScriptCmdlet) { ExecutionContext.PropagateInputSource(inputData, result, engineIntrinsics.SessionState.Internal.LanguageMode); } return result; } private static void CheckBoolValue(object value, Type boolType) { if (value != null) { Type resultType = value.GetType(); if (resultType == typeof(PSObject)) resultType = ((PSObject)value).BaseObject.GetType(); if (!(LanguagePrimitives.IsNumeric(resultType.GetTypeCode()) || LanguagePrimitives.IsBoolOrSwitchParameterType(resultType))) { ThrowPSInvalidBooleanArgumentCastException(resultType, boolType); } } else { bool isNullable = boolType.IsGenericType && boolType.GetGenericTypeDefinition() == typeof(Nullable<>); if (!isNullable && LanguagePrimitives.IsBooleanType(boolType)) { ThrowPSInvalidBooleanArgumentCastException(null, boolType); } } } internal static void ThrowPSInvalidBooleanArgumentCastException(Type resultType, Type convertType) { throw new PSInvalidCastException("InvalidCastExceptionUnsupportedParameterType", null, ExtendedTypeSystem.InvalidCastExceptionForBooleanArgumentValue, resultType, convertType); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using Web.Areas.HelpPage.Models; namespace Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; using Frapid.WebApi; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Kanban Details. /// </summary> [RoutePrefix("api/v1.0/config/kanban-detail")] public class KanbanDetailController : FrapidApiController { /// <summary> /// The KanbanDetail repository. /// </summary> private IKanbanDetailRepository KanbanDetailRepository; public KanbanDetailController() { } public KanbanDetailController(IKanbanDetailRepository repository) { this.KanbanDetailRepository = repository; } protected override void Initialize(HttpControllerContext context) { base.Initialize(context); if (this.KanbanDetailRepository == null) { this.KanbanDetailRepository = new Frapid.Config.DataAccess.KanbanDetail { _Catalog = this.MetaUser.Catalog, _LoginId = this.MetaUser.LoginId, _UserId = this.MetaUser.UserId }; } } /// <summary> /// Creates meta information of "kanban detail" entity. /// </summary> /// <returns>Returns the "kanban detail" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/config/kanban-detail/meta")] [RestAuthorize] public EntityView GetEntityView() { return new EntityView { PrimaryKey = "kanban_detail_id", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "kanban_detail_id", PropertyName = "KanbanDetailId", DataType = "long", DbDataType = "int8", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "kanban_id", PropertyName = "KanbanId", DataType = "long", DbDataType = "int8", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "rating", PropertyName = "Rating", DataType = "short", DbDataType = "int2", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "resource_id", PropertyName = "ResourceId", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 128 }, new EntityColumn { ColumnName = "audit_user_id", PropertyName = "AuditUserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "audit_ts", PropertyName = "AuditTs", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } /// <summary> /// Counts the number of kanban details. /// </summary> /// <returns>Returns the count of the kanban details.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/kanban-detail/count")] [RestAuthorize] public long Count() { try { return this.KanbanDetailRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns all collection of kanban detail. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/config/kanban-detail/all")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetAll() { try { return this.KanbanDetailRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of kanban detail for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/config/kanban-detail/export")] [RestAuthorize] public IEnumerable<dynamic> Export() { try { return this.KanbanDetailRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns an instance of kanban detail. /// </summary> /// <param name="kanbanDetailId">Enter KanbanDetailId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{kanbanDetailId}")] [Route("~/api/config/kanban-detail/{kanbanDetailId}")] [RestAuthorize] public Frapid.Config.Entities.KanbanDetail Get(long kanbanDetailId) { try { return this.KanbanDetailRepository.Get(kanbanDetailId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/config/kanban-detail/get")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.KanbanDetail> Get([FromUri] long[] kanbanDetailIds) { try { return this.KanbanDetailRepository.Get(kanbanDetailIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the first instance of kanban detail. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/config/kanban-detail/first")] [RestAuthorize] public Frapid.Config.Entities.KanbanDetail GetFirst() { try { return this.KanbanDetailRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the previous instance of kanban detail. /// </summary> /// <param name="kanbanDetailId">Enter KanbanDetailId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{kanbanDetailId}")] [Route("~/api/config/kanban-detail/previous/{kanbanDetailId}")] [RestAuthorize] public Frapid.Config.Entities.KanbanDetail GetPrevious(long kanbanDetailId) { try { return this.KanbanDetailRepository.GetPrevious(kanbanDetailId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the next instance of kanban detail. /// </summary> /// <param name="kanbanDetailId">Enter KanbanDetailId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{kanbanDetailId}")] [Route("~/api/config/kanban-detail/next/{kanbanDetailId}")] [RestAuthorize] public Frapid.Config.Entities.KanbanDetail GetNext(long kanbanDetailId) { try { return this.KanbanDetailRepository.GetNext(kanbanDetailId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the last instance of kanban detail. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/config/kanban-detail/last")] [RestAuthorize] public Frapid.Config.Entities.KanbanDetail GetLast() { try { return this.KanbanDetailRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 kanban details on each page, sorted by the property KanbanDetailId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/kanban-detail")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetPaginatedResult() { try { return this.KanbanDetailRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 kanban details on each page, sorted by the property KanbanDetailId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/kanban-detail/page/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetPaginatedResult(long pageNumber) { try { return this.KanbanDetailRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of kanban details using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered kanban details.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/kanban-detail/count-where")] [RestAuthorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.KanbanDetailRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 kanban details on each page, sorted by the property KanbanDetailId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/kanban-detail/get-where/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.KanbanDetailRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of kanban details using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered kanban details.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/kanban-detail/count-filtered/{filterName}")] [RestAuthorize] public long CountFiltered(string filterName) { try { return this.KanbanDetailRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 kanban details on each page, sorted by the property KanbanDetailId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/kanban-detail/get-filtered/{pageNumber}/{filterName}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.KanbanDetail> GetFiltered(long pageNumber, string filterName) { try { return this.KanbanDetailRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of kanban details. /// </summary> /// <returns>Returns an enumerable key/value collection of kanban details.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/config/kanban-detail/display-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { try { return this.KanbanDetailRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for kanban details. /// </summary> /// <returns>Returns an enumerable custom field collection of kanban details.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/config/kanban-detail/custom-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields() { try { return this.KanbanDetailRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for kanban details. /// </summary> /// <returns>Returns an enumerable custom field collection of kanban details.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/config/kanban-detail/custom-fields/{resourceId}")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { try { return this.KanbanDetailRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds or edits your instance of KanbanDetail class. /// </summary> /// <param name="kanbanDetail">Your instance of kanban details class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/config/kanban-detail/add-or-edit")] [RestAuthorize] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic kanbanDetail = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer()); if (kanbanDetail == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { return this.KanbanDetailRepository.AddOrEdit(kanbanDetail, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds your instance of KanbanDetail class. /// </summary> /// <param name="kanbanDetail">Your instance of kanban details class to add.</param> [AcceptVerbs("POST")] [Route("add/{kanbanDetail}")] [Route("~/api/config/kanban-detail/add/{kanbanDetail}")] [RestAuthorize] public void Add(Frapid.Config.Entities.KanbanDetail kanbanDetail) { if (kanbanDetail == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.KanbanDetailRepository.Add(kanbanDetail); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Edits existing record with your instance of KanbanDetail class. /// </summary> /// <param name="kanbanDetail">Your instance of KanbanDetail class to edit.</param> /// <param name="kanbanDetailId">Enter the value for KanbanDetailId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{kanbanDetailId}")] [Route("~/api/config/kanban-detail/edit/{kanbanDetailId}")] [RestAuthorize] public void Edit(long kanbanDetailId, [FromBody] Frapid.Config.Entities.KanbanDetail kanbanDetail) { if (kanbanDetail == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.KanbanDetailRepository.Update(kanbanDetail, kanbanDetailId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of KanbanDetail class. /// </summary> /// <param name="collection">Your collection of KanbanDetail class to bulk import.</param> /// <returns>Returns list of imported kanbanDetailIds.</returns> /// <exception cref="DataAccessException">Thrown when your any KanbanDetail class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/config/kanban-detail/bulk-import")] [RestAuthorize] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> kanbanDetailCollection = this.ParseCollection(collection); if (kanbanDetailCollection == null || kanbanDetailCollection.Count.Equals(0)) { return null; } try { return this.KanbanDetailRepository.BulkImport(kanbanDetailCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Deletes an existing instance of KanbanDetail class via KanbanDetailId. /// </summary> /// <param name="kanbanDetailId">Enter the value for KanbanDetailId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{kanbanDetailId}")] [Route("~/api/config/kanban-detail/delete/{kanbanDetailId}")] [RestAuthorize] public void Delete(long kanbanDetailId) { try { this.KanbanDetailRepository.Delete(kanbanDetailId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get-by-resources")] [Route("~/api/config/kanban-detail/get-by-resources")] public IEnumerable<Frapid.Config.Entities.KanbanDetail> Get([FromUri] long[] kanbanIds, [FromUri] object[] resourceIds) { try { return this.KanbanDetailRepository.Get(kanbanIds, resourceIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } } }