context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using MS.Utility;
using System;
using System.Windows;
using System.Windows.Media;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using MS.Internal.Ink;
using MS.Internal;
using MS.Internal.PresentationCore;
namespace System.Windows.Ink
{
/// <summary>
/// The Renderer class is used to render a stroke collection.
/// This class listens to stroke added and removed events on the
/// stroke collection and updates the internal visual tree.
/// It also listens to the Invalidated event on Stroke (fired when
/// DrawingAttributes changes, packet data changes, DrawingAttributes
/// replaced, as well as Stroke developer calls Stroke.OnInvalidated)
/// and updates the visual state as necessary.
/// </summary>
///
[FriendAccessAllowed] // Built into Core, also used by Framework.
internal class Renderer
{
#region StrokeVisual
/// <summary>
/// A retained visual for rendering a single stroke in a stroke collection view
/// </summary>
private class StrokeVisual : System.Windows.Media.DrawingVisual
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="stroke">a stroke to render into this visual</param>
/// <param name="renderer">a renderer associated to this visual</param>
internal StrokeVisual(Stroke stroke, Renderer renderer) : base()
{
Debug.Assert(renderer != null);
if (stroke == null)
{
throw new System.ArgumentNullException("stroke");
}
_stroke = stroke;
_renderer = renderer;
// The original value of the color and IsHighlighter are cached so
// when Stroke.Invalidated is fired, Renderer knows whether re-arranging
// the visual tree is needed.
_cachedColor = stroke.DrawingAttributes.Color;
_cachedIsHighlighter = stroke.DrawingAttributes.IsHighlighter;
// Update the visual contents
Update();
}
/// <summary>
/// The Stroke rendedered into this visual.
/// </summary>
internal Stroke Stroke
{
get { return _stroke; }
}
/// <summary>
/// Updates the contents of the visual.
/// </summary>
internal void Update()
{
using (DrawingContext drawingContext = RenderOpen())
{
bool highContrast = _renderer.IsHighContrast();
if (highContrast == true && _stroke.DrawingAttributes.IsHighlighter)
{
// we don't render highlighters in high contrast
return;
}
DrawingAttributes da;
if (highContrast)
{
da = _stroke.DrawingAttributes.Clone();
da.Color = _renderer.GetHighContrastColor();
}
else if (_stroke.DrawingAttributes.IsHighlighter == true)
{
// Get the drawing attributes to use for a highlighter stroke. This can be a copied DA with color.A
// overridden if color.A != 255.
da = StrokeRenderer.GetHighlighterAttributes(_stroke, _stroke.DrawingAttributes);
}
else
{
// Otherwise, usethe DA on this stroke
da = _stroke.DrawingAttributes;
}
// Draw selected stroke as hollow
_stroke.DrawInternal (drawingContext, da, _stroke.IsSelected );
}
}
/// <summary>
/// StrokeVisual should not be hittestable as it interferes with event routing
/// </summary>
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParams)
{
return null;
}
/// <summary>
/// The previous value of IsHighlighter
/// </summary>
internal bool CachedIsHighlighter
{
get {return _cachedIsHighlighter;}
set {_cachedIsHighlighter = value;}
}
/// <summary>
/// The previous value of Color
/// </summary>
internal Color CachedColor
{
get {return _cachedColor;}
set {_cachedColor = value;}
}
private Stroke _stroke;
private bool _cachedIsHighlighter;
private Color _cachedColor;
private Renderer _renderer;
}
/// <summary>
/// Private helper that helps reverse map the highlighter dictionary
/// </summary>
private class HighlighterContainerVisual : ContainerVisual
{
internal HighlighterContainerVisual(Color color)
{
_color = color;
}
/// <summary>
/// The Color of the strokes in this highlighter container visual
/// </summary>
internal Color Color
{
get { return _color; }
}
private Color _color;
}
#endregion
#region Internal interface
/// <summary>
/// Public Constructor
/// </summary>
internal Renderer()
{
// Initialize the data members.
// We intentionally don't use lazy initialization for the core members to avoid
// hidden bug situations when one thing has been created while another not.
// If the user is looking for lazy initialization, she should do that on her
// own and create Renderer only when there's a need for it.
// Create visuals that'll be the containers for all other visuals
// created by the Renderer. This visuals are created once and are
// not supposed to be replaced nor destroyed while the Renderer is alive.
_rootVisual = new ContainerVisual();
_highlightersRoot = new ContainerVisual();
_regularInkVisuals = new ContainerVisual();
_incrementalRenderingVisuals = new ContainerVisual();
// Highlighters go to the bottom, then regular ink, and regular
// ink' incremental rendering in on top.
VisualCollection rootChildren = _rootVisual.Children;
rootChildren.Add(_highlightersRoot);
rootChildren.Add(_regularInkVisuals);
rootChildren.Add(_incrementalRenderingVisuals);
// Set the default value of highcontrast to be false.
_highContrast = false;
// Create a stroke-visual dictionary
_visuals = new Dictionary<Stroke, StrokeVisual>();
}
/// <summary>
/// Returns a reference to a visual tree that can be used to render the ink.
/// This property may be either a single visual or a container visual with
/// children. The element uses this visual as a child visual and arranges
/// it with respects to the other siblings.
/// Note: No visuals are actually generated until the application gets
/// this property for the first time. If no strokes are set then an empty
/// visual is returned.
/// </summary>
internal Visual RootVisual { get { return _rootVisual; } }
/// <summary>
/// Set the strokes property to the collection of strokes to be rendered.
/// The Renderer will then listen to changes to the StrokeCollection
/// and update its state to reflect the changes.
/// </summary>
internal StrokeCollection Strokes
{
get
{
// We should never return a null value.
if ( _strokes == null )
{
_strokes = new StrokeCollection();
// Start listening on events from the stroke collection.
_strokes.StrokesChangedInternal += new StrokeCollectionChangedEventHandler(OnStrokesChanged);
}
return _strokes;
}
set
{
if (value == null)
{
throw new System.ArgumentNullException("value");
}
if (value == _strokes)
{
return;
}
// Detach the current stroke collection
if (null != _strokes)
{
// Stop listening on events from the stroke collection.
_strokes.StrokesChangedInternal -= new StrokeCollectionChangedEventHandler(OnStrokesChanged);
foreach (StrokeVisual visual in _visuals.Values)
{
StopListeningOnStrokeEvents(visual.Stroke);
// Detach the visual from the tree
DetachVisual(visual);
}
_visuals.Clear();
}
// Set it.
_strokes = value;
// Create visuals
foreach (Stroke stroke in _strokes)
{
// Create a visual per stroke
StrokeVisual visual = new StrokeVisual(stroke, this);
// Store the stroke-visual pair in the dictionary
_visuals.Add(stroke, visual);
StartListeningOnStrokeEvents(visual.Stroke);
// Attach it to the visual tree
AttachVisual(visual, true/*buildingStrokeCollection*/);
}
// Start listening on events from the stroke collection.
_strokes.StrokesChangedInternal += new StrokeCollectionChangedEventHandler(OnStrokesChanged);
}
}
/// <summary>
/// User supposed to use this method to attach IncrementalRenderer's root visual
/// to the visual tree of a stroke collection view.
/// </summary>
/// <param name="visual">visual to attach</param>
/// <param name="drawingAttributes">drawing attributes that used in the incremental rendering</param>
internal void AttachIncrementalRendering(Visual visual, DrawingAttributes drawingAttributes)
{
// Check the input parameters
if (visual == null)
{
throw new System.ArgumentNullException("visual");
}
if (drawingAttributes == null)
{
throw new System.ArgumentNullException("drawingAttributes");
}
//harden against eaten exceptions
bool exceptionRaised = false;
// Verify that the visual hasn't been attached already
if (_attachedVisuals != null)
{
foreach(Visual alreadyAttachedVisual in _attachedVisuals)
{
if (visual == alreadyAttachedVisual)
{
exceptionRaised = true;
throw new System.InvalidOperationException(SR.Get(SRID.CannotAttachVisualTwice));
}
}
}
else
{
// Create the list to register attached visuals in
_attachedVisuals = new List<Visual>();
}
if (!exceptionRaised)
{
// The position of the visual in the tree depends on the drawingAttributes
// Find the appropriate parent visual to attach this visual to.
ContainerVisual parent = drawingAttributes.IsHighlighter ? GetContainerVisual(drawingAttributes) : _incrementalRenderingVisuals;
// Attach the visual to the tree
parent.Children.Add(visual);
// Put the visual into the list of visuals attached via this method
_attachedVisuals.Add(visual);
}
}
/// <summary>
/// Detaches a visual previously attached via AttachIncrementalRendering
/// </summary>
/// <param name="visual">the visual to detach</param>
internal void DetachIncrementalRendering(Visual visual)
{
if (visual == null)
{
throw new System.ArgumentNullException("visual");
}
// Remove the visual in the list of attached via AttachIncrementalRendering
if ((_attachedVisuals == null) || (_attachedVisuals.Remove(visual) == false))
{
throw new System.InvalidOperationException(SR.Get(SRID.VisualCannotBeDetached));
}
// Detach it from the tree
DetachVisual(visual);
}
/// <summary>
/// Internal helper used to indicate if a visual was previously attached
/// via a call to AttachIncrementalRendering
/// </summary>
internal bool ContainsAttachedIncrementalRenderingVisual(Visual visual)
{
if (visual == null || _attachedVisuals == null)
{
return false;
}
return _attachedVisuals.Contains(visual);
}
/// <summary>
/// Internal helper used to determine if a visual is in the right spot in the visual tree
/// </summary>
internal bool AttachedVisualIsPositionedCorrectly(Visual visual, DrawingAttributes drawingAttributes)
{
if (visual == null || drawingAttributes == null || _attachedVisuals == null || !_attachedVisuals.Contains(visual))
{
return false;
}
ContainerVisual correctParent
= drawingAttributes.IsHighlighter ? GetContainerVisual(drawingAttributes) : _incrementalRenderingVisuals;
ContainerVisual currentParent
= VisualTreeHelper.GetParent(visual) as ContainerVisual;
if (currentParent == null || correctParent != currentParent)
{
return false;
}
return true;
}
/// <summary>
/// TurnOnHighContrast turns on the HighContrast rendering mode
/// </summary>
/// <param name="strokeColor">The stroke color under high contrast</param>
internal void TurnHighContrastOn(Color strokeColor)
{
if ( !_highContrast || strokeColor != _highContrastColor )
{
_highContrast = true;
_highContrastColor = strokeColor;
UpdateStrokeVisuals();
}
}
/// <summary>
/// ResetHighContrast turns off the HighContrast mode
/// </summary>
internal void TurnHighContrastOff()
{
if ( _highContrast )
{
_highContrast = false;
UpdateStrokeVisuals();
}
}
/// <summary>
/// Indicates whether the renderer is in high contrast mode.
/// </summary>
/// <returns></returns>
internal bool IsHighContrast()
{
return _highContrast;
}
/// <summary>
/// returns the stroke color for the high contrast rendering.
/// </summary>
/// <returns></returns>
public Color GetHighContrastColor()
{
return _highContrastColor;
}
#endregion
#region Event handlers
/// <summary>
/// StrokeCollectionChanged event handler
/// </summary>
private void OnStrokesChanged(object sender, StrokeCollectionChangedEventArgs eventArgs)
{
System.Diagnostics.Debug.Assert(sender == _strokes);
// Read the args
StrokeCollection added = eventArgs.Added;
StrokeCollection removed = eventArgs.Removed;
// Add new strokes
foreach (Stroke stroke in added)
{
// Verify that it's not a dupe
if (_visuals.ContainsKey(stroke))
{
throw new System.ArgumentException(SR.Get(SRID.DuplicateStrokeAdded));
}
// Create a visual for the new stroke and add it to the dictionary
StrokeVisual visual = new StrokeVisual(stroke, this);
_visuals.Add(stroke, visual);
// Start listening on the stroke events
StartListeningOnStrokeEvents(visual.Stroke);
// Attach it to the visual tree
AttachVisual(visual, false/*buildingStrokeCollection*/);
}
// Deal with removed strokes first
foreach (Stroke stroke in removed)
{
// Verify that the event is in sync with the view
StrokeVisual visual = null;
if (_visuals.TryGetValue(stroke, out visual))
{
// get rid of both the visual and the stroke
DetachVisual(visual);
StopListeningOnStrokeEvents(visual.Stroke);
_visuals.Remove(stroke);
}
else
{
throw new System.ArgumentException(SR.Get(SRID.UnknownStroke3));
}
}
}
/// <summary>
/// Stroke Invalidated event handler
/// </summary>
private void OnStrokeInvalidated(object sender, EventArgs eventArgs)
{
System.Diagnostics.Debug.Assert(_strokes.IndexOf(sender as Stroke) != -1);
// Find the visual associated with the changed stroke.
StrokeVisual visual;
Stroke stroke = (Stroke)sender;
if (_visuals.TryGetValue(stroke, out visual) == false)
{
throw new System.ArgumentException(SR.Get(SRID.UnknownStroke1));
}
// The original value of IsHighligher and Color are cached in StrokeVisual.
// if (IsHighlighter value changed or (IsHighlighter == true and not changed and color changed)
// detach and re-attach the corresponding visual;
// otherwise Invalidate the corresponding StrokeVisual
if (visual.CachedIsHighlighter != stroke.DrawingAttributes.IsHighlighter ||
(stroke.DrawingAttributes.IsHighlighter &&
StrokeRenderer.GetHighlighterColor(visual.CachedColor) != StrokeRenderer.GetHighlighterColor(stroke.DrawingAttributes.Color)))
{
// The change requires reparenting the visual in the tree.
DetachVisual(visual);
AttachVisual(visual, false/*buildingStrokeCollection*/);
// Update the cached values
visual.CachedIsHighlighter = stroke.DrawingAttributes.IsHighlighter;
visual.CachedColor = stroke.DrawingAttributes.Color;
}
// Update the visual.
visual.Update();
}
#endregion
#region Helper methods
/// <summary>
/// Update the stroke visuals
/// </summary>
private void UpdateStrokeVisuals()
{
foreach ( StrokeVisual strokeVisual in _visuals.Values )
{
strokeVisual.Update();
}
}
/// <summary>
/// Attaches a stroke visual to the tree based on the stroke's
/// drawing attributes and/or its z-order (index in the collection).
/// </summary>
private void AttachVisual(StrokeVisual visual, bool buildingStrokeCollection)
{
System.Diagnostics.Debug.Assert(_strokes != null);
if (visual.Stroke.DrawingAttributes.IsHighlighter)
{
// Find or create a container visual for highlighter strokes of the color
ContainerVisual parent = GetContainerVisual(visual.Stroke.DrawingAttributes);
Debug.Assert(visual is StrokeVisual);
//insert StrokeVisuals under any non-StrokeVisuals used for dynamic inking
int i = 0;
for (int j = parent.Children.Count - 1; j >= 0; j--)
{
if (parent.Children[j] is StrokeVisual)
{
i = j + 1;
break;
}
}
parent.Children.Insert(i, visual);
}
else
{
// For regular ink we have to respect the z-order of the strokes.
// The implementation below is not optimal in a generic case, but the
// most simple and should work ok in most common scenarios.
// Find the nearest non-highlighter stroke with a lower z-order
// and insert the new visual right next to the visual of that stroke.
StrokeVisual precedingVisual = null;
int i = 0;
if (buildingStrokeCollection)
{
Stroke visualStroke = visual.Stroke;
//we're building up a stroke collection, no need to start at IndexOf,
i = Math.Min(_visuals.Count, _strokes.Count); //not -1, we're about to decrement
while (--i >= 0)
{
if (object.ReferenceEquals(_strokes[i], visualStroke))
{
break;
}
}
}
else
{
i = _strokes.IndexOf(visual.Stroke);
}
while (--i >= 0)
{
Stroke stroke = _strokes[i];
if ((stroke.DrawingAttributes.IsHighlighter == false)
&& (_visuals.TryGetValue(stroke, out precedingVisual) == true)
&& (VisualTreeHelper.GetParent(precedingVisual) != null))
{
VisualCollection children = ((ContainerVisual)(VisualTreeHelper.GetParent(precedingVisual))).Children;
int index = children.IndexOf(precedingVisual);
children.Insert(index + 1, visual);
break;
}
}
// If found no non-highlighter strokes with a lower z-order, insert
// the stroke at the very bottom of the regular ink visual tree.
if (i < 0)
{
ContainerVisual parent = GetContainerVisual(visual.Stroke.DrawingAttributes);
parent.Children.Insert(0, visual);
}
}
}
/// <summary>
/// Detaches a visual from the tree, also removes highligher parents if empty
/// when true is passed
/// </summary>
private void DetachVisual(Visual visual)
{
ContainerVisual parent = (ContainerVisual)(VisualTreeHelper.GetParent(visual));
if (parent != null)
{
VisualCollection children = parent.Children;
children.Remove(visual);
// If the parent is a childless highlighter, detach it too.
HighlighterContainerVisual hcVisual = parent as HighlighterContainerVisual;
if (hcVisual != null &&
hcVisual.Children.Count == 0 &&
_highlighters != null &&
_highlighters.ContainsValue(hcVisual))
{
DetachVisual(hcVisual);
_highlighters.Remove(hcVisual.Color);
}
}
}
/// <summary>
/// Attaches event handlers to stroke events
/// </summary>
private void StartListeningOnStrokeEvents(Stroke stroke)
{
System.Diagnostics.Debug.Assert(stroke != null);
stroke.Invalidated += new EventHandler(OnStrokeInvalidated);
}
/// <summary>
/// Detaches event handlers from stroke
/// </summary>
private void StopListeningOnStrokeEvents(Stroke stroke)
{
System.Diagnostics.Debug.Assert(stroke != null);
stroke.Invalidated -= new EventHandler(OnStrokeInvalidated);
}
/// <summary>
/// Finds a container for a new visual based on the drawing attributes
/// of the stroke rendered into that visual.
/// </summary>
/// <param name="drawingAttributes">drawing attributes</param>
/// <returns>visual</returns>
private ContainerVisual GetContainerVisual(DrawingAttributes drawingAttributes)
{
System.Diagnostics.Debug.Assert(drawingAttributes != null);
HighlighterContainerVisual hcVisual;
if (drawingAttributes.IsHighlighter)
{
// For a highlighter stroke, the color.A is neglected.
Color color = StrokeRenderer.GetHighlighterColor(drawingAttributes.Color);
if ((_highlighters == null) || (_highlighters.TryGetValue(color, out hcVisual) == false))
{
if (_highlighters == null)
{
_highlighters = new Dictionary<Color, HighlighterContainerVisual>();
}
hcVisual = new HighlighterContainerVisual(color);
hcVisual.Opacity = StrokeRenderer.HighlighterOpacity;
_highlightersRoot.Children.Add(hcVisual);
_highlighters.Add(color, hcVisual);
}
else if (VisualTreeHelper.GetParent(hcVisual) == null)
{
_highlightersRoot.Children.Add(hcVisual);
}
return hcVisual;
}
else
{
return _regularInkVisuals;
}
}
#endregion
#region Fields
// The renderer's top level container visuals
private ContainerVisual _rootVisual;
private ContainerVisual _highlightersRoot;
private ContainerVisual _incrementalRenderingVisuals;
private ContainerVisual _regularInkVisuals;
// Stroke-to-visual map
private Dictionary<Stroke, StrokeVisual> _visuals;
// Color-to-visual map for highlighter ink container visuals
private Dictionary<Color, HighlighterContainerVisual> _highlighters = null;
// Collection of strokes this Renderer renders
private StrokeCollection _strokes = null;
// List of visuals attached via AttachIncrementalRendering
private List<Visual> _attachedVisuals = null;
// Whhen true, will render in high contrast mode
private bool _highContrast;
private Color _highContrastColor = Colors.White;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
//#define VERBOSE
namespace Assets.Plugins.Editor.JetBrains
{
[InitializeOnLoad]
public static class RiderPlugin
{
private static readonly string SlnFile;
private static string DefaultApp
{
get { return EditorPrefs.GetString("kScriptsDefaultApp"); }
}
public static bool TargetFrameworkVersion45
{
get { return EditorPrefs.GetBool("Rider_TargetFrameworkVersion45", true); }
set { EditorPrefs.SetBool("Rider_TargetFrameworkVersion45", value); }
}
internal static bool Enabled
{
get
{
if (string.IsNullOrEmpty(DefaultApp))
return false;
return DefaultApp.ToLower().Contains("rider"); // seems like .app doesn't exist as file
}
}
static RiderPlugin()
{
if (Enabled)
{
var riderFileInfo = new FileInfo(DefaultApp);
var newPath = riderFileInfo.FullName;
// try to search the new version
switch (riderFileInfo.Extension)
{
/*
Unity itself transforms lnk to exe
case ".lnk":
{
if (riderFileInfo.Directory != null && riderFileInfo.Directory.Exists)
{
var possibleNew = riderFileInfo.Directory.GetFiles("*ider*.lnk");
if (possibleNew.Length > 0)
newPath = possibleNew.OrderBy(a => a.LastWriteTime).Last().FullName;
}
break;
}*/
case ".exe":
{
var possibleNew =
riderFileInfo.Directory.Parent.Parent.GetDirectories("*ider*")
.SelectMany(a => a.GetDirectories("bin"))
.SelectMany(a => a.GetFiles(riderFileInfo.Name))
.ToArray();
if (possibleNew.Length > 0)
newPath = possibleNew.OrderBy(a => a.LastWriteTime).Last().FullName;
break;
}
default:
{
break;
}
}
if (newPath != riderFileInfo.FullName)
{
Log(string.Format("Update {0} to {1}", riderFileInfo.FullName, newPath));
EditorPrefs.SetString("kScriptsDefaultApp", newPath);
}
}
var projectDirectory = Directory.GetParent(Application.dataPath).FullName;
var projectName = Path.GetFileName(projectDirectory);
SlnFile = Path.Combine(projectDirectory, string.Format("{0}.sln", projectName));
UpdateUnitySettings(SlnFile);
}
/// <summary>
/// Helps to open xml and txt files at least on Windows
/// </summary>
/// <param name="slnFile"></param>
private static void UpdateUnitySettings(string slnFile)
{
try
{
EditorPrefs.SetString("kScriptEditorArgs",
string.Format("{0}{1}{0} {0}$(File){0}", "\"", slnFile));
}
catch (Exception e)
{
Log("Exception on updating kScriptEditorArgs: " + e.Message);
}
}
/// <summary>
/// Asset Open Callback (from Unity)
/// </summary>
/// <remarks>
/// Called when Unity is about to open an asset.
/// </remarks>
[UnityEditor.Callbacks.OnOpenAssetAttribute()]
static bool OnOpenedAsset(int instanceID, int line)
{
var riderFileInfo = new FileInfo(DefaultApp);
if (Enabled && (riderFileInfo.Exists || riderFileInfo.Extension == ".app"))
{
string appPath = Path.GetDirectoryName(Application.dataPath);
// determine asset that has been double clicked in the project view
var selected = EditorUtility.InstanceIDToObject(instanceID);
if (selected.GetType().ToString() == "UnityEditor.MonoScript" ||
selected.GetType().ToString() == "UnityEngine.Shader")
{
var assetFilePath = Path.Combine(appPath, AssetDatabase.GetAssetPath(selected));
var args = string.Format("{0}{1}{0} -l {2} {0}{3}{0}", "\"", SlnFile, line, assetFilePath);
CallRider(riderFileInfo.FullName, args);
return true;
}
}
return false;
}
private static void CallRider(string riderPath, string args)
{
var proc = new Process();
if (new FileInfo(riderPath).Extension == ".app")
{
proc.StartInfo.FileName = "open";
proc.StartInfo.Arguments = string.Format("-n {0}{1}{0} --args {2}", "\"", "/" + riderPath, args);
Log(proc.StartInfo.FileName + " " + proc.StartInfo.Arguments);
}
else
{
proc.StartInfo.FileName = riderPath;
proc.StartInfo.Arguments = args;
Log("\"" + proc.StartInfo.FileName + "\"" + " " + proc.StartInfo.Arguments);
}
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
if (new FileInfo(riderPath).Extension == ".exe")
{
try
{
ActivateWindow();
}
catch (Exception e)
{
Log("Exception on ActivateWindow: " + e);
}
}
}
private static void ActivateWindow()
{
var process = Process.GetProcesses().FirstOrDefault(p =>
{
string processName;
try
{
processName = p.ProcessName;
// some processes like kaspersky antivirus throw exception on attempt to get ProcessName
}
catch (Exception)
{
return false;
}
return !p.HasExited && processName.Contains("Rider");
});
if (process != null)
{
// Collect top level windows
var topLevelWindows = User32Dll.GetTopLevelWindowHandles();
// Get process main window title
var windowHandle =
topLevelWindows.FirstOrDefault(hwnd => User32Dll.GetWindowProcessId(hwnd) == process.Id);
if (windowHandle != IntPtr.Zero)
User32Dll.SetForegroundWindow(windowHandle);
}
}
[MenuItem("Assets/Open C# Project in Rider", false, 1000)]
static void MenuOpenProject()
{
// Force the project files to be sync
SyncSolution();
// Load Project
CallRider(new FileInfo(DefaultApp).FullName, string.Format("{0}{1}{0}", "\"", SlnFile));
}
[MenuItem("Assets/Open C# Project in Rider", true, 1000)]
static bool ValidateMenuOpenProject()
{
return Enabled;
}
/// <summary>
/// Force Unity To Write Project File
/// </summary>
private static void SyncSolution()
{
System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor");
System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
SyncSolution.Invoke(null, null);
}
public static void Log(object message)
{
#if VERBOSE
Debug.Log("[Rider] " + message);
#endif
}
/// <summary>
/// JetBrains Rider Integration Preferences Item
/// </summary>
/// <remarks>
/// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off
/// </remarks>
[PreferenceItem("Rider")]
static void RiderPreferencesItem()
{
EditorGUILayout.BeginVertical();
var url = "https://github.com/JetBrains/Unity3dRider";
if (GUILayout.Button(url))
{
Application.OpenURL(url);
}
EditorGUI.BeginChangeCheck();
var help = @"For now target 4.5 is strongly recommended.
- Without 4.5:
- Rider will fail to resolve System.Linq on Mac/Linux
- Rider will fail to resolve Firebase Analytics.
- With 4.5 Rider will show ambiguos references in UniRx.
All thouse problems will go away after Unity upgrades to mono4.";
TargetFrameworkVersion45 =
EditorGUILayout.Toggle(
new GUIContent("TargetFrameworkVersion 4.5",
help), TargetFrameworkVersion45);
EditorGUILayout.HelpBox(help, MessageType.None);
EditorGUI.EndChangeCheck();
}
static class User32Dll
{
/// <summary>
/// Gets the ID of the process that owns the window.
/// Note that creating a <see cref="Process"/> wrapper for that is very expensive because it causes an enumeration of all the system processes to happen.
/// </summary>
public static int GetWindowProcessId(IntPtr hwnd)
{
uint dwProcessId;
GetWindowThreadProcessId(hwnd, out dwProcessId);
return unchecked((int) dwProcessId);
}
/// <summary>
/// Lists the handles of all the top-level windows currently available in the system.
/// </summary>
public static List<IntPtr> GetTopLevelWindowHandles()
{
var retval = new List<IntPtr>();
EnumWindowsProc callback = (hwnd, param) =>
{
retval.Add(hwnd);
return 1;
};
EnumWindows(Marshal.GetFunctionPointerForDelegate(callback), IntPtr.Zero);
GC.KeepAlive(callback);
return retval;
}
public delegate Int32 EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true,
ExactSpelling = true)]
public static extern Int32 EnumWindows(IntPtr lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true,
ExactSpelling = true)]
public static extern Int32 SetForegroundWindow(IntPtr hWnd);
}
}
}
// Developed using JetBrains Rider =)
| |
// Copyright 2008 Adrian Akison
// Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx
using System.Collections;
using System.Collections.Generic;
namespace Facet.Combinatorics
{
/// <summary>
/// Combinations defines a meta-collection, typically a list of lists, of all possible
/// subsets of a particular size from the set of values. This list is enumerable and
/// allows the scanning of all possible combinations using a simple foreach() loop.
/// Within the returned set, there is no prescribed order. This follows the mathematical
/// concept of choose. For example, put 10 dominoes in a hat and pick 5. The number of possible
/// combinations is defined as "10 choose 5", which is calculated as (10!) / ((10 - 5)! * 5!).
/// </summary>
/// <remarks>
/// The MetaCollectionType parameter of the constructor allows for the creation of
/// two types of sets, those with and without repetition in the output set when
/// presented with repetition in the input set.
/// When given a input collect {A B C} and lower index of 2, the following sets are generated:
/// MetaCollectionType.WithRepetition =>
/// {A A}, {A B}, {A C}, {B B}, {B C}, {C C}
/// MetaCollectionType.WithoutRepetition =>
/// {A B}, {A C}, {B C}
/// Input sets with multiple equal values will generate redundant combinations in proprotion
/// to the likelyhood of outcome. For example, {A A B B} and a lower index of 3 will generate:
/// {A A B} {A A B} {A B B} {A B B}
/// </remarks>
/// <typeparam name="T">The type of the values within the list.</typeparam>
public class Combinations<T> : IMetaCollection<T>
{
#region Heavy Lifting Members
/// <summary>
/// Initialize the combinations by settings a copy of the values from the
/// </summary>
/// <param name="values">List of values to select combinations from.</param>
/// <param name="lowerIndex">The size of each combination set to return.</param>
/// <param name="type">The type of Combinations set to generate.</param>
/// <remarks>
/// Copies the array and parameters and then creates a map of booleans that will
/// be used by a permutations object to refence the subset. This map is slightly
/// different based on whether the type is with or without repetition.
/// When the type is WithoutRepetition, then a map of upper index elements is
/// created with lower index false's.
/// E.g. 8 choose 3 generates:
/// Map: {1 1 1 1 1 0 0 0}
/// Note: For sorting reasons, false denotes inclusion in output.
/// When the type is WithRepetition, then a map of upper index - 1 + lower index
/// elements is created with the falses indicating that the 'current' element should
/// be included and the trues meaning to advance the 'current' element by one.
/// E.g. 8 choose 3 generates:
/// Map: {1 1 1 1 1 1 1 1 0 0 0} (7 trues, 3 falses).
/// </remarks>
private void Initialize(IList<T> values, int lowerIndex, GenerateOption type)
{
myMetaCollectionType = type;
myLowerIndex = lowerIndex;
myValues = new List<T>();
myValues.AddRange(values);
var myMap = new List<bool>();
if (type == GenerateOption.WithoutRepetition)
{
for (var i = 0; i < myValues.Count; ++i)
{
if (i >= myValues.Count - myLowerIndex)
{
myMap.Add(false);
}
else
{
myMap.Add(true);
}
}
}
else
{
for (var i = 0; i < values.Count - 1; ++i)
{
myMap.Add(true);
}
for (var i = 0; i < myLowerIndex; ++i)
{
myMap.Add(false);
}
}
myPermutations = new Permutations<bool>(myMap);
}
#endregion
#region Enumerator Inner Class
/// <summary>
/// The enumerator that enumerates each meta-collection of the enclosing Combinations class.
/// </summary>
public class Enumerator : IEnumerator<IList<T>>
{
#region Constructors
/// <summary>
/// Construct a enumerator with the parent object.
/// </summary>
/// <param name="source">The source combinations object.</param>
public Enumerator(Combinations<T> source)
{
myParent = source;
myPermutationsEnumerator = (Permutations<bool>.Enumerator) myParent.myPermutations.GetEnumerator();
}
#endregion
#region Heavy Lifting Members
/// <summary>
/// The only complex function of this entire wrapper, ComputeCurrent() creates
/// a list of original values from the bool permutation provided.
/// The exception for accessing current (InvalidOperationException) is generated
/// by the call to .Current on the underlying enumeration.
/// </summary>
/// <remarks>
/// To compute the current list of values, the underlying permutation object
/// which moves with this enumerator, is scanned differently based on the type.
/// The items have only two values, true and false, which have different meanings:
/// For type WithoutRepetition, the output is a straightforward subset of the input array.
/// E.g. 6 choose 3 without repetition
/// Input array: {A B C D E F}
/// Permutations: {0 1 0 0 1 1}
/// Generates set: {A C D }
/// Note: size of permutation is equal to upper index.
/// For type WithRepetition, the output is defined by runs of characters and when to
/// move to the next element.
/// E.g. 6 choose 5 with repetition
/// Input array: {A B C D E F}
/// Permutations: {0 1 0 0 1 1 0 0 1 1}
/// Generates set: {A B B D D }
/// Note: size of permutation is equal to upper index - 1 + lower index.
/// </remarks>
private void ComputeCurrent()
{
if (myCurrentList == null)
{
myCurrentList = new List<T>();
var index = 0;
var currentPermutation = (IList<bool>) myPermutationsEnumerator.Current;
for (var i = 0; i < currentPermutation.Count; ++i)
{
if (currentPermutation[i] == false)
{
myCurrentList.Add(myParent.myValues[index]);
if (myParent.Type == GenerateOption.WithoutRepetition)
{
++index;
}
}
else
{
++index;
}
}
}
}
#endregion
#region IEnumerator interface
/// <summary>
/// Resets the combinations enumerator to the first combination.
/// </summary>
public void Reset()
{
myPermutationsEnumerator.Reset();
}
/// <summary>
/// Advances to the next combination of items from the set.
/// </summary>
/// <returns>True if successfully moved to next combination, False if no more unique combinations exist.</returns>
/// <remarks>
/// The heavy lifting is done by the permutations object, the combination is generated
/// by creating a new list of those items that have a true in the permutation parrellel array.
/// </remarks>
public bool MoveNext()
{
var ret = myPermutationsEnumerator.MoveNext();
myCurrentList = null;
return ret;
}
/// <summary>
/// The current combination
/// </summary>
public IList<T> Current
{
get
{
ComputeCurrent();
return myCurrentList;
}
}
/// <summary>
/// The current combination
/// </summary>
object IEnumerator.Current
{
get
{
ComputeCurrent();
return myCurrentList;
}
}
/// <summary>
/// Cleans up non-managed resources, of which there are none used here.
/// </summary>
public void Dispose()
{
;
}
#endregion
#region Data
/// <summary>
/// Parent object this is an enumerator for.
/// </summary>
private readonly Combinations<T> myParent;
/// <summary>
/// The current list of values, this is lazy evaluated by the Current property.
/// </summary>
private List<T> myCurrentList;
/// <summary>
/// An enumertor of the parents list of lexicographic orderings.
/// </summary>
private readonly Permutations<bool>.Enumerator myPermutationsEnumerator;
#endregion
}
#endregion
#region Constructors
/// <summary>
/// No default constructor, must provided a list of values and size.
/// </summary>
protected Combinations()
{
;
}
/// <summary>
/// Create a combination set from the provided list of values.
/// The upper index is calculated as values.Count, the lower index is specified.
/// Collection type defaults to MetaCollectionType.WithoutRepetition
/// </summary>
/// <param name="values">List of values to select combinations from.</param>
/// <param name="lowerIndex">The size of each combination set to return.</param>
public Combinations(IList<T> values, int lowerIndex)
{
Initialize(values, lowerIndex, GenerateOption.WithoutRepetition);
}
/// <summary>
/// Create a combination set from the provided list of values.
/// The upper index is calculated as values.Count, the lower index is specified.
/// </summary>
/// <param name="values">List of values to select combinations from.</param>
/// <param name="lowerIndex">The size of each combination set to return.</param>
/// <param name="type">The type of Combinations set to generate.</param>
public Combinations(IList<T> values, int lowerIndex, GenerateOption type)
{
Initialize(values, lowerIndex, type);
}
#endregion
#region IEnumerable Interface
/// <summary>
/// Gets an enumerator for collecting the list of combinations.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<IList<T>> GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Gets an enumerator for collecting the list of combinations.
/// </summary>
/// <returns>The enumerator.returns>
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region IMetaList Interface
/// <summary>
/// The number of unique combinations that are defined in this meta-collection.
/// This value is mathematically defined as Choose(M, N) where M is the set size
/// and N is the subset size. This is M! / (N! * (M-N)!).
/// </summary>
public long Count
{
get { return myPermutations.Count; }
}
/// <summary>
/// The type of Combinations set that is generated.
/// </summary>
public GenerateOption Type
{
get { return myMetaCollectionType; }
}
/// <summary>
/// The upper index of the meta-collection, equal to the number of items in the initial set.
/// </summary>
public int UpperIndex
{
get { return myValues.Count; }
}
/// <summary>
/// The lower index of the meta-collection, equal to the number of items returned each iteration.
/// </summary>
public int LowerIndex
{
get { return myLowerIndex; }
}
#endregion
#region Data
/// <summary>
/// Copy of values object is intialized with, required for enumerator reset.
/// </summary>
private List<T> myValues;
/// <summary>
/// Permutations object that handles permutations on booleans for combination inclusion.
/// </summary>
private Permutations<bool> myPermutations;
/// <summary>
/// The type of the combination collection.
/// </summary>
private GenerateOption myMetaCollectionType;
/// <summary>
/// The lower index defined in the constructor.
/// </summary>
private int myLowerIndex;
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class Is
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public static ConstraintExpression Not
{
get { return new ConstraintExpression().Not; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public static ConstraintExpression All
{
get { return new ConstraintExpression().All; }
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public static NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public static TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public static FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public static GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public static LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public static NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public static EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public static UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region BinarySerializable
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public static BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
#endif
#endregion
#region XmlSerializable
#if !SILVERLIGHT
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in xml format.
/// </summary>
public static XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endif
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public static EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public static SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the suppled argument
/// </summary>
public static GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public static GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the suppled argument
/// </summary>
public static LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public static LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf<T>()
{
return new ExactTypeConstraint(typeof(T));
}
#endif
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom<T>()
{
return new AssignableFromConstraint(typeof(T));
}
#endif
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo<T>()
{
return new AssignableToConstraint(typeof(T));
}
#endif
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public static CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public static CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public static CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public static SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region StringStarting
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public static StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region StringEnding
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public static EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region StringMatching
#if !NETCF
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public static RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endif
#endregion
#region SamePath
#if !PORTABLE
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public static SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(expected);
}
#endif
#endregion
#region SubPath
#if !PORTABLE
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is under an expected path after canonicalization.
/// </summary>
public static SubPathConstraint SubPath(string expected)
{
return new SubPathConstraint(expected);
}
#endif
#endregion
#region SamePathOrUnder
#if !PORTABLE
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public static SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return new SamePathOrUnderConstraint(expected);
}
#endif
#endregion
#region InRange
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public static RangeConstraint<T> InRange<T>(T from, T to) where T : IComparable<T>
{
return new RangeConstraint<T>(from, to);
}
#else
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public static RangeConstraint InRange(IComparable from, IComparable to)
{
return new RangeConstraint(from, to);
}
#endif
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel
{
public sealed class InstanceContext : CommunicationObject, IExtensibleObject<InstanceContext>
{
private InstanceBehavior _behavior;
private ConcurrencyInstanceContextFacet _concurrency;
private ServiceChannelManager _channels;
private ExtensionCollection<InstanceContext> _extensions;
private object _serviceInstanceLock = new object();
private SynchronizationContext _synchronizationContext;
private object _userObject;
private bool _wellKnown;
private SynchronizedCollection<IChannel> _wmiChannels;
private bool _isUserCreated;
public InstanceContext(object implementation)
: this(implementation, true)
{
}
internal InstanceContext(object implementation, bool isUserCreated)
: this(implementation, true, isUserCreated)
{
}
internal InstanceContext(object implementation, bool wellKnown, bool isUserCreated)
{
if (implementation != null)
{
_userObject = implementation;
_wellKnown = wellKnown;
}
_channels = new ServiceChannelManager(this);
_isUserCreated = isUserCreated;
}
internal InstanceBehavior Behavior
{
get { return _behavior; }
set
{
if (_behavior == null)
{
_behavior = value;
}
}
}
internal ConcurrencyInstanceContextFacet Concurrency
{
get
{
if (_concurrency == null)
{
lock (this.ThisLock)
{
if (_concurrency == null)
_concurrency = new ConcurrencyInstanceContextFacet();
}
}
return _concurrency;
}
}
protected override TimeSpan DefaultCloseTimeout
{
get
{
return ServiceDefaults.CloseTimeout;
}
}
protected override TimeSpan DefaultOpenTimeout
{
get
{
return ServiceDefaults.OpenTimeout;
}
}
public IExtensionCollection<InstanceContext> Extensions
{
get
{
this.ThrowIfClosed();
lock (this.ThisLock)
{
if (_extensions == null)
_extensions = new ExtensionCollection<InstanceContext>(this, this.ThisLock);
return _extensions;
}
}
}
public ICollection<IChannel> IncomingChannels
{
get
{
this.ThrowIfClosed();
return _channels.IncomingChannels;
}
}
public ICollection<IChannel> OutgoingChannels
{
get
{
this.ThrowIfClosed();
return _channels.OutgoingChannels;
}
}
public SynchronizationContext SynchronizationContext
{
get { return _synchronizationContext; }
set
{
this.ThrowIfClosedOrOpened();
_synchronizationContext = value;
}
}
new internal object ThisLock
{
get { return base.ThisLock; }
}
internal object UserObject
{
get { return _userObject; }
}
internal ICollection<IChannel> WmiChannels
{
get
{
if (_wmiChannels == null)
{
lock (this.ThisLock)
{
if (_wmiChannels == null)
{
_wmiChannels = new SynchronizedCollection<IChannel>();
}
}
}
return _wmiChannels;
}
}
protected override void OnAbort()
{
_channels.Abort();
}
internal void BindRpc(ref MessageRpc rpc)
{
this.ThrowIfClosed();
_channels.IncrementActivityCount();
rpc.SuccessfullyBoundInstance = true;
}
internal void FaultInternal()
{
this.Fault();
}
public object GetServiceInstance(Message message)
{
lock (_serviceInstanceLock)
{
this.ThrowIfClosedOrNotOpen();
object current = _userObject;
if (current != null)
{
return current;
}
if (_behavior == null)
{
Exception error = new InvalidOperationException(SR.SFxInstanceNotInitialized);
if (message != null)
{
throw TraceUtility.ThrowHelperError(error, message);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
object newUserObject;
if (message != null)
{
newUserObject = _behavior.GetInstance(this, message);
}
else
{
newUserObject = _behavior.GetInstance(this);
}
if (newUserObject != null)
{
SetUserObject(newUserObject);
}
return newUserObject;
}
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new CloseAsyncResult(timeout, callback, state, this);
}
protected override void OnEndClose(IAsyncResult result)
{
CloseAsyncResult.End(result);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new CompletedAsyncResult(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected override void OnClose(TimeSpan timeout)
{
_channels.Close(timeout);
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
}
protected override void OnOpened()
{
base.OnOpened();
}
protected override void OnOpening()
{
base.OnOpening();
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
this.OnClose(timeout);
return TaskHelpers.CompletedTask();
}
protected internal override Task OnOpenAsync(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
return TaskHelpers.CompletedTask();
}
private void SetUserObject(object newUserObject)
{
if (_behavior != null && !_wellKnown)
{
object oldUserObject = Interlocked.Exchange(ref _userObject, newUserObject);
}
}
internal void UnbindRpc(ref MessageRpc rpc)
{
if (rpc.InstanceContext == this && rpc.SuccessfullyBoundInstance)
{
_channels.DecrementActivityCount();
}
}
internal class CloseAsyncResult : AsyncResult
{
private InstanceContext _instanceContext;
private TimeoutHelper _timeoutHelper;
public CloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, InstanceContext instanceContext)
: base(callback, state)
{
_timeoutHelper = new TimeoutHelper(timeout);
_instanceContext = instanceContext;
IAsyncResult result = _instanceContext._channels.BeginClose(_timeoutHelper.RemainingTime(), PrepareAsyncCompletion(new AsyncCompletion(CloseChannelsCallback)), this);
if (result.CompletedSynchronously && CloseChannelsCallback(result))
{
base.Complete(true);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CloseAsyncResult>(result);
}
private bool CloseChannelsCallback(IAsyncResult result)
{
Fx.Assert(object.ReferenceEquals(this, result.AsyncState), "AsyncState should be this");
_instanceContext._channels.EndClose(result);
return true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using YogUILibrary;
using YogUILibrary.UIComponents;
using YogUILibrary.Managers;
using YogUILibrary.Structs;
using System.IO;
using System.Diagnostics;
namespace NinepatchEditor
{
/// <summary>
/// This is the main type for your game
/// </summary
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public Texture2D curTexture = null;
public NinePatch curNinepatch = new NinePatch();
public TextField xStart;
public TextField xEnd;
public TextField yStart;
public TextField yEnd;
public Button refreshNinepatch;
public CheckBox drawContent;
public SliderBar patchScale;
public Button loadNinepatch;
public Button saveNinepatchAs;
public Rectangle fileOpDraw = new Rectangle(1, 1, 200, 50);
public Rectangle patchInfoDraw = new Rectangle(201, 1, 800 - 201, 50);
public Rectangle patchDisplayDraw = new Rectangle(201, 51, 800 - 201, 480 - 51);
public Rectangle patchTextureDraw = new Rectangle(1, 51, 200, 480 - 51);
public Rectangle testDrawing = new Rectangle(0, 0, 1, 1);
public RadioButtonGroup scaleGroup = new RadioButtonGroup();
public RadioButton scaleX;
public RadioButton scaleY;
public RadioButton scaleXY;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
this.IsMouseVisible = true;
Window.Title = "YoGUI Ninepatch editor";
graphics.PreferMultiSampling = true;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
YogUI.YogUI_LoadContent(this);
SpriteFont buttonFont = Content.Load<SpriteFont>("buttonFont");
loadNinepatch = new Button(new Vector2(46, 23), "Open", buttonFont, loadExisting);
saveNinepatchAs = new Button(new Vector2(150, 23), "Save", buttonFont, saveImage);
xStart = new TextField(new Vector2(225, 3), 70, 15, Color.Black, buttonFont, (string s) => { refresh(); }, (string s) => { refresh(); });
xEnd = new TextField(new Vector2(225, 28), 70, 15, Color.Black, buttonFont, (string s) => { refresh(); }, (string s) => { refresh(); });
xStart.stringPattern = xEnd.stringPattern = "^\\d+?$";
xStart.placeHolderText = "X start";
xEnd.placeHolderText = "X end";
yStart = new TextField(new Vector2(305, 3), 70, 15, Color.Black, buttonFont, (string s) => { refresh(); }, (string s) => { refresh(); });
yEnd = new TextField(new Vector2(305, 28), 70, 15, Color.Black, buttonFont, (string s) => { refresh(); }, (string s) => { refresh(); });
yStart.stringPattern = yEnd.stringPattern = "^\\d+?$";
yStart.placeHolderText = "Y start";
yEnd.placeHolderText = "Y end";
refreshNinepatch = new Button(new Vector2(420, 18), "Refresh", buttonFont, refresh);
patchScale = new SliderBar(new Vector2(465, 9), 225, 30, 0, 100, buttonFont);
drawContent = new CheckBox(new Vector2(390, 45), buttonFont);
drawContent.SetLabel("Draw content");
drawContent.SetChecked(true);
scaleX = new RadioButton(new Vector2(700, 9), buttonFont, "Scale X");
scaleY = new RadioButton(new Vector2(700, 23), buttonFont, "Scale Y");
scaleXY = new RadioButton(new Vector2(700, 37), buttonFont, "Scale X+Y");
scaleGroup.addButton(scaleX);
scaleGroup.addButton(scaleY);
scaleGroup.addButton(scaleXY);
scaleX.selected = true;
// TODO: use this.Content to load your game content here
}
public void refresh()
{
Texture2D refreshTexture = createImageNinepatch();
if (refreshTexture == null) return;
curNinepatch.LoadFromTexture(refreshTexture);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
YogUI.YogUI_Update(gameTime);
loadNinepatch.Update(gameTime);
saveNinepatchAs.Update(gameTime);
xStart.Update(gameTime);
xEnd.Update(gameTime);
yStart.Update(gameTime);
yEnd.Update(gameTime);
refreshNinepatch.Update(gameTime);
patchScale.Update(gameTime);
scaleX.Update(gameTime);
scaleY.Update(gameTime);
scaleXY.Update(gameTime);
drawContent.Update(gameTime);
base.Update(gameTime);
}
public void loadExisting()
{
var open = new System.Windows.Forms.OpenFileDialog();
open.SupportMultiDottedExtensions = true;
open.DefaultExt = ".9.png";
open.Filter = "Image files|*.png|Ninepatch files|*.9.png|All files|*";
open.ShowDialog();
String fileName = open.FileName;
if (File.Exists(fileName))
{
loadImage(fileName);
}
}
public void loadImage(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
Texture2D texture = Texture2D.FromStream(GraphicsDevice, fs);
if (NinePatch.isAlreadyNinepatch(texture))
{
loadImageExisting(texture);
}
else
{
loadImageNew(texture);
}
computeScale();
}
}
public void loadImageExisting(Texture2D texture)
{
//We have to remove the 1-pixel padding on each side first.
Color[] textureData = new Color[(texture.Width - 2) * (texture.Height - 2)];
Color[] textureDataHolder = new Color[texture.Width * texture.Height];
texture.GetData<Color>(textureDataHolder);
int totalMinus = 0;
for (int i = texture.Width + 1; i < (texture.Width * texture.Height); i++)
{
bool isNotToLeft = ((float)i / (float)texture.Width) != (i / texture.Width);
bool isNotToRight = ((float)(i + 1) / (float)texture.Width) != ((i + 1) / texture.Width);
totalMinus += (!isNotToLeft || !isNotToRight) ? 1 : 0;
// if (!isNotToLeft) System.Diagnostics.Debugger.Break();
if (isNotToLeft && isNotToRight && i >= texture.Width && i < (texture.Width - 1) * texture.Height)
{
//Is within the bounds.
int test = i - (texture.Width + 1 + totalMinus);
textureData[test] = textureDataHolder[i];
}
}
Texture2D ret = new Texture2D(GraphicsDevice, texture.Width - 2, texture.Height - 2);
ret.SetData<Color>(textureData);
curTexture = ret;
curNinepatch.LoadFromTexture(texture);
xStart.SetText(curNinepatch.leftMostPatch.ToString());
xEnd.SetText(curNinepatch.rightMostPatch.ToString());
yStart.SetText(curNinepatch.topMostPatch.ToString());
yEnd.SetText(curNinepatch.bottomMostPatch.ToString());
}
public void loadImageNew(Texture2D texture)
{
curTexture = texture;
xStart.SetText("1");
xEnd.SetText("3");
yStart.SetText("1");
yEnd.SetText("3");
curTexture = texture;
curNinepatch.LoadFromTexture(createImageNinepatch());
}
public void computeScale()
{
if (curNinepatch == null) return;
int midWidth = (curNinepatch.rightMostPatch - curNinepatch.leftMostPatch);
int midHeight = (curNinepatch.bottomMostPatch - curNinepatch.topMostPatch);
int extraWidth = curNinepatch.leftWidth + curNinepatch.rightWidth;
int extraHeight = curNinepatch.bottomHeight + curNinepatch.topHeight;
if (scaleX.selected)
{
int totalMinimum = midWidth + extraWidth + 10;
int available = patchDisplayDraw.Width - totalMinimum;
patchScale.min = 0;
patchScale.max = available;
}
else if (scaleY.selected)
{
int totalMinimum = midHeight + extraHeight + 10;
int available = patchDisplayDraw.Height - totalMinimum;
patchScale.min = 0;
patchScale.max = available;
}
else if (scaleXY.selected)
{
int totalMinimumW = midWidth + extraWidth + 10;
int totalMinimumH = midHeight + extraHeight + 10;
int availableW = patchDisplayDraw.Width - totalMinimumW;
int availableH = patchDisplayDraw.Height - totalMinimumH;
patchScale.min = 0;
//set it to the lower of the two.
patchScale.max = (availableH < availableW) ? availableH : availableW;
}
}
public void saveImage()
{
if (curNinepatch.texture == null || curTexture == null) return;
var save = new System.Windows.Forms.SaveFileDialog();
save.SupportMultiDottedExtensions = true;
save.DefaultExt = ".9.png";
save.Filter = "Ninepatch files|*.9.png|All files|*";
save.ShowDialog();
String fileName = save.FileName;
Texture2D toSave = createImageNinepatch();
if (toSave == null) return;
try
{
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
toSave.SaveAsPng(fs, toSave.Width, toSave.Height);
}
}
catch (Exception) { }
}
public Texture2D createImageNinepatch()
{
if (curNinepatch.texture == null || curTexture == null) return null;
int leftMost = xStart.textValid ? Convert.ToInt32(xStart.GetText()) : 0;
int rightMost = xEnd.textValid ? Convert.ToInt32(xEnd.GetText()) : 1;
int topMost = yStart.textValid ? Convert.ToInt32(yStart.GetText()) : 0;
int bottomMost = yEnd.textValid ? Convert.ToInt32(yEnd.GetText()) : 1;
Color[] newData = new Color[(curTexture.Width + 2) * (curTexture.Height + 2)];
Color[] curData = new Color[curTexture.Width * curTexture.Height];
curTexture.GetData<Color>(curData);
int curRealPos = -1;
for (int i = 0; i < newData.Length; i++)
{
Color curColor = Color.Transparent;
int y = (i / (curTexture.Width + 2));
int x = i - (y * (curTexture.Width + 2));
int curPos = (x - 1) + ((y - 1) * curTexture.Width);
if (y == 0)
{
if (x >= leftMost && x <= rightMost)
{
curColor = Color.Black;
}
}
if (x == 0)
{
if (y >= topMost && y <= bottomMost)
{
curColor = Color.Black;
}
}
if (x > 0 && y > 0 && x < (curTexture.Width + 1) && y < (curTexture.Height + 1))
{
curRealPos += 1;
curColor = curData[curRealPos];
}
newData[i] = curColor;
}
Texture2D ret = new Texture2D(GraphicsDevice, curTexture.Width + 2, curTexture.Height + 2);
ret.SetData<Color>(newData);
return ret;
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
GraphicsDevice.PresentationParameters.MultiSampleCount = 12;
spriteBatch.Begin();
DrawManager.Draw_Box(new Vector2(fileOpDraw.Left, fileOpDraw.Top), new Vector2(fileOpDraw.Right, fileOpDraw.Bottom), Color.Black, spriteBatch, 0f, 200);
DrawManager.Draw_Outline(new Vector2(fileOpDraw.Left, fileOpDraw.Top), new Vector2(fileOpDraw.Right, fileOpDraw.Bottom), Color.White, spriteBatch);
DrawManager.Draw_Box(new Vector2(patchInfoDraw.Left, patchInfoDraw.Top), new Vector2(patchInfoDraw.Right, patchInfoDraw.Bottom), Color.Black, spriteBatch, 0f, 200);
DrawManager.Draw_Outline(new Vector2(patchInfoDraw.Left, patchInfoDraw.Top), new Vector2(patchInfoDraw.Right, patchInfoDraw.Bottom), Color.White, spriteBatch);
DrawManager.Draw_Box(new Vector2(patchDisplayDraw.Left, patchDisplayDraw.Top), new Vector2(patchDisplayDraw.Right, patchDisplayDraw.Bottom), Color.Black, spriteBatch, 0f, 200);
DrawManager.Draw_Outline(new Vector2(patchDisplayDraw.Left, patchDisplayDraw.Top), new Vector2(patchDisplayDraw.Right, patchDisplayDraw.Bottom), Color.White, spriteBatch);
DrawManager.Draw_Box(new Vector2(patchTextureDraw.Left, patchTextureDraw.Top), new Vector2(patchTextureDraw.Right, patchTextureDraw.Bottom), Color.Black, spriteBatch, 0f, 200);
DrawManager.Draw_Outline(new Vector2(patchTextureDraw.Left, patchTextureDraw.Top), new Vector2(patchTextureDraw.Right, patchTextureDraw.Bottom), Color.White, spriteBatch);
DrawManager.Draw_Box(new Vector2(testDrawing.Left, testDrawing.Top), new Vector2(testDrawing.Right, testDrawing.Bottom), Color.Black, spriteBatch, 0f, 200);
DrawManager.Draw_Outline(new Vector2(testDrawing.Left, testDrawing.Top), new Vector2(testDrawing.Right, testDrawing.Bottom), Color.White, spriteBatch);
loadNinepatch.Draw(spriteBatch);
saveNinepatchAs.Draw(spriteBatch);
xStart.Draw(spriteBatch);
xEnd.Draw(spriteBatch);
yStart.Draw(spriteBatch);
yEnd.Draw(spriteBatch);
refreshNinepatch.Draw(spriteBatch);
scaleX.Draw(spriteBatch);
scaleY.Draw(spriteBatch);
scaleXY.Draw(spriteBatch);
drawContent.Draw(spriteBatch);
if (curTexture != null)
{
spriteBatch.Draw(curTexture, ConversionManager.PToV(patchTextureDraw.Center), null, Color.White, 0f, new Vector2(curTexture.Width / 2, curTexture.Height / 2), 1f, SpriteEffects.None, 0f);
}
Vector2 drawPos = ConversionManager.PToV(patchDisplayDraw.Center);
if (curNinepatch.texture != null)
{
computeScale();
patchScale.Draw(spriteBatch);
int height = curNinepatch.bottomMostPatch - curNinepatch.topMostPatch;
int width = curNinepatch.rightMostPatch - curNinepatch.leftMostPatch;
if (scaleX.selected)
{
curNinepatch.Draw(spriteBatch, drawPos - curNinepatch.getCenter(width + patchScale.getNumber(), height), width + (patchScale.getNumber()), height);
if (drawContent.GetChecked())
curNinepatch.DrawContent(spriteBatch, drawPos - curNinepatch.getCenter(width + patchScale.getNumber(), height), width + (patchScale.getNumber()), height, Color.Red);
}
else if (scaleY.selected)
{
curNinepatch.Draw(spriteBatch, drawPos - curNinepatch.getCenter(width, height + patchScale.getNumber()), width, height + (patchScale.getNumber()));
if (drawContent.GetChecked())
curNinepatch.DrawContent(spriteBatch, drawPos - curNinepatch.getCenter(width, height + patchScale.getNumber()), width, height + (patchScale.getNumber()), Color.Red);
}
else if (scaleXY.selected)
{
curNinepatch.Draw(spriteBatch, drawPos - curNinepatch.getCenter(width + patchScale.getNumber(), height + patchScale.getNumber()), width + (patchScale.getNumber()), height + (patchScale.getNumber()));
if (drawContent.GetChecked())
curNinepatch.DrawContent(spriteBatch, drawPos - curNinepatch.getCenter(width + patchScale.getNumber(), height + patchScale.getNumber()), width + (patchScale.getNumber()), height + (patchScale.getNumber()), Color.Red);
}
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Core.Definitions;
using Microsoft.MixedReality.Toolkit.Core.EventDatum.Teleport;
using Microsoft.MixedReality.Toolkit.Core.Interfaces.InputSystem;
using Microsoft.MixedReality.Toolkit.Core.Interfaces.TeleportSystem;
using Microsoft.MixedReality.Toolkit.Core.Utilities;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Microsoft.MixedReality.Toolkit.Core.Services.Teleportation
{
/// <summary>
/// The Mixed Reality Toolkit's specific implementation of the <see cref="IMixedRealityTeleportSystem"/>
/// </summary>
public class MixedRealityTeleportSystem : BaseEventSystem, IMixedRealityTeleportSystem
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="profile"></param>
public MixedRealityTeleportSystem(BaseMixedRealityProfile profile)
: base(profile)
{
}
private TeleportEventData teleportEventData;
private bool isTeleporting = false;
private bool isProcessingTeleportRequest = false;
private Vector3 targetPosition = Vector3.zero;
private Vector3 targetRotation = Vector3.zero;
/// <summary>
/// only used to clean up event system when shutting down if this system created one.
/// </summary>
private GameObject eventSystemReference = null;
#region IMixedRealityService Implementation
/// <inheritdoc />
public override void Initialize()
{
base.Initialize();
if (!Application.isPlaying) { return; }
teleportEventData = new TeleportEventData(EventSystem.current);
}
/// <inheritdoc />
public override void Destroy()
{
base.Destroy();
if (eventSystemReference != null)
{
if (Application.isEditor)
{
Object.DestroyImmediate(eventSystemReference);
}
else
{
Object.Destroy(eventSystemReference);
}
}
}
#endregion IMixedRealityService Implementation
#region IEventSystemManager Implementation
/// <inheritdoc />
public override void HandleEvent<T>(BaseEventData eventData, ExecuteEvents.EventFunction<T> eventHandler)
{
Debug.Assert(eventData != null);
var teleportData = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
Debug.Assert(teleportData != null);
Debug.Assert(!teleportData.used);
// Process all the event listeners
base.HandleEvent(teleportData, eventHandler);
}
/// <summary>
/// Unregister a <see cref="GameObject"/> from listening to Teleport events.
/// </summary>
/// <param name="listener"></param>
public override void Register(GameObject listener)
{
base.Register(listener);
}
/// <summary>
/// Unregister a <see cref="GameObject"/> from listening to Teleport events.
/// </summary>
/// <param name="listener"></param>
public override void Unregister(GameObject listener)
{
base.Unregister(listener);
}
#endregion IEventSystemManager Implementation
#region IMixedRealityTeleportSystem Implementation
private float teleportDuration = 0.25f;
/// <inheritdoc />
public float TeleportDuration
{
get { return teleportDuration; }
set
{
if (isProcessingTeleportRequest)
{
Debug.LogWarning("Couldn't change teleport duration. Teleport in progress.");
return;
}
teleportDuration = value;
}
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityTeleportHandler> OnTeleportRequestHandler =
delegate (IMixedRealityTeleportHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
handler.OnTeleportRequest(casted);
};
/// <inheritdoc />
public void RaiseTeleportRequest(IMixedRealityPointer pointer, IMixedRealityTeleportHotSpot hotSpot)
{
// initialize event
teleportEventData.Initialize(pointer, hotSpot);
// Pass handler
HandleEvent(teleportEventData, OnTeleportRequestHandler);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityTeleportHandler> OnTeleportStartedHandler =
delegate (IMixedRealityTeleportHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
handler.OnTeleportStarted(casted);
};
/// <inheritdoc />
public void RaiseTeleportStarted(IMixedRealityPointer pointer, IMixedRealityTeleportHotSpot hotSpot)
{
if (isTeleporting)
{
Debug.LogError("Teleportation already in progress");
return;
}
isTeleporting = true;
// initialize event
teleportEventData.Initialize(pointer, hotSpot);
// Pass handler
HandleEvent(teleportEventData, OnTeleportStartedHandler);
ProcessTeleportationRequest(teleportEventData);
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityTeleportHandler> OnTeleportCompletedHandler =
delegate (IMixedRealityTeleportHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
handler.OnTeleportCompleted(casted);
};
/// <summary>
/// Raise a teleportation completed event.
/// </summary>
/// <param name="pointer">The pointer that raised the event.</param>
/// <param name="hotSpot">The teleport target</param>
private void RaiseTeleportComplete(IMixedRealityPointer pointer, IMixedRealityTeleportHotSpot hotSpot)
{
if (!isTeleporting)
{
Debug.LogError("No Active Teleportation in progress.");
return;
}
// initialize event
teleportEventData.Initialize(pointer, hotSpot);
// Pass handler
HandleEvent(teleportEventData, OnTeleportCompletedHandler);
isTeleporting = false;
}
private static readonly ExecuteEvents.EventFunction<IMixedRealityTeleportHandler> OnTeleportCanceledHandler =
delegate (IMixedRealityTeleportHandler handler, BaseEventData eventData)
{
var casted = ExecuteEvents.ValidateEventData<TeleportEventData>(eventData);
handler.OnTeleportCanceled(casted);
};
/// <inheritdoc />
public void RaiseTeleportCanceled(IMixedRealityPointer pointer, IMixedRealityTeleportHotSpot hotSpot)
{
// initialize event
teleportEventData.Initialize(pointer, hotSpot);
// Pass handler
HandleEvent(teleportEventData, OnTeleportCanceledHandler);
}
#endregion IMixedRealityTeleportSystem Implementation
private void ProcessTeleportationRequest(TeleportEventData eventData)
{
isProcessingTeleportRequest = true;
var cameraParent = MixedRealityToolkit.Instance.MixedRealityPlayspace;
targetRotation = Vector3.zero;
targetRotation.y = eventData.Pointer.PointerOrientation;
targetPosition = eventData.Pointer.Result.Details.Point;
if (eventData.HotSpot != null)
{
targetPosition = eventData.HotSpot.Position;
if (eventData.HotSpot.OverrideTargetOrientation)
{
targetRotation.y = eventData.HotSpot.TargetOrientation;
}
}
float height = targetPosition.y;
targetPosition -= CameraCache.Main.transform.position - cameraParent.position;
targetPosition.y = height;
cameraParent.position = targetPosition;
cameraParent.RotateAround(CameraCache.Main.transform.position, Vector3.up, targetRotation.y - CameraCache.Main.transform.eulerAngles.y);
isProcessingTeleportRequest = false;
// Raise complete event using the pointer and hot spot provided.
RaiseTeleportComplete(eventData.Pointer, eventData.HotSpot);
}
}
}
| |
// --------------------------------------------------------------------------------------------
// <copyright from='2011' to='2011' company='SIL International'>
// Copyright (c) 2011, SIL International. All Rights Reserved.
//
// Distributable under the terms of either the Common Public License or the
// GNU Lesser General Public License, as specified in the LICENSING.txt file.
// </copyright>
// --------------------------------------------------------------------------------------------
#if __MonoCS__
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using X11.XKlavier;
using Palaso.Reporting;
using Palaso.UI.WindowsForms.Keyboarding.Interfaces;
using Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces;
using Palaso.UI.WindowsForms.Keyboarding.Types;
using Palaso.WritingSystems;
namespace Palaso.UI.WindowsForms.Keyboarding.Linux
{
/// <summary>
/// Class for handling xkb keyboards on Linux
/// </summary>
public class XkbKeyboardAdaptor: IKeyboardAdaptor
{
protected List<IKeyboardErrorDescription> m_BadLocales;
private IXklEngine m_engine;
public XkbKeyboardAdaptor(): this(new XklEngine())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Palaso.UI.WindowsForms.Keyboarding.Linux.XkbKeyboardAdaptor"/> class.
/// This overload is used in unit tests.
/// </summary>
public XkbKeyboardAdaptor(IXklEngine engine)
{
m_engine = engine;
}
private string GetLanguageCountry(Icu.Locale locale)
{
if (string.IsNullOrEmpty(locale.Country) && string.IsNullOrEmpty(locale.Language))
return string.Empty;
return locale.Language + "_" + locale.Country;
}
/// <summary>
/// Gets the IcuLocales by language and country. The 3-letter language and country codes
/// are concatenated with an underscore in between, e.g. fra_BEL
/// </summary>
private Dictionary<string, Icu.Locale> IcuLocalesByLanguageCountry
{
get
{
var localesByLanguageCountry = new Dictionary<string, Icu.Locale>();
foreach (var locale in Icu.Locale.AvailableLocales)
{
var languageCountry = GetLanguageCountry(locale);
if (string.IsNullOrEmpty(languageCountry) ||
localesByLanguageCountry.ContainsKey(languageCountry))
{
continue;
}
localesByLanguageCountry[languageCountry] = locale;
}
return localesByLanguageCountry;
}
}
private static string GetDescription(XklConfigRegistry.LayoutDescription layout)
{
return string.Format("{0} - {1} ({2})", layout.Description, layout.Language, layout.Country);
}
protected virtual void InitLocales()
{
if (m_BadLocales != null)
return;
ReinitLocales();
}
private void ReinitLocales()
{
m_BadLocales = new List<IKeyboardErrorDescription>();
var configRegistry = XklConfigRegistry.Create(m_engine);
var layouts = configRegistry.Layouts;
for (int iGroup = 0; iGroup < m_engine.GroupNames.Length; iGroup++)
{
// a group in a xkb keyboard is a keyboard layout. This can be used with
// multiple languages - which language is ambigious. Here we just add all
// of them.
// m_engine.GroupNames are not localized, but the layouts are. Before we try
// to compare them we better localize the group name as well, or we won't find
// much (FWNX-1388)
var groupName = m_engine.LocalizedGroupNames[iGroup];
List<XklConfigRegistry.LayoutDescription> layoutList;
if (!layouts.TryGetValue(groupName, out layoutList))
{
// No language in layouts uses the groupName keyboard layout.
m_BadLocales.Add(new KeyboardErrorDescription(groupName));
Console.WriteLine("WARNING: Couldn't find layout for {0}.", groupName);
Logger.WriteEvent("WARNING: Couldn't find layout for {0}.", groupName);
continue;
}
for (int iLayout = 0; iLayout < layoutList.Count; iLayout++)
{
var layout = layoutList[iLayout];
AddKeyboardForLayout(layout, iGroup);
}
}
}
private void AddKeyboardForLayout(XklConfigRegistry.LayoutDescription layout, int iGroup)
{
AddKeyboardForLayout(layout, iGroup, this);
}
internal void AddKeyboardForLayout(XklConfigRegistry.LayoutDescription layout, int iGroup, IKeyboardAdaptor engine)
{
var description = GetDescription(layout);
CultureInfo culture = null;
try
{
culture = new CultureInfo(layout.LocaleId);
}
catch (ArgumentException)
{
// This can happen if the locale is not supported.
// TODO: fix mono's list of supported locales. Doesn't support e.g. de-BE.
// See mono/tools/locale-builder.
}
var inputLanguage = new InputLanguageWrapper(culture, IntPtr.Zero, layout.Language);
var keyboard = new XkbKeyboardDescription(description, layout.LayoutId, layout.LocaleId,
inputLanguage, engine, iGroup);
KeyboardController.Manager.RegisterKeyboard(keyboard);
}
internal IXklEngine XklEngine
{
get { return m_engine; }
}
public List<IKeyboardErrorDescription> ErrorKeyboards
{
get
{
InitLocales();
return m_BadLocales;
}
}
public void Initialize()
{
InitLocales();
}
public void UpdateAvailableKeyboards()
{
ReinitLocales();
}
public void Close()
{
m_engine.Close();
m_engine = null;
}
public bool ActivateKeyboard(IKeyboardDefinition keyboard)
{
Debug.Assert(keyboard is KeyboardDescription);
Debug.Assert(((KeyboardDescription)keyboard).Engine == this);
Debug.Assert(keyboard is XkbKeyboardDescription);
var xkbKeyboard = keyboard as XkbKeyboardDescription;
if (xkbKeyboard == null)
throw new ArgumentException();
if (xkbKeyboard.GroupIndex >= 0)
{
m_engine.SetGroup(xkbKeyboard.GroupIndex);
}
return true;
}
public void DeactivateKeyboard(IKeyboardDefinition keyboard)
{
}
public IKeyboardDefinition GetKeyboardForInputLanguage(IInputLanguage inputLanguage)
{
throw new NotImplementedException();
}
/// <summary>
/// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...)
/// </summary>
public KeyboardType Type
{
get { return KeyboardType.System; }
}
/// <summary>
/// Gets the default keyboard of the system.
/// </summary>
/// <remarks>For Xkb the default keyboard is the first one.</remarks>
public IKeyboardDefinition DefaultKeyboard
{
get
{
return Keyboard.Controller.AllAvailableKeyboards.Where(kbd => kbd.Type == KeyboardType.System)
.FirstOrDefault(x => x is XkbKeyboardDescription && ((XkbKeyboardDescription)x).GroupIndex == 0);
}
}
private string _missingKeyboardFmt;
/// <summary>
/// Creates and returns a keyboard definition object based on the layout and locale.
/// Note that this method is used when we do NOT have a matching available keyboard.
/// Therefore we can presume that the created one is NOT available.
/// </summary>
public IKeyboardDefinition CreateKeyboardDefinition(string layout, string locale)
{
var realLocale = locale;
if (locale == "zh")
{
realLocale = "zh-CN"; // Mono doesn't support bare "zh" until version 3 sometime
}
else if (locale == "x040F")
{
realLocale = "is"; // 0x040F is the numeric code for Icelandic.
}
// Don't crash if the locale is unknown to the system. (It may be that ibus is not running and
// this particular locale and layout refer to an ibus keyboard.) Mark the keyboard description
// as missing, but create an English (US) keyboard underneath.
if (IsLocaleKnown(realLocale))
return new XkbKeyboardDescription(string.Format("{0} ({1})", locale, layout), layout, locale,
new InputLanguageWrapper(realLocale, IntPtr.Zero, layout), this, -1) {IsAvailable = false};
if (_missingKeyboardFmt == null)
_missingKeyboardFmt = L10NSharp.LocalizationManager.GetString("XkbKeyboardAdaptor.MissingKeyboard", "[Missing] {0} ({1})");
return new XkbKeyboardDescription(String.Format(_missingKeyboardFmt, locale, layout), layout, locale,
new InputLanguageWrapper("en", IntPtr.Zero, "US"), this, -1) {IsAvailable = false};
}
private static HashSet<string> _knownCultures;
/// <summary>
/// Check whether the locale is known to the system.
/// </summary>
private static bool IsLocaleKnown(string locale)
{
if (_knownCultures == null)
{
_knownCultures = new HashSet<string>();
foreach (var ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
_knownCultures.Add(ci.Name);
}
return _knownCultures.Contains(locale);
}
}
}
#endif
| |
/* * * * *
* A simple Json Parser / builder
* ------------------------------
*
* It mainly has been written as a simple Json parser. It can build a Json string
* from the node-tree, or generate a node tree from any valid Json string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Modified by oPless, 2014-09-21 to round-trip properly
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JsonArray), objects(JsonClass) and values(JsonData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed Json is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JsonLazyCreator class which simplifies the construction of a Json tree
* Now you can simple reference any item that doesn't exist yet and it will return a JsonLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
// Originally taken from https://github.com/opless/SimpleJSON
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NAME.Json
{
internal enum JsonBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
internal abstract class JsonNode : IJsonNode
{
public virtual void Add(string aKey, JsonNode aItem)
{
}
IJsonNode IJsonNode.this[string aKey] => this[aKey];
IJsonNode IJsonNode.this[int aIndex] => this[aIndex];
public virtual JsonNode this[int aIndex]
{
get { return null; }
set { }
}
public virtual JsonNode this[string aKey]
{
get { return null; }
set { }
}
public virtual string Value
{
get { return string.Empty; }
set { }
}
public virtual int Count
{
get { return 0; }
}
public virtual void Add(JsonNode aItem)
{
this.Add(string.Empty, aItem);
}
public virtual JsonNode Remove(string aKey)
{
return null;
}
public virtual JsonNode Remove(int aIndex)
{
return null;
}
public virtual JsonNode Remove(JsonNode aNode)
{
return aNode;
}
public virtual IEnumerable<JsonNode> Children
{
get
{
yield break;
}
}
public IEnumerable<JsonNode> DeepChildren
{
get
{
foreach (var c in this.Children)
{
foreach (var d in c.DeepChildren)
yield return d;
}
}
}
public override string ToString()
{
return "JsonNode";
}
public virtual string ToString(string aPrefix)
{
return "JsonNode";
}
public abstract string ToJson(int prefix);
public virtual JsonBinaryTag Tag { get; set; }
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(this.Value, out v))
return v;
return 0;
}
set
{
this.Value = value.ToString();
this.Tag = JsonBinaryTag.IntValue;
}
}
public virtual long AsLong
{
get
{
long v = 0;
if (long.TryParse(this.Value, out v))
return v;
return 0;
}
set
{
this.Value = value.ToString();
this.Tag = JsonBinaryTag.IntValue;
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(this.Value, out v))
return v;
return 0.0f;
}
set
{
this.Value = value.ToString();
this.Tag = JsonBinaryTag.FloatValue;
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(this.Value, out v))
return v;
return 0.0;
}
set
{
this.Value = value.ToString();
this.Tag = JsonBinaryTag.DoubleValue;
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(this.Value, out v))
return v;
return !string.IsNullOrEmpty(this.Value);
}
set
{
this.Value = value ? "true" : "false";
this.Tag = JsonBinaryTag.BoolValue;
}
}
public virtual JsonArray AsArray
{
get
{
return this as JsonArray;
}
}
public virtual JsonClass AsObject
{
get
{
return this as JsonClass;
}
}
public static implicit operator JsonNode(string s)
{
return new JsonData(s);
}
public static implicit operator string(JsonNode d)
{
return (d == null) ? null : d.Value;
}
public static bool operator ==(JsonNode a, object b)
{
if (b == null && a is JsonLazyCreator)
return true;
return object.ReferenceEquals(a, b);
}
public static bool operator !=(JsonNode a, object b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
return object.ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
internal static string Escape(string aText)
{
string result = string.Empty;
if (aText != null)
{
foreach (char c in aText)
{
switch (c)
{
case '\\':
result += "\\\\";
break;
case '\"':
result += "\\\"";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
default:
result += c;
break;
}
}
}
return result;
}
private static JsonData Numberize(string token)
{
bool flag = false;
int integer = 0;
double real = 0;
if (int.TryParse(token, out integer))
{
return new JsonData(integer);
}
if (double.TryParse(token, out real))
{
return new JsonData(real);
}
if (bool.TryParse(token, out flag))
{
return new JsonData(flag);
}
throw new NotImplementedException(token);
}
private static void AddElement(JsonNode ctx, string token, string tokenName, bool tokenIsString)
{
if (tokenIsString)
{
if (ctx is JsonArray)
ctx.Add(token);
else
ctx.Add(tokenName, token); // assume dictionary/object
}
else
{
JsonData number = Numberize(token);
if (ctx is JsonArray)
ctx.Add(number);
else
ctx.Add(tokenName, number);
}
}
public static JsonNode Parse(string aJson)
{
Stack<JsonNode> stack = new Stack<JsonNode>();
JsonNode ctx = null;
int i = 0;
string token = string.Empty;
string tokenName = string.Empty;
bool quoteMode = false;
bool tokenIsString = false;
while (i < aJson.Length)
{
switch (aJson[i])
{
case '{':
if (quoteMode)
{
token += aJson[i];
break;
}
stack.Push(new JsonClass());
if (ctx != null)
{
tokenName = tokenName.Trim();
if (ctx is JsonArray)
ctx.Add(stack.Peek());
else if (tokenName != string.Empty)
ctx.Add(tokenName, stack.Peek());
}
tokenName = string.Empty;
token = string.Empty;
ctx = stack.Peek();
break;
case '[':
if (quoteMode)
{
token += aJson[i];
break;
}
stack.Push(new JsonArray());
if (ctx != null)
{
tokenName = tokenName.Trim();
if (ctx is JsonArray)
ctx.Add(stack.Peek());
else if (tokenName != string.Empty)
ctx.Add(tokenName, stack.Peek());
}
tokenName = string.Empty;
token = string.Empty;
ctx = stack.Peek();
break;
case '}':
case ']':
if (quoteMode)
{
token += aJson[i];
break;
}
if (stack.Count == 0)
throw new Exception("Json Parse: Too many closing brackets");
stack.Pop();
if (token != string.Empty)
{
tokenName = tokenName.Trim();
/*
if (ctx is JsonArray)
ctx.Add (Token);
else if (TokenName != string.Empty)
ctx.Add (TokenName, Token);
*/
AddElement(ctx, token, tokenName, tokenIsString);
tokenIsString = false;
}
tokenName = string.Empty;
token = string.Empty;
if (stack.Count > 0)
ctx = stack.Peek();
break;
case ':':
if (quoteMode)
{
token += aJson[i];
break;
}
tokenName = token;
token = string.Empty;
tokenIsString = false;
break;
case '"':
quoteMode ^= true;
tokenIsString = quoteMode == true ? true : tokenIsString;
break;
case ',':
if (quoteMode)
{
token += aJson[i];
break;
}
if (token != string.Empty)
{
/*
if (ctx is JsonArray) {
ctx.Add (Token);
} else if (TokenName != string.Empty) {
ctx.Add (TokenName, Token);
}
*/
AddElement(ctx, token, tokenName, tokenIsString);
tokenIsString = false;
}
tokenName = string.Empty;
token = string.Empty;
tokenIsString = false;
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (quoteMode)
token += aJson[i];
break;
case '\\':
++i;
if (quoteMode)
{
char c = aJson[i];
switch (c)
{
case 't':
token += '\t';
break;
case 'r':
token += '\r';
break;
case 'n':
token += '\n';
break;
case 'b':
token += '\b';
break;
case 'f':
token += '\f';
break;
case 'u':
{
string s = aJson.Substring(i + 1, 4);
token += (char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default:
token += c;
break;
}
}
break;
default:
token += aJson[i];
break;
}
++i;
}
if (quoteMode)
{
throw new Exception("Json Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter)
{
}
public void SaveToStream(System.IO.Stream aData)
{
var w = new System.IO.BinaryWriter(aData);
this.Serialize(w);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJson");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJson");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJson");
}
#endif
public void SaveToFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using (var F = System.IO.File.OpenWrite(aFileName))
{
SaveToStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
this.SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JsonNode Deserialize(System.IO.BinaryReader aReader)
{
JsonBinaryTag type = (JsonBinaryTag)aReader.ReadByte();
switch (type)
{
case JsonBinaryTag.Array:
{
int count = aReader.ReadInt32();
JsonArray tmp = new JsonArray();
for (int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JsonBinaryTag.Class:
{
int count = aReader.ReadInt32();
JsonClass tmp = new JsonClass();
for (int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JsonBinaryTag.Value:
{
return new JsonData(aReader.ReadString());
}
case JsonBinaryTag.IntValue:
{
return new JsonData(aReader.ReadInt32());
}
case JsonBinaryTag.DoubleValue:
{
return new JsonData(aReader.ReadDouble());
}
case JsonBinaryTag.BoolValue:
{
return new JsonData(aReader.ReadBoolean());
}
case JsonBinaryTag.FloatValue:
{
return new JsonData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing Json. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JsonNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JsonNode LoadFromCompressedFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JsonNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JsonNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJson");
}
public static JsonNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJson");
}
public static JsonNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJson");
}
#endif
public static JsonNode LoadFromStream(System.IO.Stream aData)
{
using (var r = new System.IO.BinaryReader(aData))
{
return Deserialize(r);
}
}
public static JsonNode LoadFromFile(string aFileName)
{
#if USE_FileIO
using (var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JsonNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
}
// End of JsonNode
internal class JsonArray : JsonNode, IEnumerable, IList
{
private List<JsonNode> list = new List<JsonNode>();
public override JsonNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= this.list.Count)
return null;
return this.list[aIndex];
}
set
{
if (aIndex < 0 || aIndex >= this.list.Count)
this.list.Add(value);
else
this.list[aIndex] = value;
}
}
public override JsonNode this[string aKey]
{
get { return new JsonLazyCreator(this); }
set { this.list.Add(value); }
}
public override int Count
{
get { return this.list.Count; }
}
public override void Add(string aKey, JsonNode aItem)
{
this.list.Add(aItem);
}
public override JsonNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= this.list.Count)
return null;
JsonNode tmp = this.list[aIndex];
this.list.RemoveAt(aIndex);
return tmp;
}
public override JsonNode Remove(JsonNode aNode)
{
this.list.Remove(aNode);
return aNode;
}
public override IEnumerable<JsonNode> Children
{
get
{
foreach (JsonNode n in this.list)
yield return n;
}
}
public IEnumerator GetEnumerator()
{
foreach (JsonNode n in this.list)
yield return n;
}
public override string ToString()
{
string result = "[ ";
foreach (JsonNode n in this.list)
{
if (result.Length > 2)
result += ", ";
result += n.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JsonNode n in this.list)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += n.ToString(aPrefix + " ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override string ToJson(int prefix)
{
string s = new string(' ', (prefix + 1) * 2);
string ret = "[ ";
foreach (JsonNode n in this.list)
{
if (ret.Length > 3)
ret += ", ";
ret += "\n" + s;
ret += n.ToJson(prefix + 1);
}
ret += "\n" + s + "]";
return ret;
}
public override void Serialize(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JsonBinaryTag.Array);
aWriter.Write(this.list.Count);
for (int i = 0; i < this.list.Count; i++)
{
this.list[i].Serialize(aWriter);
}
}
public int Add(object value)
{
if (!(value is JsonNode))
return -1;
this.list.Add(value as JsonNode);
return this.list.Count - 1;
}
public bool Contains(object value)
{
return this.list.Any(o => o == value);
}
public void Clear()
{
this.list.Clear();
}
public int IndexOf(object value)
{
if (!(value is JsonNode))
return -1;
return this.list.IndexOf(value as JsonNode);
}
public void Insert(int index, object value)
{
this.list.Insert(index, (JsonNode)value);
}
public void Remove(object value)
{
this.list.Remove((JsonNode)value);
}
public void RemoveAt(int index)
{
this.list.RemoveAt(index);
}
public void CopyTo(Array array, int index)
{
JsonNode[] nodes = new JsonNode[array.Length];
for (int i = 0; i < array.Length; i++)
{
nodes[i] = (JsonNode)array.GetValue(i);
}
this.list.CopyTo(nodes, index);
}
public bool IsReadOnly => true;
public bool IsFixedSize => false;
public object SyncRoot
{
get
{
return this.list;
}
}
public bool IsSynchronized => false;
object IList.this[int index]
{
get
{
return this.list[index];
}
set
{
this.list[index] = (JsonNode)value;
}
}
}
// End of JsonArray
internal class JsonClass : JsonNode, IEnumerable
{
private Dictionary<string, JsonNode> dict = new Dictionary<string, JsonNode>();
public override JsonNode this[string aKey]
{
get
{
if (this.dict.ContainsKey(aKey))
return this.dict[aKey];
else
return null;
}
set
{
if (this.dict.ContainsKey(aKey))
this.dict[aKey] = value;
else
this.dict.Add(aKey, value);
}
}
public override JsonNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= this.dict.Count)
return null;
return this.dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= this.dict.Count)
return;
string key = this.dict.ElementAt(aIndex).Key;
this.dict[key] = value;
}
}
public override int Count
{
get { return this.dict.Count; }
}
public override void Add(string aKey, JsonNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (this.dict.ContainsKey(aKey))
this.dict[aKey] = aItem;
else
this.dict.Add(aKey, aItem);
}
else
{
this.dict.Add(Guid.NewGuid().ToString(), aItem);
}
}
public override JsonNode Remove(string aKey)
{
if (!this.dict.ContainsKey(aKey))
return null;
JsonNode tmp = this.dict[aKey];
this.dict.Remove(aKey);
return tmp;
}
public override JsonNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= this.dict.Count)
return null;
var item = this.dict.ElementAt(aIndex);
this.dict.Remove(item.Key);
return item.Value;
}
public override JsonNode Remove(JsonNode aNode)
{
try
{
var item = this.dict.Where(k => k.Value == aNode).First();
this.dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JsonNode> Children
{
get
{
foreach (KeyValuePair<string, JsonNode> n in this.dict)
yield return n.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach (KeyValuePair<string, JsonNode> n in this.dict)
yield return n;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JsonNode> n in this.dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(n.Key) + "\":" + (n.Value?.ToString() ?? "\"\"");
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JsonNode> n in this.dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(n.Key) + "\" : " + n.Value.ToString(aPrefix + " ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override string ToJson(int prefix)
{
string s = new string(' ', (prefix + 1) * 2);
string ret = "{ ";
foreach (KeyValuePair<string, JsonNode> n in this.dict)
{
if (ret.Length > 3)
ret += ", ";
ret += "\n" + s;
ret += string.Format("\"{0}\": {1}", n.Key, n.Value.ToJson(prefix + 1));
}
ret += "\n" + s + "}";
return ret;
}
public override void Serialize(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JsonBinaryTag.Class);
aWriter.Write(this.dict.Count);
foreach (string k in this.dict.Keys)
{
aWriter.Write(k);
this.dict[k].Serialize(aWriter);
}
}
}
// End of JsonClass
internal class JsonData : JsonNode
{
private string data;
public override string Value
{
get
{
return this.data;
}
set
{
this.data = value;
this.Tag = JsonBinaryTag.Value;
}
}
public JsonData(string aData)
{
this.data = aData;
this.Tag = JsonBinaryTag.Value;
}
public JsonData(float aData)
{
this.AsFloat = aData;
}
public JsonData(double aData)
{
this.AsDouble = aData;
}
public JsonData(bool aData)
{
this.AsBool = aData;
}
public JsonData(int aData)
{
this.AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(this.data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(this.data) + "\"";
}
public override string ToJson(int prefix)
{
switch (this.Tag)
{
case JsonBinaryTag.DoubleValue:
case JsonBinaryTag.FloatValue:
case JsonBinaryTag.IntValue:
return this.data;
case JsonBinaryTag.Value:
return string.Format("\"{0}\"", Escape(this.data));
default:
throw new NotSupportedException("This shouldn't be here: " + this.Tag.ToString());
}
}
public override void Serialize(System.IO.BinaryWriter aWriter)
{
var tmp = new JsonData(string.Empty);
tmp.AsInt = this.AsInt;
if (tmp.data == this.data)
{
aWriter.Write((byte)JsonBinaryTag.IntValue);
aWriter.Write(this.AsInt);
return;
}
tmp.AsFloat = this.AsFloat;
if (tmp.data == this.data)
{
aWriter.Write((byte)JsonBinaryTag.FloatValue);
aWriter.Write(this.AsFloat);
return;
}
tmp.AsDouble = this.AsDouble;
if (tmp.data == this.data)
{
aWriter.Write((byte)JsonBinaryTag.DoubleValue);
aWriter.Write(this.AsDouble);
return;
}
tmp.AsBool = this.AsBool;
if (tmp.data == this.data)
{
aWriter.Write((byte)JsonBinaryTag.BoolValue);
aWriter.Write(this.AsBool);
return;
}
aWriter.Write((byte)JsonBinaryTag.Value);
aWriter.Write(this.data);
}
}
// End of JsonData
internal class JsonLazyCreator : JsonNode
{
private JsonNode node = null;
private string key = null;
public JsonLazyCreator(JsonNode aNode)
{
this.node = aNode;
this.key = null;
}
public JsonLazyCreator(JsonNode aNode, string aKey)
{
this.node = aNode;
this.key = aKey;
}
private void Set(JsonNode aVal)
{
if (this.key == null)
{
this.node.Add(aVal);
}
else
{
this.node.Add(this.key, aVal);
}
this.node = null; // Be GC friendly.
}
public override JsonNode this[int aIndex]
{
get
{
return new JsonLazyCreator(this);
}
set
{
var tmp = new JsonArray();
tmp.Add(value);
this.Set(tmp);
}
}
public override JsonNode this[string aKey]
{
get
{
return new JsonLazyCreator(this, aKey);
}
set
{
var tmp = new JsonClass();
tmp.Add(aKey, value);
this.Set(tmp);
}
}
public override void Add(JsonNode aItem)
{
var tmp = new JsonArray();
tmp.Add(aItem);
this.Set(tmp);
}
public override void Add(string aKey, JsonNode aItem)
{
var tmp = new JsonClass();
tmp.Add(aKey, aItem);
this.Set(tmp);
}
public static bool operator ==(JsonLazyCreator a, object b)
{
if (b == null)
return true;
return object.ReferenceEquals(a, b);
}
public static bool operator !=(JsonLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (obj == null)
return true;
return object.ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
return string.Empty;
}
public override string ToString(string aPrefix)
{
return string.Empty;
}
public override string ToJson(int prefix)
{
return string.Empty;
}
public override int AsInt
{
get
{
JsonData tmp = new JsonData(0);
this.Set(tmp);
return 0;
}
set
{
JsonData tmp = new JsonData(value);
this.Set(tmp);
}
}
public override float AsFloat
{
get
{
JsonData tmp = new JsonData(0.0f);
this.Set(tmp);
return 0.0f;
}
set
{
JsonData tmp = new JsonData(value);
this.Set(tmp);
}
}
public override double AsDouble
{
get
{
JsonData tmp = new JsonData(0.0);
this.Set(tmp);
return 0.0;
}
set
{
JsonData tmp = new JsonData(value);
this.Set(tmp);
}
}
public override bool AsBool
{
get
{
JsonData tmp = new JsonData(false);
this.Set(tmp);
return false;
}
set
{
JsonData tmp = new JsonData(value);
this.Set(tmp);
}
}
public override JsonArray AsArray
{
get
{
JsonArray tmp = new JsonArray();
this.Set(tmp);
return tmp;
}
}
public override JsonClass AsObject
{
get
{
JsonClass tmp = new JsonClass();
this.Set(tmp);
return tmp;
}
}
}
// End of JsonLazyCreator
internal static class Json
{
public static JsonNode Parse(string aJson)
{
return JsonNode.Parse(aJson);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/9/2009 5:59:10 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using DotSpatial.Data;
using GeoAPI.Geometries;
namespace DotSpatial.Symbology
{
/// <summary>
/// Group
/// </summary>
public class Group : Layer, IGroup
{
#region Events
/// <summary>
/// This occurs when a new layer is added either to this group, or one of the child groups within this group.
/// </summary>
public event EventHandler<LayerEventArgs> LayerAdded;
/// <summary>
/// This occurs when a layer is removed from this group.
/// </summary>
public event EventHandler<LayerEventArgs> LayerRemoved;
#endregion
#region Private Variables
private int _handle;
private Image _image;
private ILayerCollection _layers;
//private ILegend _legend;
private IGroup _parentGroup;
private bool _selectionEnabled;
private bool _stateLocked;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of Group
/// </summary>
public Group()
{
Configure();
}
/// <summary>
/// Creates a group that sits in a layer list and uses the specified progress handler
/// </summary>
/// <param name="frame"></param>
/// <param name="progressHandler">the progress handler</param>
public Group(IFrame frame, IProgressHandler progressHandler)
: base(progressHandler)
{
MapFrame = frame;
Configure();
}
/// <summary>
/// Creates a group that sits in a layer list and uses the specified progress handler
/// </summary>
/// <param name="container">the layer list</param>
/// <param name="frame"></param>
/// <param name="progressHandler">the progress handler</param>
public Group(ICollection<ILayer> container, IFrame frame, IProgressHandler progressHandler)
: base(container, progressHandler)
{
MapFrame = frame;
Configure();
}
private void Configure()
{
Layers = new LayerCollection(MapFrame, this);
_stateLocked = false;
IsDragable = true;
base.IsExpanded = true;
ContextMenuItems = new List<SymbologyMenuItem>();
ContextMenuItems.Add(new SymbologyMenuItem("Remove Group", Remove_Click));
ContextMenuItems.Add(new SymbologyMenuItem("Zoom to Group", (sender, args) => ZoomToGroup()));
ContextMenuItems.Add(new SymbologyMenuItem("Create new Group", CreateGroupClick));
_selectionEnabled = true;
}
#endregion
#region Methods
/// <inheritdoc />
public virtual void Add(ILayer layer)
{
_layers.Add(layer);
}
/// <inheritdoc />
public virtual bool Remove(ILayer layer)
{
return _layers.Remove(layer);
}
/// <inheritdoc />
public virtual void Insert(int index, ILayer layer)
{
_layers.Insert(index, layer);
}
/// <inheritdoc />
public override Size GetLegendSymbolSize()
{
return new Size(16, 16);
}
/// <inheritdoc />
public override bool CanReceiveItem(ILegendItem item)
{
ILayer lyr = item as ILayer;
if (lyr != null)
{
if (lyr != this) return true; // don't allow groups to add to themselves
}
return false;
}
/// <inheritdoc />
public Bitmap LegendSnapShot(int imgWidth)
{
//bool TO_DO_GROUP_LEGEND_SNAPSHOT;
//return new Bitmap(100, 100);
throw new NotImplementedException();
}
/// <inheritdoc />
public override void Invalidate(Extent region)
{
foreach (ILayer layer in GetLayers())
{
layer.Invalidate(region);
}
}
/// <inheritdoc />
public override void Invalidate()
{
foreach (ILayer layer in GetLayers())
{
layer.Invalidate();
}
}
/// <inheritdoc />
public override bool ClearSelection(out Envelope affectedAreas)
{
affectedAreas = new Envelope();
bool changed = false;
if (!_selectionEnabled) return false;
MapFrame.SuspendEvents();
foreach (ILayer layer in GetLayers())
{
Envelope layerArea;
if (layer.ClearSelection(out layerArea)) changed = true;
affectedAreas.ExpandToInclude(layerArea);
}
MapFrame.ResumeEvents();
OnSelectionChanged(); // fires only AFTER the individual layers have fired their events.
return changed;
}
/// <inheritdoc />
public override bool Select(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
{
affectedArea = new Envelope();
if (!_selectionEnabled) return false;
bool somethingChanged = false;
MapFrame.SuspendEvents();
foreach (var s in GetLayers()
.Reverse()
.Where(_ => _.SelectionEnabled && _.IsVisible))
{
Envelope layerArea;
if (s.Select(tolerant, strict, mode, out layerArea)) somethingChanged = true;
affectedArea.ExpandToInclude(layerArea);
// removed by jany_: this selected only features of the first layer with features in the selected area, if user wanted to select features of another layer too they get ignored
// added SelectPlugin enables user to choose the layers in which he wants to select features
//if (somethingChanged)
//{
// MapFrame.ResumeEvents();
// OnSelectionChanged(); // fires only AFTER the individual layers have fired their events.
// return somethingChanged;
//}
}
MapFrame.ResumeEvents();
OnSelectionChanged(); // fires only AFTER the individual layers have fired their events.
return somethingChanged;
}
/// <inheritdoc />
public virtual IList<ILayer> GetLayers()
{
return _layers.ToList();
}
/// <inheritdoc />
public int GetLayerCount(bool recursive)
{
// if this is not overridden, this just looks at the Layers collection
int count = 0;
IList<ILayer> layers = GetLayers();
foreach (ILayer item in layers)
{
IGroup grp = item as IGroup;
if (grp != null)
{
if (recursive) count += grp.GetLayerCount(true);
}
else
{
count++;
}
}
return count;
}
/// <inheritdoc />
public override bool InvertSelection(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
{
affectedArea = new Envelope();
if (!_selectionEnabled) return false;
bool somethingChanged = false;
MapFrame.SuspendEvents();
foreach (ILayer s in GetLayers())
{
if (s.SelectionEnabled == false) continue;
Envelope layerArea;
if (s.InvertSelection(tolerant, strict, mode, out layerArea)) somethingChanged = true;
affectedArea.ExpandToInclude(layerArea);
}
MapFrame.ResumeEvents();
OnSelectionChanged(); // fires only AFTER the individual layers have fired their events.
return somethingChanged;
}
/// <inheritdoc />
public override bool UnSelect(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
{
affectedArea = new Envelope();
if (!_selectionEnabled) return false;
bool somethingChanged = false;
SuspendEvents();
foreach (ILayer s in GetLayers())
{
Envelope layerArea;
if (s.UnSelect(tolerant, strict, mode, out layerArea)) somethingChanged = true;
affectedArea.ExpandToInclude(layerArea);
}
ResumeEvents();
OnSelectionChanged(); // fires only AFTER the individual layers have fired their events.
return somethingChanged;
}
/// <inheritdoc />
public virtual void SuspendEvents()
{
_layers.SuspendEvents();
}
/// <inheritdoc />
public virtual void ResumeEvents()
{
_layers.ResumeEvents();
}
/// <inheritdoc />
public virtual bool EventsSuspended
{
get { return _layers.EventsSuspended; }
}
#endregion
#region Properties
/// <summary>
/// gets or sets the list of layers.
/// </summary>
[ShallowCopy]
protected ILayerCollection Layers
{
get
{
return _layers;
}
set
{
if (Layers != null)
{
Ignore_Layer_Events(_layers);
}
_layers = value;
if (_layers != null)
{
Handle_Layer_Events(value);
_layers.ParentGroup = this;
_layers.MapFrame = MapFrame;
}
}
}
/// <summary>
/// Boolean, true if any sub-layers in the group are visible. Setting this
/// will force all the layers in this group to become visible.
/// </summary>
public override bool IsVisible
{
get { return GetLayers().Any(lyr => lyr.IsVisible); }
set
{
foreach (var lyr in GetLayers())
{
lyr.IsVisible = value;
}
base.IsVisible = value;
}
}
/// <summary>
/// The envelope that contains all of the layers for this data frame. Essentially this would be
/// the extents to use if you want to zoom to the world view.
/// </summary>
public override Extent Extent
{
get
{
var layers = GetLayers();
if (layers == null) return null;
Extent ext = null;
foreach (var extent in layers
.Select(layer => layer.Extent)
.Where(extent => extent != null && !extent.IsEmpty()) // changed by jany (2015-07-17) don't add extents of empty layers, because they cause a wrong overall extent
)
{
if (ext == null)
ext = (Extent)extent.Clone();
else
ext.ExpandToInclude(extent);
}
return ext;
}
}
/// <summary>
/// Gets the integer handle for this group
/// </summary>
public int Handle
{
get { return _handle; }
protected set { _handle = value; }
}
/// <summary>
/// Gets or sets the icon
/// </summary>
public Image Icon
{
get { return _image; }
set { _image = value; }
}
/// <summary>
/// Gets the currently invalidated region as a union of all the
/// invalidated regions of individual layers in this group.
/// </summary>
public override Extent InvalidRegion
{
get
{
Extent result = new Extent();
foreach (ILayer lyr in GetLayers())
{
if (lyr.InvalidRegion != null) result.ExpandToInclude(lyr.InvalidRegion);
}
return result;
}
}
/// <summary>
/// Gets the layer handle of the specified layer
/// </summary>
/// <param name="positionInGroup">0 based index into list of layers</param>
/// <returns>Layer's handle on success, -1 on failure</returns>
public int LayerHandle(int positionInGroup)
{
throw new NotSupportedException();
}
/// <summary>
/// Returns the count of the layers that are currently stored in this map frame.
/// </summary>
public int LayerCount
{
get { return _layers.Count; }
}
/// <summary>
/// Gets a boolean that is true if any of the immediate layers or groups contained within this
/// control are visible. Setting this will set the visibility for each of the members of this
/// map frame.
/// </summary>
public bool LayersVisible
{
get { return GetLayers().Any(layer => layer.IsVisible); }
set
{
foreach (var layer in GetLayers())
{
layer.IsVisible = value;
}
}
}
/// <summary>
/// This is a different view of the layers cast as legend items. This allows
/// easier cycling in recursive legend code.
/// </summary>
public override IEnumerable<ILegendItem> LegendItems
{
get
{
return _layers;
}
}
/// <summary>
/// Gets the parent group of this group.
/// </summary>
public IGroup ParentGroup
{
get { return _parentGroup; }
protected set { _parentGroup = value; }
}
/// <summary>
/// Gets or sets the progress handler to use. Setting this will set the progress handler for
/// each of the layers in this map frame.
/// </summary>
public override IProgressHandler ProgressHandler
{
get { return base.ProgressHandler; }
set
{
base.ProgressHandler = value;
foreach (ILayer layer in GetLayers())
{
layer.ProgressHandler = value;
}
}
}
/// <summary>
/// gets or sets the locked property, which prevents the user from changing the visual state
/// except layer by layer
/// </summary>
public bool StateLocked
{
get { return _stateLocked; }
set { _stateLocked = value; }
}
#endregion
#region Private Methods
private void Remove_Click(object sender, EventArgs e)
{
OnRemoveItem();
}
/// <summary>
/// Zoom to group
/// </summary>
internal void ZoomToGroup()
{
var extent = Extent;
if (extent != null)
{
OnZoomToLayer(extent.ToEnvelope());
}
}
private void CreateGroupClick(object sender, EventArgs e)
{
OnCreateGroup();
}
/// <summary>
/// Creates a virtual method when sub-groups are being created
/// </summary>
protected virtual void OnCreateGroup()
{
Group grp = new Group(Layers, MapFrame, ProgressHandler);
grp.LegendText = "New Group";
}
private void LayersItemChanged(object sender, EventArgs e)
{
OnItemChanged(sender);
}
private void LayersLayerVisibleChanged(object sender, EventArgs e)
{
OnVisibleChanged(sender, e);
}
private void Layers_ZoomToLayer(object sender, EnvelopeArgs e)
{
OnZoomToLayer(e.Envelope);
}
/// <summary>
/// Given a new LayerCollection, we need to be sensitive to certain events
/// </summary>
protected virtual void Handle_Layer_Events(ILayerEvents collection)
{
if (collection == null) return;
collection.LayerVisibleChanged += LayersLayerVisibleChanged;
collection.ItemChanged += LayersItemChanged;
collection.ZoomToLayer += Layers_ZoomToLayer;
collection.SelectionChanging += collection_SelectionChanging;
collection.LayerSelected += collection_LayerSelected;
collection.LayerAdded += Layers_LayerAdded;
collection.LayerRemoved += Layers_LayerRemoved;
collection.SelectionChanged += collection_SelectionChanged;
}
private void collection_LayerSelected(object sender, LayerSelectedEventArgs e)
{
OnLayerSelected(e.Layer, e.IsSelected);
}
private void collection_SelectionChanging(object sender, FeatureLayerSelectionEventArgs e)
{
OnSelectionChanged();
}
private void collection_SelectionChanged(object sender, EventArgs e)
{
OnSelectionChanged();
}
private void Layers_LayerRemoved(object sender, LayerEventArgs e)
{
OnLayerRemoved(sender, e);
}
/// <summary>
/// Occurs when removing a layer. This also fires the LayerRemoved event.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected virtual void OnLayerRemoved(object sender, LayerEventArgs e)
{
if (LayerRemoved != null) LayerRemoved(sender, e);
}
private void Layers_LayerAdded(object sender, LayerEventArgs e)
{
OnLayerAdded(sender, e);
}
/// <summary>
/// Simply echo this event out to members above this group that might be listening to it.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected virtual void OnLayerAdded(object sender, LayerEventArgs e)
{
if (LayerAdded != null) LayerAdded(sender, e);
}
/// <summary>
/// When setting an old layer collection it is advisable to not only add
/// new handlers to the new collection, but remove the handlers related
/// to the old collection.
/// </summary>
/// <param name="collection"></param>
protected virtual void Ignore_Layer_Events(ILayerEvents collection)
{
if (collection == null) return;
collection.LayerVisibleChanged -= LayersLayerVisibleChanged;
collection.ItemChanged -= LayersItemChanged;
collection.ZoomToLayer -= Layers_ZoomToLayer;
collection.SelectionChanging -= collection_SelectionChanging;
collection.LayerSelected -= collection_LayerSelected;
collection.LayerAdded -= Layers_LayerAdded;
collection.LayerRemoved -= Layers_LayerRemoved;
collection.SelectionChanged -= collection_SelectionChanged;
}
/// <summary>
/// Disposes the unmanaged resourced of this group. If disposeManagedResources is true, then this will
/// also dispose the resources of the child layers and groups unless they are dispose locked.
/// </summary>
/// <param name="disposeManagedResources">Boolean, true to dispose child objects and set managed members to null.</param>
protected override void Dispose(bool disposeManagedResources)
{
if (disposeManagedResources)
{
_parentGroup = null;
if (_layers != null)
{
_layers.Dispose();
}
}
if (_image != null)
{
_image.Dispose();
}
base.Dispose(disposeManagedResources);
}
#endregion
#region IGroup Members
/// <inheritdoc />
public virtual int IndexOf(ILayer item)
{
return _layers.IndexOf(item);
}
/// <inheritdoc />
public virtual void RemoveAt(int index)
{
_layers.RemoveAt(index);
}
/// <inheritdoc />
public virtual ILayer this[int index]
{
get
{
return _layers[index];
}
set
{
_layers[index] = value;
}
}
/// <inheritdoc />
public virtual void Clear()
{
_layers.Clear();
}
/// <inheritdoc />
public virtual bool Contains(ILayer item)
{
return _layers.Contains(item);
}
/// <inheritdoc />
public virtual void CopyTo(ILayer[] array, int arrayIndex)
{
_layers.CopyTo(array, arrayIndex);
}
/// <inheritdoc />
public virtual int Count
{
get { return _layers.Count; }
}
/// <inheritdoc />
public virtual bool IsReadOnly
{
get { return _layers.IsReadOnly; }
}
/// <inheritdoc />
public virtual IEnumerator<ILayer> GetEnumerator()
{
return _layers.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _layers.GetEnumerator();
}
#endregion
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Dynamic;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Actions.Calls;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime.Binding {
using Ast = Expression;
using AstUtils = Microsoft.Scripting.Ast.Utils;
class MetaPythonFunction : MetaPythonObject, IPythonInvokable, IPythonOperable, IPythonConvertible, IInferableInvokable, IConvertibleMetaObject, IPythonGetable {
public MetaPythonFunction(Expression/*!*/ expression, BindingRestrictions/*!*/ restrictions, PythonFunction/*!*/ value)
: base(expression, BindingRestrictions.Empty, value) {
Assert.NotNull(value);
}
#region IPythonInvokable Members
public DynamicMetaObject/*!*/ Invoke(PythonInvokeBinder/*!*/ pythonInvoke, Expression/*!*/ codeContext, DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args) {
return new FunctionBinderHelper(pythonInvoke, this, codeContext, args).MakeMetaObject();
}
#endregion
#region IPythonGetable Members
public DynamicMetaObject GetMember(PythonGetMemberBinder member, DynamicMetaObject codeContext) {
return BindGetMemberWorker(member, member.Name, codeContext);
}
#endregion
#region MetaObject Overrides
public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
ParameterExpression tmp = Expression.Parameter(typeof(object));
// first get the default binder value
DynamicMetaObject fallback = action.FallbackInvokeMember(this, args);
// then fallback w/ an error suggestion that does a late bound lookup.
return action.FallbackInvokeMember(
this,
args,
new DynamicMetaObject(
Ast.Block(
new[] { tmp },
Ast.Condition(
Ast.NotEqual(
Ast.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("PythonFunctionGetMember"),
AstUtils.Convert(
Expression,
typeof(PythonFunction)
),
Expression.Constant(action.Name)
)
),
Ast.Constant(OperationFailed.Value)
),
action.FallbackInvoke(
new DynamicMetaObject(tmp, BindingRestrictions.Empty),
args,
null
).Expression,
AstUtils.Convert(fallback.Expression, typeof(object))
)
),
BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)).Merge(fallback.Restrictions)
)
);
}
public override DynamicMetaObject/*!*/ BindInvoke(InvokeBinder/*!*/ call, params DynamicMetaObject/*!*/[]/*!*/ args) {
return new FunctionBinderHelper(call, this, null, args).MakeMetaObject();
}
public override DynamicMetaObject BindConvert(ConvertBinder/*!*/ conversion) {
return ConvertWorker(conversion, conversion.Type, conversion.Explicit ? ConversionResultKind.ExplicitCast : ConversionResultKind.ImplicitCast);
}
public DynamicMetaObject BindConvert(PythonConversionBinder binder) {
return ConvertWorker(binder, binder.Type, binder.ResultKind);
}
public DynamicMetaObject ConvertWorker(DynamicMetaObjectBinder binder, Type type, ConversionResultKind kind) {
if (type.IsSubclassOf(typeof(Delegate))) {
return MakeDelegateTarget(binder, type, Restrict(typeof(PythonFunction)));
}
return FallbackConvert(binder);
}
public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() {
foreach (object o in Value.__dict__.Keys) {
if (o is string) {
yield return (string)o;
}
}
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder) {
return BindGetMemberWorker(binder, binder.Name, PythonContext.GetCodeContextMO(binder));
}
private DynamicMetaObject BindGetMemberWorker(DynamicMetaObjectBinder binder, string name, DynamicMetaObject codeContext) {
ParameterExpression tmp = Expression.Parameter(typeof(object));
// first get the default binder value
DynamicMetaObject fallback = FallbackGetMember(binder, this, codeContext);
// then fallback w/ an error suggestion that does a late bound lookup.
return FallbackGetMember(
binder,
this,
codeContext,
new DynamicMetaObject(
Ast.Block(
new[] { tmp },
Ast.Condition(
Ast.NotEqual(
Ast.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("PythonFunctionGetMember"),
AstUtils.Convert(
Expression,
typeof(PythonFunction)
),
Expression.Constant(name)
)
),
Ast.Constant(OperationFailed.Value)
),
tmp,
AstUtils.Convert(fallback.Expression, typeof(object))
)
),
BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)).Merge(fallback.Restrictions)
)
);
}
private static DynamicMetaObject FallbackGetMember(DynamicMetaObjectBinder binder, DynamicMetaObject self, DynamicMetaObject codeContext) {
return FallbackGetMember(binder, self, codeContext, null);
}
private static DynamicMetaObject FallbackGetMember(DynamicMetaObjectBinder binder, DynamicMetaObject self, DynamicMetaObject codeContext, DynamicMetaObject errorSuggestion) {
PythonGetMemberBinder pyGetMem = binder as PythonGetMemberBinder;
if (pyGetMem != null) {
return pyGetMem.Fallback(self, codeContext, errorSuggestion);
}
return ((GetMemberBinder)binder).FallbackGetMember(self, errorSuggestion);
}
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) {
// fallback w/ an error suggestion that does a late bound set
return binder.FallbackSetMember(
this,
value,
new DynamicMetaObject(
Ast.Call(
typeof(PythonOps).GetMethod("PythonFunctionSetMember"),
AstUtils.Convert(
Expression,
typeof(PythonFunction)
),
Expression.Constant(binder.Name),
AstUtils.Convert(
value.Expression,
typeof(object)
)
),
BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction))
)
);
}
public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) {
switch (binder.Name) {
case "__dict__":
return new DynamicMetaObject(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.PythonFunctionDeleteDict))
),
BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction))
);
case "__doc__":
return new DynamicMetaObject(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.PythonFunctionDeleteDoc)),
Expression.Convert(Expression, typeof(PythonFunction))
),
BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction))
);
case "__defaults__":
return new DynamicMetaObject(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.PythonFunctionDeleteDefaults)),
Expression.Convert(Expression, typeof(PythonFunction))
),
BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction))
);
}
// first get the default binder value
DynamicMetaObject fallback = binder.FallbackDeleteMember(this);
// then fallback w/ an error suggestion that does a late bound delete
return binder.FallbackDeleteMember(
this,
new DynamicMetaObject(
Expression.Condition(
Ast.Call(
typeof(PythonOps).GetMethod("PythonFunctionDeleteMember"),
AstUtils.Convert(
Expression,
typeof(PythonFunction)
),
Expression.Constant(binder.Name)
),
Expression.Default(typeof(void)), // we deleted the member
AstUtils.Convert(
fallback.Expression, // report language specific error,
typeof(void)
)
),
BindingRestrictions.GetTypeRestriction(Expression, typeof(PythonFunction)).Merge(fallback.Restrictions)
)
);
}
#endregion
#region Calls
/// <summary>
/// Performs the actual work of binding to the function.
///
/// Overall this works by going through the arguments and attempting to bind all the outstanding known
/// arguments - position arguments and named arguments which map to parameters are easy and handled
/// in the 1st pass for GetArgumentsForRule. We also pick up any extra named or position arguments which
/// will need to be passed off to a kw argument or a params array.
///
/// After all the normal args have been assigned to do a 2nd pass in FinishArguments. Here we assign
/// a value to either a value from the params list, kw-dict, or defaults. If there is ambiguity between
/// this (e.g. we have a splatted params list, kw-dict, and defaults) we call a helper which extracts them
/// in the proper order (first try the list, then the dict, then the defaults).
/// </summary>
class FunctionBinderHelper {
private readonly MetaPythonFunction/*!*/ _func; // the meta object for the function we're calling
private readonly DynamicMetaObject/*!*/[]/*!*/ _args; // the arguments for the function
private readonly DynamicMetaObject/*!*/[]/*!*/ _originalArgs; // the original arguments for the function
private readonly DynamicMetaObjectBinder/*!*/ _call; // the signature for the method call
private readonly Expression _codeContext; // the code context expression if one is available.
private List<ParameterExpression>/*!*/ _temps; // temporary variables allocated to create the rule
private ParameterExpression _dict, _params, _paramsLen; // splatted dictionary & params + the initial length of the params array, null if not provided.
private List<Expression> _init; // a set of initialization code (e.g. creating a list for the params array)
private Expression _error; // a custom error expression if the default needs to be overridden.
private bool _extractedParams; // true if we needed to extract a parameter from the parameter list.
private bool _extractedDefault; // true if we needed to extract a parameter from the kw list.
private bool _needCodeTest; // true if we need to test the code object
private Expression _deferTest; // non-null if we have a test which could fail at runtime and we need to fallback to deferal
private Expression _userProvidedParams; // expression the user provided that should be expanded for params.
private Expression _paramlessCheck; // tests when we have no parameters
public FunctionBinderHelper(DynamicMetaObjectBinder/*!*/ call, MetaPythonFunction/*!*/ function, Expression codeContext, DynamicMetaObject/*!*/[]/*!*/ args) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "PythonFunction Invoke " + function.Value.FunctionCompatibility + " w/ " + args.Length + " args");
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "PythonFunction");
_call = call;
_func = function;
_args = args;
_originalArgs = args;
_temps = new List<ParameterExpression>();
_codeContext = codeContext;
// Remove the passed in instance argument if present
int instanceIndex = Signature.IndexOf(ArgumentType.Instance);
if (instanceIndex > -1) {
_args = ArrayUtils.RemoveAt(_args, instanceIndex);
}
}
public DynamicMetaObject/*!*/ MakeMetaObject() {
Expression[] invokeArgs = GetArgumentsForRule();
BindingRestrictions restrict = _func.Restrictions.Merge(GetRestrictions().Merge(BindingRestrictions.Combine(_args)));
DynamicMetaObject res;
if (invokeArgs != null) {
// successful call
Expression target = AddInitialization(MakeFunctionInvoke(invokeArgs));
if (_temps.Count > 0) {
target = Ast.Block(
_temps,
target
);
}
res = new DynamicMetaObject(
target,
restrict
);
} else if (_error != null) {
// custom error generated while figuring out the call
res = new DynamicMetaObject(_error, restrict);
} else {
// generic error
res = new DynamicMetaObject(
_call.Throw(
Ast.Call(
typeof(PythonOps).GetMethod(Signature.HasKeywordArgument() ? "BadKeywordArgumentError" : "FunctionBadArgumentError"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)),
AstUtils.Constant(Signature.GetProvidedPositionalArgumentCount())
),
typeof(object)
),
restrict
);
}
DynamicMetaObject[] deferArgs = ArrayUtils.Insert(_func, _originalArgs);
if (_codeContext != null) {
deferArgs = ArrayUtils.Insert(new DynamicMetaObject(_codeContext, BindingRestrictions.Empty), deferArgs);
}
return BindingHelpers.AddDynamicTestAndDefer(
_call,
res,
deferArgs,
new ValidationInfo(_deferTest),
res.Expression.Type // force defer to our return type, our restrictions guarantee this to be true (only defaults can change, and we restrict to the delegate type)
);
}
private CallSignature Signature {
get {
return BindingHelpers.GetCallSignature(_call);
}
}
/// <summary>
/// Makes the test for our rule.
/// </summary>
private BindingRestrictions/*!*/ GetRestrictions() {
if (!Signature.HasKeywordArgument()) {
return GetSimpleRestriction();
}
return GetComplexRestriction();
}
/// <summary>
/// Makes the test when we just have simple positional arguments.
/// </summary>
private BindingRestrictions/*!*/ GetSimpleRestriction() {
_deferTest = Ast.Equal(
Ast.Call(
typeof(PythonOps).GetMethod("FunctionGetCompatibility"),
Ast.Convert(_func.Expression, typeof(PythonFunction))
),
AstUtils.Constant(_func.Value.FunctionCompatibility)
);
return BindingRestrictionsHelpers.GetRuntimeTypeRestriction(
_func.Expression, typeof(PythonFunction)
);
}
/// <summary>
/// Makes the test when we have a keyword argument call or splatting.
/// </summary>
/// <returns></returns>
private BindingRestrictions/*!*/ GetComplexRestriction() {
if (_extractedDefault) {
return BindingRestrictions.GetInstanceRestriction(_func.Expression, _func.Value);
} else if (_needCodeTest) {
return GetSimpleRestriction().Merge(
BindingRestrictions.GetInstanceRestriction(
Expression.Property(
GetFunctionParam(),
"__code__"
),
_func.Value.__code__
)
);
}
return GetSimpleRestriction();
}
/// <summary>
/// Gets the array of expressions which correspond to each argument for the function. These
/// correspond with the function as it's defined in Python and must be transformed for our
/// delegate type before being used.
/// </summary>
private Expression/*!*/[]/*!*/ GetArgumentsForRule() {
Expression[] exprArgs = new Expression[_func.Value.NormalArgumentCount + _func.Value.ExtraArguments];
List<Expression> extraArgs = null;
Dictionary<string, Expression> namedArgs = null;
int instanceIndex = Signature.IndexOf(ArgumentType.Instance);
// walk all the provided args and find out where they go...
for (int i = 0; i < _args.Length; i++) {
int parameterIndex = (instanceIndex == -1 || i < instanceIndex) ? i : i + 1;
switch (Signature.GetArgumentKind(i)) {
case ArgumentType.Dictionary:
_args[parameterIndex] = MakeDictionaryCopy(_args[parameterIndex]);
continue;
case ArgumentType.List:
_userProvidedParams = _args[parameterIndex].Expression;
continue;
case ArgumentType.Named:
_needCodeTest = true;
bool foundName = false;
for (int j = 0; j < _func.Value.NormalArgumentCount; j++) {
if (_func.Value.ArgNames[j] == Signature.GetArgumentName(i)) {
if (exprArgs[j] != null) {
// kw-argument provided for already provided normal argument.
if (_error == null) {
_error = _call.Throw(
Expression.Call(
typeof(PythonOps).GetMethod("MultipleKeywordArgumentError"),
GetFunctionParam(),
Expression.Constant(_func.Value.ArgNames[j])
),
typeof(object)
);
}
return null;
}
exprArgs[j] = _args[parameterIndex].Expression;
foundName = true;
break;
}
}
if (!foundName) {
if (namedArgs == null) {
namedArgs = new Dictionary<string, Expression>();
}
namedArgs[Signature.GetArgumentName(i)] = _args[parameterIndex].Expression;
}
continue;
}
if (i < _func.Value.NormalArgumentCount) {
exprArgs[i] = _args[parameterIndex].Expression;
} else {
if (extraArgs == null) {
extraArgs = new List<Expression>();
}
extraArgs.Add(_args[parameterIndex].Expression);
}
}
if (!FinishArguments(exprArgs, extraArgs, namedArgs)) {
if (namedArgs != null && _func.Value.ExpandDictPosition == -1) {
MakeUnexpectedKeywordError(namedArgs);
}
return null;
}
return GetArgumentsForTargetType(exprArgs);
}
/// <summary>
/// Binds any missing arguments to values from params array, kw dictionary, or default values.
/// </summary>
private bool FinishArguments(Expression[] exprArgs, List<Expression> paramsArgs, Dictionary<string, Expression> namedArgs) {
int noDefaults = _func.Value.NormalArgumentCount - _func.Value.Defaults.Length; // number of args w/o defaults
for (int i = 0; i < _func.Value.NormalArgumentCount; i++) {
if (exprArgs[i] != null) {
if (_userProvidedParams != null && i >= Signature.GetProvidedPositionalArgumentCount()) {
exprArgs[i] = ValidateNotDuplicate(exprArgs[i], _func.Value.ArgNames[i], i);
}
continue;
}
if (i < noDefaults) {
exprArgs[i] = ExtractNonDefaultValue(_func.Value.ArgNames[i]);
if (exprArgs[i] == null) {
// can't get a value, this is an invalid call.
return false;
}
} else {
exprArgs[i] = ExtractDefaultValue(i, i - noDefaults);
}
}
if (!TryFinishList(exprArgs, paramsArgs) ||
!TryFinishDictionary(exprArgs, namedArgs))
return false;
// add check for extra parameters.
AddCheckForNoExtraParameters(exprArgs);
return true;
}
/// <summary>
/// Creates the argument for the list expansion parameter.
/// </summary>
private bool TryFinishList(Expression[] exprArgs, List<Expression> paramsArgs) {
if (_func.Value.ExpandListPosition != -1) {
if (_userProvidedParams != null) {
if (_params == null && paramsArgs == null) {
// we didn't extract any params, we can re-use a Tuple or
// make a single copy.
exprArgs[_func.Value.ExpandListPosition] = Ast.Call(
typeof(PythonOps).GetMethod("GetOrCopyParamsTuple"),
GetFunctionParam(),
AstUtils.Convert(_userProvidedParams, typeof(object))
);
} else {
// user provided a sequence to be expanded, and we may have used it,
// or we have extra args.
EnsureParams();
exprArgs[_func.Value.ExpandListPosition] = Ast.Call(
typeof(PythonOps).GetMethod("MakeTupleFromSequence"),
AstUtils.Convert(_params, typeof(object))
);
if (paramsArgs != null) {
MakeParamsAddition(paramsArgs);
}
}
} else {
exprArgs[_func.Value.ExpandListPosition] = MakeParamsTuple(paramsArgs);
}
} else if (paramsArgs != null) {
// extra position args which are unused and no where to put them.
return false;
}
return true;
}
/// <summary>
/// Adds extra positional arguments to the start of the expanded list.
/// </summary>
private void MakeParamsAddition(List<Expression> paramsArgs) {
_extractedParams = true;
List<Expression> args = new List<Expression>(paramsArgs.Count + 1);
args.Add(_params);
args.AddRange(paramsArgs);
EnsureInit();
_init.Add(
AstUtils.ComplexCallHelper(
typeof(PythonOps).GetMethod("AddParamsArguments"),
args.ToArray()
)
);
}
/// <summary>
/// Creates the argument for the dictionary expansion parameter.
/// </summary>
private bool TryFinishDictionary(Expression[] exprArgs, Dictionary<string, Expression> namedArgs) {
if (_func.Value.ExpandDictPosition != -1) {
if (_dict != null) {
// used provided a dictionary to be expanded
exprArgs[_func.Value.ExpandDictPosition] = _dict;
if (namedArgs != null) {
foreach (KeyValuePair<string, Expression> kvp in namedArgs) {
MakeDictionaryAddition(kvp);
}
}
} else {
exprArgs[_func.Value.ExpandDictPosition] = MakeDictionary(namedArgs);
}
} else if (namedArgs != null) {
// extra named args which are unused and no where to put them.
return false;
}
return true;
}
/// <summary>
/// Adds an unbound keyword argument into the dictionary.
/// </summary>
/// <param name="kvp"></param>
private void MakeDictionaryAddition(KeyValuePair<string, Expression> kvp) {
_init.Add(
Ast.Call(
typeof(PythonOps).GetMethod("AddDictionaryArgument"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)),
AstUtils.Constant(kvp.Key),
AstUtils.Convert(kvp.Value, typeof(object)),
AstUtils.Convert(_dict, typeof(PythonDictionary))
)
);
}
/// <summary>
/// Adds a check to the last parameter (so it's evaluated after we've extracted
/// all the parameters) to ensure that we don't have any extra params or kw-params
/// when we don't have a params array or params dict to expand them into.
/// </summary>
private void AddCheckForNoExtraParameters(Expression[] exprArgs) {
List<Expression> tests = new List<Expression>(3);
// test we've used all of the extra parameters
if (_func.Value.ExpandListPosition == -1) {
if (_params != null) {
// we used some params, they should have gone down to zero...
tests.Add(
Ast.Call(
typeof(PythonOps).GetMethod("CheckParamsZero"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)),
_params
)
);
} else if (_userProvidedParams != null) {
// the user provided params, we didn't need any, and they should be zero
tests.Add(
Ast.Call(
typeof(PythonOps).GetMethod("CheckUserParamsZero"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)),
AstUtils.Convert(_userProvidedParams, typeof(object))
)
);
}
}
// test that we've used all the extra named arguments
if (_func.Value.ExpandDictPosition == -1 && _dict != null) {
tests.Add(
Ast.Call(
typeof(PythonOps).GetMethod("CheckDictionaryZero"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)),
AstUtils.Convert(_dict, typeof(IDictionary))
)
);
}
if (tests.Count != 0) {
if (exprArgs.Length != 0) {
// if we have arguments run the tests after the last arg is evaluated.
Expression last = exprArgs[exprArgs.Length - 1];
ParameterExpression temp;
_temps.Add(temp = Ast.Variable(last.Type, "$temp"));
tests.Insert(0, Ast.Assign(temp, last));
tests.Add(temp);
exprArgs[exprArgs.Length - 1] = Ast.Block(tests.ToArray());
} else {
// otherwise run them right before the method call
_paramlessCheck = Ast.Block(tests.ToArray());
}
}
}
/// <summary>
/// Helper function to validate that a named arg isn't duplicated with by
/// a params list or the dictionary (or both).
/// </summary>
private Expression ValidateNotDuplicate(Expression value, string name, int position) {
EnsureParams();
return Ast.Block(
Ast.Call(
typeof(PythonOps).GetMethod("VerifyUnduplicatedByPosition"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), // function
AstUtils.Constant(name, typeof(string)), // name
AstUtils.Constant(position), // position
_paramsLen // params list length
),
value
);
}
/// <summary>
/// Helper function to get a value (which has no default) from either the
/// params list or the dictionary (or both).
/// </summary>
private Expression ExtractNonDefaultValue(string name) {
if (_userProvidedParams != null) {
// expanded params
if (_dict != null) {
// expanded params & dict
return ExtractFromListOrDictionary(name);
} else {
return ExtractNextParamsArg();
}
} else if (_dict != null) {
// expanded dict
return ExtractDictionaryArgument(name);
}
// missing argument, no default, no expanded params or dict.
return null;
}
/// <summary>
/// Helper function to get the specified variable from the dictionary.
/// </summary>
private Expression ExtractDictionaryArgument(string name) {
_needCodeTest = true;
return Ast.Call(
typeof(PythonOps).GetMethod("ExtractDictionaryArgument"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), // function
AstUtils.Constant(name, typeof(string)), // name
AstUtils.Constant(Signature.ArgumentCount), // arg count
AstUtils.Convert(_dict, typeof(PythonDictionary)) // dictionary
);
}
/// <summary>
/// Helper function to extract the variable from defaults, or to call a helper
/// to check params / kw-dict / defaults to see which one contains the actual value.
/// </summary>
private Expression ExtractDefaultValue(int index, int dfltIndex) {
if (_dict == null && _userProvidedParams == null) {
// we can pull the default directly
return Ast.Call(
typeof(PythonOps).GetMethod("FunctionGetDefaultValue"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)),
AstUtils.Constant(dfltIndex)
);
} else {
// we might have a conflict, check the default last.
if (_userProvidedParams != null) {
EnsureParams();
}
_extractedDefault = true;
return Ast.Call(
typeof(PythonOps).GetMethod("GetFunctionParameterValue"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)),
AstUtils.Constant(dfltIndex),
AstUtils.Constant(_func.Value.ArgNames[index], typeof(string)),
VariableOrNull(_params, typeof(List)),
VariableOrNull(_dict, typeof(PythonDictionary))
);
}
}
/// <summary>
/// Helper function to extract from the params list or dictionary depending upon
/// which one has an available value.
/// </summary>
private Expression ExtractFromListOrDictionary(string name) {
EnsureParams();
_needCodeTest = true;
return Ast.Call(
typeof(PythonOps).GetMethod("ExtractAnyArgument"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), // function
AstUtils.Constant(name, typeof(string)), // name
_paramsLen, // arg count
_params, // params list
AstUtils.Convert(_dict, typeof(IDictionary)) // dictionary
);
}
private void EnsureParams() {
if (!_extractedParams) {
Debug.Assert(_userProvidedParams != null);
MakeParamsCopy(_userProvidedParams);
_extractedParams = true;
}
}
/// <summary>
/// Helper function to extract the next argument from the params list.
/// </summary>
private Expression ExtractNextParamsArg() {
if (!_extractedParams) {
MakeParamsCopy(_userProvidedParams);
_extractedParams = true;
}
return Ast.Call(
typeof(PythonOps).GetMethod("ExtractParamsArgument"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)), // function
AstUtils.Constant(Signature.ArgumentCount), // arg count
_params // list
);
}
private static Expression VariableOrNull(ParameterExpression var, Type type) {
if (var != null) {
return AstUtils.Convert(
var,
type
);
}
return AstUtils.Constant(null, type);
}
/// <summary>
/// Fixes up the argument list for the appropriate target delegate type.
/// </summary>
private Expression/*!*/[]/*!*/ GetArgumentsForTargetType(Expression[] exprArgs) {
Type target = _func.Value.__code__.Target.GetType();
if (target == typeof(Func<PythonFunction, object[], object>)) {
exprArgs = new Expression[] {
AstUtils.NewArrayHelper(typeof(object), exprArgs)
};
}
return exprArgs;
}
/// <summary>
/// Helper function to get the function argument strongly typed.
/// </summary>
private UnaryExpression/*!*/ GetFunctionParam() {
return Ast.Convert(_func.Expression, typeof(PythonFunction));
}
/// <summary>
/// Called when the user is expanding a dictionary - we copy the user
/// dictionary and verify that it contains only valid string names.
/// </summary>
private DynamicMetaObject/*!*/ MakeDictionaryCopy(DynamicMetaObject/*!*/ userDict) {
Debug.Assert(_dict == null);
userDict = userDict.Restrict(userDict.GetLimitType());
_temps.Add(_dict = Ast.Variable(typeof(PythonDictionary), "$dict"));
EnsureInit();
string methodName;
if (typeof(PythonDictionary).IsAssignableFrom(userDict.GetLimitType())) {
methodName = "CopyAndVerifyPythonDictionary";
} else if (typeof(IDictionary).IsAssignableFrom(userDict.GetLimitType())) {
methodName = "CopyAndVerifyDictionary";
} else {
methodName = "CopyAndVerifyUserMapping";
}
_init.Add(
Ast.Assign(
_dict,
Ast.Call(
typeof(PythonOps).GetMethod(methodName),
GetFunctionParam(),
AstUtils.Convert(userDict.Expression, userDict.GetLimitType())
)
)
);
return userDict;
}
/// <summary>
/// Called when the user is expanding a params argument
/// </summary>
private void MakeParamsCopy(Expression/*!*/ userList) {
Debug.Assert(_params == null);
_temps.Add(_params = Ast.Variable(typeof(List), "$list"));
_temps.Add(_paramsLen = Ast.Variable(typeof(int), "$paramsLen"));
EnsureInit();
_init.Add(
Ast.Assign(
_params,
Ast.Call(
typeof(PythonOps).GetMethod("CopyAndVerifyParamsList"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)),
AstUtils.Convert(userList, typeof(object))
)
)
);
_init.Add(
Ast.Assign(_paramsLen,
Ast.Add(
Ast.Call(_params, typeof(List).GetMethod("__len__")),
AstUtils.Constant(Signature.GetProvidedPositionalArgumentCount())
)
)
);
}
/// <summary>
/// Called when the user hasn't supplied a dictionary to be expanded but the
/// function takes a dictionary to be expanded.
/// </summary>
private Expression MakeDictionary(Dictionary<string, Expression/*!*/> namedArgs) {
Debug.Assert(_dict == null);
_temps.Add(_dict = Ast.Variable(typeof(PythonDictionary), "$dict"));
Expression dictCreator;
if (namedArgs != null) {
Debug.Assert(namedArgs.Count > 0);
Expression[] items = new Expression[namedArgs.Count * 2];
int itemIndex = 0;
foreach (KeyValuePair<string, Expression> kvp in namedArgs) {
items[itemIndex++] = AstUtils.Convert(kvp.Value, typeof(object));
items[itemIndex++] = AstUtils.Constant(kvp.Key, typeof(object));
}
dictCreator = Ast.Assign(
_dict,
Ast.Call(
typeof(PythonOps).GetMethod("MakeHomogeneousDictFromItems"),
Ast.NewArrayInit(typeof(object), items)
)
);
} else {
dictCreator = Ast.Assign(
_dict,
Ast.Call(
typeof(PythonOps).GetMethod("MakeDict"),
AstUtils.Constant(0)
)
);
}
return dictCreator;
}
/// <summary>
/// Helper function to create the expression for creating the actual tuple passed through.
/// </summary>
private static Expression/*!*/ MakeParamsTuple(List<Expression> extraArgs) {
if (extraArgs != null) {
return AstUtils.ComplexCallHelper(
typeof(PythonOps).GetMethod("MakeTuple"),
extraArgs.ToArray()
);
}
return Ast.Call(
typeof(PythonOps).GetMethod("MakeTuple"),
Ast.NewArrayInit(typeof(object[]))
);
}
/// <summary>
/// Creates the code to invoke the target delegate function w/ the specified arguments.
/// </summary>
private Expression/*!*/ MakeFunctionInvoke(Expression[] invokeArgs) {
Type targetType = _func.Value.__code__.Target.GetType();
MethodInfo method = targetType.GetMethod("Invoke");
// If calling generator, create the instance of PythonGenerator first
// and add it into the list of arguments
invokeArgs = ArrayUtils.Insert(GetFunctionParam(), invokeArgs);
Expression invoke = AstUtils.SimpleCallHelper(
Ast.Convert(
Ast.Call(
_call.SupportsLightThrow() ?
typeof(PythonOps).GetMethod("FunctionGetLightThrowTarget")
: typeof(PythonOps).GetMethod("FunctionGetTarget"),
GetFunctionParam()
),
targetType
),
method,
invokeArgs
);
if (_paramlessCheck != null) {
invoke = Expression.Block(_paramlessCheck, invoke);
}
return invoke;
}
/// <summary>
/// Appends the initialization code for the call to the function if any exists.
/// </summary>
private Expression/*!*/ AddInitialization(Expression body) {
if (_init == null) return body;
List<Expression> res = new List<Expression>(_init);
res.Add(body);
return Ast.Block(res);
}
private void MakeUnexpectedKeywordError(Dictionary<string, Expression> namedArgs) {
string name = null;
foreach (string id in namedArgs.Keys) {
name = id;
break;
}
_error = _call.Throw(
Ast.Call(
typeof(PythonOps).GetMethod("UnexpectedKeywordArgumentError"),
AstUtils.Convert(GetFunctionParam(), typeof(PythonFunction)),
AstUtils.Constant(name, typeof(string))
),
typeof(PythonOps)
);
}
private void EnsureInit() {
if (_init == null) _init = new List<Expression>();
}
}
#endregion
#region Operations
private static DynamicMetaObject/*!*/ MakeCallSignatureRule(DynamicMetaObject self) {
return new DynamicMetaObject(
Ast.Call(
typeof(PythonOps).GetMethod("GetFunctionSignature"),
AstUtils.Convert(
self.Expression,
typeof(PythonFunction)
)
),
BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, typeof(PythonFunction))
);
}
private static DynamicMetaObject MakeIsCallableRule(DynamicMetaObject/*!*/ self) {
return new DynamicMetaObject(
AstUtils.Constant(true),
BindingRestrictionsHelpers.GetRuntimeTypeRestriction(self.Expression, typeof(PythonFunction))
);
}
#endregion
#region Helpers
public new PythonFunction/*!*/ Value {
get {
return (PythonFunction)base.Value;
}
}
#endregion
#region IPythonOperable Members
DynamicMetaObject IPythonOperable.BindOperation(PythonOperationBinder action, DynamicMetaObject[] args) {
switch (action.Operation) {
case PythonOperationKind.CallSignatures:
return MakeCallSignatureRule(this);
case PythonOperationKind.IsCallable:
return MakeIsCallableRule(this);
}
return null;
}
#endregion
#region IInvokableInferable Members
InferenceResult IInferableInvokable.GetInferredType(Type delegateType, Type parameterType) {
if (!delegateType.IsSubclassOf(typeof(Delegate))) {
throw new InvalidOperationException();
}
MethodInfo invoke = delegateType.GetMethod("Invoke");
ParameterInfo[] pis = invoke.GetParameters();
if (pis.Length == Value.NormalArgumentCount) {
// our signatures are compatible
return new InferenceResult(
typeof(object),
Restrictions.Merge(
BindingRestrictions.GetTypeRestriction(
Expression,
typeof(PythonFunction)
).Merge(
BindingRestrictions.GetExpressionRestriction(
Expression.Equal(
Expression.Call(
typeof(PythonOps).GetMethod("FunctionGetCompatibility"),
Expression.Convert(Expression, typeof(PythonFunction))
),
Expression.Constant(Value.FunctionCompatibility)
)
)
)
)
);
}
return null;
}
#endregion
#region IConvertibleMetaObject Members
bool IConvertibleMetaObject.CanConvertTo(Type/*!*/ type, bool @explicit) {
return type.IsSubclassOf(typeof(Delegate));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using angah.Areas.HelpPage.ModelDescriptions;
using angah.Areas.HelpPage.Models;
namespace angah.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 media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), 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 description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <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)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.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}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A virtual TPM device
/// First published in XenServer 4.0.
/// </summary>
public partial class VTPM : XenObject<VTPM>
{
#region Constructors
public VTPM()
{
}
public VTPM(string uuid,
XenRef<VM> VM,
XenRef<VM> backend)
{
this.uuid = uuid;
this.VM = VM;
this.backend = backend;
}
/// <summary>
/// Creates a new VTPM from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public VTPM(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new VTPM from a Proxy_VTPM.
/// </summary>
/// <param name="proxy"></param>
public VTPM(Proxy_VTPM proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given VTPM.
/// </summary>
public override void UpdateFrom(VTPM update)
{
uuid = update.uuid;
VM = update.VM;
backend = update.backend;
}
internal void UpdateFrom(Proxy_VTPM proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM);
backend = proxy.backend == null ? null : XenRef<VM>.Create(proxy.backend);
}
public Proxy_VTPM ToProxy()
{
Proxy_VTPM result_ = new Proxy_VTPM();
result_.uuid = uuid ?? "";
result_.VM = VM ?? "";
result_.backend = backend ?? "";
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this VTPM
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("VM"))
VM = Marshalling.ParseRef<VM>(table, "VM");
if (table.ContainsKey("backend"))
backend = Marshalling.ParseRef<VM>(table, "backend");
}
public bool DeepEquals(VTPM other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._VM, other._VM) &&
Helper.AreEqual2(this._backend, other._backend);
}
internal static List<VTPM> ProxyArrayToObjectList(Proxy_VTPM[] input)
{
var result = new List<VTPM>();
foreach (var item in input)
result.Add(new VTPM(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, VTPM server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given VTPM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static VTPM get_record(Session session, string _vtpm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vtpm_get_record(session.opaque_ref, _vtpm);
else
return new VTPM(session.proxy.vtpm_get_record(session.opaque_ref, _vtpm ?? "").parse());
}
/// <summary>
/// Get a reference to the VTPM instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VTPM> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vtpm_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<VTPM>.Create(session.proxy.vtpm_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new VTPM instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<VTPM> create(Session session, VTPM _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vtpm_create(session.opaque_ref, _record);
else
return XenRef<VTPM>.Create(session.proxy.vtpm_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new VTPM instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, VTPM _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vtpm_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.proxy.async_vtpm_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified VTPM instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static void destroy(Session session, string _vtpm)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vtpm_destroy(session.opaque_ref, _vtpm);
else
session.proxy.vtpm_destroy(session.opaque_ref, _vtpm ?? "").parse();
}
/// <summary>
/// Destroy the specified VTPM instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static XenRef<Task> async_destroy(Session session, string _vtpm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_vtpm_destroy(session.opaque_ref, _vtpm);
else
return XenRef<Task>.Create(session.proxy.async_vtpm_destroy(session.opaque_ref, _vtpm ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VTPM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static string get_uuid(Session session, string _vtpm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vtpm_get_uuid(session.opaque_ref, _vtpm);
else
return session.proxy.vtpm_get_uuid(session.opaque_ref, _vtpm ?? "").parse();
}
/// <summary>
/// Get the VM field of the given VTPM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static XenRef<VM> get_VM(Session session, string _vtpm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vtpm_get_vm(session.opaque_ref, _vtpm);
else
return XenRef<VM>.Create(session.proxy.vtpm_get_vm(session.opaque_ref, _vtpm ?? "").parse());
}
/// <summary>
/// Get the backend field of the given VTPM.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vtpm">The opaque_ref of the given vtpm</param>
public static XenRef<VM> get_backend(Session session, string _vtpm)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vtpm_get_backend(session.opaque_ref, _vtpm);
else
return XenRef<VM>.Create(session.proxy.vtpm_get_backend(session.opaque_ref, _vtpm ?? "").parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// the virtual machine
/// </summary>
[JsonConverter(typeof(XenRefConverter<VM>))]
public virtual XenRef<VM> VM
{
get { return _VM; }
set
{
if (!Helper.AreEqual(value, _VM))
{
_VM = value;
Changed = true;
NotifyPropertyChanged("VM");
}
}
}
private XenRef<VM> _VM = new XenRef<VM>(Helper.NullOpaqueRef);
/// <summary>
/// the domain where the backend is located
/// </summary>
[JsonConverter(typeof(XenRefConverter<VM>))]
public virtual XenRef<VM> backend
{
get { return _backend; }
set
{
if (!Helper.AreEqual(value, _backend))
{
_backend = value;
Changed = true;
NotifyPropertyChanged("backend");
}
}
}
private XenRef<VM> _backend = new XenRef<VM>(Helper.NullOpaqueRef);
}
}
| |
#region Namespaces
using System;
using System.Windows.Forms;
#endregion
namespace Epi.Windows.Controls
{
/// <summary>
/// A Dragable GUID field to be used in MakeView's questionnaire designer
/// </summary>
public class DragableGUIDField : System.Windows.Forms.TextBox, IDragable, IFieldControl
{
#region Private Members
private int fieldId;
private Epi.Fields.Field field;
private ControlTracker controlTracker;
private Enums.TrackerStatus trackerStatus;
private bool hasMoved = false;
private bool isMouseDown = false;
private int x;
private int y;
#endregion
#region Constructors
/// <summary>
/// Constructor for the class
/// </summary>
public DragableGUIDField()
{
InitializeComponent();
}
#endregion
#region Override Methods
/// <summary>
/// Overrides the GUIDField's OnPaint event
/// </summary>
/// <param name="e">Parameters for the paint event</param>
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
base.OnPaint(e);
}
#endregion
#region Private Methods
/// <summary>
/// Initializes the GUIDField
/// </summary>
private void InitializeComponent()
{
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.DragableGUIDField_MouseDown);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.DragableGUIDField_MouseMove);
this.MouseLeave += new System.EventHandler(this.DragableGUIDField_MouseLeave);
this.DragOver += new DragEventHandler(DragableGUIDField_DragOver);
}
#endregion
#region Event Handlers
/// <summary>
/// Handles the mouse-move event over the GUID field
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void DragableGUIDField_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (isMouseDown)
{
DataObject data = new DataObject("DragControl", this);
this.DoDragDrop(data, DragDropEffects.Move);
isMouseDown = false;
this.hasMoved = true;
}
}
/// <summary>
/// Handles the mouse-down event of the GUID field
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void DragableGUIDField_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
isMouseDown = true;
x = e.X;
y = e.Y;
}
/// <summary>
/// Handles the mouse-leave event of the GUID field
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void DragableGUIDField_MouseLeave(object sender, System.EventArgs e)
{
isMouseDown = false;
}
/// <summary>
/// Handles the drag-over event of the GUID field
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void DragableGUIDField_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the horizontal distance of the mouse from the edge of the GUID field
/// </summary>
public int XOffset
{
get
{
return this.x;
}
set
{
this.x = value;
}
}
/// <summary>
/// Gets or sets the vertical distance of the mouse from the edge of the GUID field
/// </summary>
public int YOffset
{
get
{
return this.y;
}
set
{
this.y = value;
}
}
/// <summary>
/// Gets or sets whether or not the dynamic control has moved
/// </summary>
public bool HasMoved
{
get
{
return hasMoved;
}
set
{
hasMoved = value;
}
}
/// <summary>
/// Gets or sets the ID of the MakeView field referenced by the control
/// </summary>
public int FieldId
{
get
{
return fieldId;
}
set
{
fieldId = value;
}
}
/// <summary>
/// Gets and sets the field this control is associated with.
/// </summary>
public Epi.Fields.Field Field
{
get
{
return field;
}
set
{
field = value;
}
}
#endregion
#region IFieldControl Members
/// <summary>
/// IFieldControl implementation
/// </summary>
public bool IsFieldGroup
{
get
{
return false;
}
set
{
// do nothing
}
}
/// <summary>
/// IFieldControl implementation
/// </summary>
public Epi.Fields.GroupField GroupField
{
get
{
return null;
}
set
{
// Empty method needs to be here for proper interface implementation
}
}
public ControlTracker Tracker
{
get { return controlTracker; }
set { controlTracker = value; }
}
public Enums.TrackerStatus TrackerStatus
{
get { return trackerStatus; }
set
{
controlTracker.TrackerStatus = value;
this.trackerStatus = value;
}
}
#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.Collections;
using System.Collections.Generic;
using System.Security;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Text;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.IO
{
public static class Directory
{
public static DirectoryInfo GetParent(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
String fullPath = PathHelpers.GetFullPathInternal(path);
String s = Path.GetDirectoryName(fullPath);
if (s == null)
return null;
return new DirectoryInfo(s);
}
[System.Security.SecuritySafeCritical]
public static DirectoryInfo CreateDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.CreateDirectory(fullPath);
return new DirectoryInfo(fullPath, null);
}
// Input to this method should already be fullpath. This method will ensure that we append
// the trailing slash only when appropriate.
internal static String EnsureTrailingDirectorySeparator(string fullPath)
{
String fullPathWithTrailingDirectorySeparator;
if (!PathHelpers.EndsInDirectorySeparator(fullPath))
fullPathWithTrailingDirectorySeparator = fullPath + PathHelpers.DirectorySeparatorCharAsString;
else
fullPathWithTrailingDirectorySeparator = fullPath;
return fullPathWithTrailingDirectorySeparator;
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
[System.Security.SecuritySafeCritical] // auto-generated
public static bool Exists(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
String fullPath = PathHelpers.GetFullPathInternal(path);
return FileSystem.Current.DirectoryExists(fullPath);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
public static void SetCreationTime(String path, DateTime creationTime)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: true);
}
public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetCreationTime(fullPath, File.GetUtcDateTimeOffset(creationTimeUtc), asDirectory: true);
}
public static DateTime GetCreationTime(String path)
{
return File.GetCreationTime(path);
}
public static DateTime GetCreationTimeUtc(String path)
{
return File.GetCreationTimeUtc(path);
}
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: true);
}
public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastWriteTime(fullPath, File.GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: true);
}
public static DateTime GetLastWriteTime(String path)
{
return File.GetLastWriteTime(path);
}
public static DateTime GetLastWriteTimeUtc(String path)
{
return File.GetLastWriteTimeUtc(path);
}
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: true);
}
public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastAccessTime(fullPath, File.GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: true);
}
public static DateTime GetLastAccessTime(String path)
{
return File.GetLastAccessTime(path);
}
public static DateTime GetLastAccessTimeUtc(String path)
{
return File.GetLastAccessTimeUtc(path);
}
// Returns an array of filenames in the DirectoryInfo specified by path
public static String[] GetFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt").
public static String[] GetFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption);
}
// Returns an array of Directories in the current directory.
public static String[] GetDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<String[]>() != null);
return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path
public static String[] GetFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, searchOption);
}
private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption);
}
// Returns fully qualified user path of dirs/files that matches the search parameters.
// For recursive search this method will search through all the sub dirs and execute
// the given search criteria against every dir.
// For all the dirs/files returned, it will then demand path discovery permission for
// their parent folders (it will avoid duplicate permission checks)
internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(userPathOriginal != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<String> enumerable = FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption,
(includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0));
return EnumerableHelpers.ToArray(enumerable);
}
public static IEnumerable<String> EnumerateDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true);
}
public static IEnumerable<String> EnumerateFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true);
}
private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption,
bool includeFiles, bool includeDirs)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption,
(includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0));
}
[System.Security.SecuritySafeCritical]
public static String GetDirectoryRoot(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
String fullPath = PathHelpers.GetFullPathInternal(path);
String root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath));
return root;
}
internal static String InternalGetDirectoryRoot(String path)
{
if (path == null) return null;
return path.Substring(0, PathInternal.GetRootLength(path));
}
/*===============================CurrentDirectory===============================
**Action: Provides a getter and setter for the current directory. The original
** current DirectoryInfo is the one from which the process was started.
**Returns: The current DirectoryInfo (from the getter). Void from the setter.
**Arguments: The current DirectoryInfo to which to switch to the setter.
**Exceptions:
==============================================================================*/
[System.Security.SecuritySafeCritical]
public static String GetCurrentDirectory()
{
return FileSystem.Current.GetCurrentDirectory();
}
[System.Security.SecurityCritical] // auto-generated
public static void SetCurrentDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("value");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
if (PathInternal.IsPathTooLong(path))
throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetCurrentDirectory(fulldestDirName);
}
[System.Security.SecuritySafeCritical]
public static void Move(String sourceDirName, String destDirName)
{
if (sourceDirName == null)
throw new ArgumentNullException("sourceDirName");
if (sourceDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "sourceDirName");
if (destDirName == null)
throw new ArgumentNullException("destDirName");
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName");
Contract.EndContractBlock();
String fullsourceDirName = PathHelpers.GetFullPathInternal(sourceDirName);
String sourcePath = EnsureTrailingDirectorySeparator(fullsourceDirName);
if (PathInternal.IsDirectoryTooLong(sourcePath))
throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = PathHelpers.GetFullPathInternal(destDirName);
String destPath = EnsureTrailingDirectorySeparator(fulldestDirName);
if (PathInternal.IsDirectoryTooLong(destPath))
throw new PathTooLongException(SR.IO_PathTooLong);
StringComparison pathComparison = PathInternal.GetComparison();
if (String.Equals(sourcePath, destPath, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
String sourceRoot = Path.GetPathRoot(sourcePath);
String destinationRoot = Path.GetPathRoot(destPath);
if (!String.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
FileSystem.Current.MoveDirectory(fullsourceDirName, fulldestDirName);
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.RemoveDirectory(fullPath, false);
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path, bool recursive)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.RemoveDirectory(fullPath, recursive);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input.Touch;
namespace SpaceGame
{
public class SpaceGame : Microsoft.Xna.Framework.Game
{
// Resources for drawing.
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
// speed constants
protected const float SPEED_STARS = 20.0f;
protected const float SPEED_SHIP = 75.0f;
protected const float SPEED_METEOR = 40.0f;
protected const float SPEED_LASER = 90.0f;
// reference our enemy ship
protected Texture2D texEnemyShip;
// enemy ships' locations
protected List<Vector3> locEnemyShips = new List<Vector3>();
// reference to enemy laser
protected Texture2D texEnemyLaser;
// our enemy lasers' locations
protected List<Vector2> locEnemyLasers = new List<Vector2> ();
// enemy travel lanes
protected Vector2 locStartEnemyRight = Vector2.Zero;
protected Vector2 locStartEnemyLeft = Vector2.Zero;
// reference our spaceship
protected Texture2D texShip;
// our ship's location
protected Vector2 locShip = Vector2.Zero;
// references for ship damage sprites
protected List<Texture2D> texShipDamage = new List<Texture2D> ();
// ship damaged?
protected int shipDamageLevel = -1;
// reference our starfield
protected Texture2D texStars;
// our background's location
protected Vector2 locStars = Vector2.Zero;
// screen resolution
protected Rectangle rectViewBounds = Rectangle.Empty;
// player bounds
protected Rectangle rectPlayerBounds = Rectangle.Empty;
// reference to meteors
protected List<Texture2D> texMeteors = new List<Texture2D> ();
// our meteors' locations
protected List<Vector3> locMeteors = new List<Vector3> ();
// reference to laser
protected Texture2D texLaser;
// our lasers' locations
protected List<Vector2> locLasers = new List<Vector2> ();
public SpaceGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
if(PlatformHelper.CurrentPlatform == Platforms.WindowsPhone)
{
TargetElapsedTime = TimeSpan.FromTicks(333333);
}
graphics.IsFullScreen = PlatformHelper.IsMobile;
this.IsMouseVisible = PlatformHelper.IsDesktop;
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 480;
graphics.SupportedOrientations =
DisplayOrientation.LandscapeLeft |
DisplayOrientation.LandscapeRight;
//GamePadEx.KeyboardPlayerIndex = PlayerIndex.One;
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// load our spaceship image
texShip = Content.Load<Texture2D> ("ship/playerShip1_red");
// load our space background
texStars = Content.Load<Texture2D> ("purple");
// load our meteors
texMeteors.Add (Content.Load<Texture2D> ("meteor/meteorBrown_big1"));
texMeteors.Add (Content.Load<Texture2D> ("meteor/meteorBrown_big2"));
texMeteors.Add (Content.Load<Texture2D> ("meteor/meteorBrown_big3"));
texMeteors.Add (Content.Load<Texture2D> ("meteor/meteorBrown_big4"));
// load our laser
texLaser = Content.Load<Texture2D> ("ship/laserRed01");
// load our ship damage sprites
texShipDamage.Add(Content.Load<Texture2D> ("ship/playerShip1_damage1"));
texShipDamage.Add(Content.Load<Texture2D> ("ship/playerShip1_damage2"));
texShipDamage.Add(Content.Load<Texture2D> ("ship/playerShip1_damage3"));
// load enemy ship
texEnemyShip = Content.Load<Texture2D> ("enemy/enemyBlack3");
// load enemy laser
texEnemyLaser = Content.Load<Texture2D> ("enemy/laserBlue01");
// screen bounds
rectViewBounds = graphics.GraphicsDevice.Viewport.Bounds;
// player bounds
rectPlayerBounds = rectViewBounds;
rectPlayerBounds.X = 10;
rectPlayerBounds.Width = rectViewBounds.Width - 10 * 2;
rectPlayerBounds.Y = rectViewBounds.Height / 3;
rectPlayerBounds.Height = rectViewBounds.Height - rectPlayerBounds.Top - 10;
// start ship at center, bottom of screen
locShip.X = rectViewBounds.Width / 2 - texShip.Bounds.Width / 2;
locShip.Y = rectViewBounds.Height - texShip.Bounds.Height - 10.0f;
// start stars off screen
locStars.Y = -texStars.Bounds.Height;
// enemy ship starting locations
locStartEnemyRight.X = rectViewBounds.Right - 1;
locStartEnemyRight.Y =
rectViewBounds.Height / 9 -
texEnemyShip.Bounds.Height / 2;
locStartEnemyLeft.X =
1 - texEnemyShip.Bounds.Width;
locStartEnemyRight.Y =
2 * rectViewBounds.Height / 9 -
texEnemyShip.Bounds.Height / 2;
}
// time between meteor creation
protected const float METEOR_DELAY = 3.0f;
protected float meteorElapsed = METEOR_DELAY;
// time between enemy creation
protected const float ENEMY_DELAY = 5.0f;
protected float enemyElapsed = ENEMY_DELAY;
protected bool isEnemyLeft = true;
// random meteor placement
protected Random rand = new Random ();
// time between laser shots
protected const float INIT_LASER_DELAY = 1.0f;
protected float laserDelay = INIT_LASER_DELAY;
protected float laserElapsed = INIT_LASER_DELAY;
// time between enemy shots
protected const float INIT_ENEMY_LASER_DELAY = 3.25f;
protected override void Update(GameTime gameTime)
{
var gamepad1 = GamePadEx.GetState (PlayerIndex.One);
if (gamepad1.IsButtonDown (Buttons.Back)) {
this.Exit ();
} else {
// move the ship
var elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
var dX =
gamepad1.ThumbSticks.Left.X +
gamepad1.ThumbSticks.Right.X;
var dY =
gamepad1.ThumbSticks.Left.Y +
gamepad1.ThumbSticks.Right.Y;
locShip.X += dX * SPEED_SHIP * elapsed;
locShip.Y -= dY * SPEED_SHIP * elapsed;
// keep ship in bounds (Horizontal)
var maxX = rectPlayerBounds.Right - texShip.Bounds.Width;
if (locShip.X < rectPlayerBounds.X) {
locShip.X = rectPlayerBounds.X;
} else if(locShip.X > maxX) {
locShip.X = maxX;
}
// keep ship in bounds (Vertical)
var maxY = rectPlayerBounds.Bottom - texShip.Bounds.Height;
if (locShip.Y < rectPlayerBounds.Y) {
locShip.Y = rectPlayerBounds.Y;
} else if(locShip.Y > maxY) {
locShip.Y = maxY;
}
// move the stars
locStars.Y += SPEED_STARS * elapsed;
if (locStars.Y >= 0.0f) {
locStars.Y = -texStars.Bounds.Height;
}
// add a new enemy?
enemyElapsed += elapsed;
if (enemyElapsed >= ENEMY_DELAY) {
var locEnemy = new Vector3(locStartEnemyLeft, 0.0f);
if (!isEnemyLeft) {
locEnemy = new Vector3(locStartEnemyRight, 0.0f);
}
locEnemyShips.Add (locEnemy);
enemyElapsed = 0.0f;
isEnemyLeft = !isEnemyLeft;
}
// update existing enemies
for (int i = 0; i < locEnemyShips.Count; i++) {
var loc = locEnemyShips [i];
if (loc.Y == locStartEnemyLeft.Y) {
loc.X += elapsed * SPEED_SHIP;
} else {
loc.X -= elapsed * SPEED_SHIP;
}
locEnemyShips [i] = loc;
}
// add a new meteor?
meteorElapsed += elapsed;
if (meteorElapsed >= METEOR_DELAY) {
var iMeteor = rand.Next (texMeteors.Count);
var meteorWidth = texMeteors [iMeteor].Bounds.Width;
var meteorHeight = texMeteors [iMeteor].Bounds.Height;
var randX = rand.Next(rectPlayerBounds.Width - meteorWidth);
var loc =
new Vector3 (
rectPlayerBounds.Left + randX,
1 - meteorHeight,
iMeteor);
locMeteors.Add (loc);
meteorElapsed = 0.0f;
}
// update existing meteors
for (int i = 0; i < locMeteors.Count; i++) {
var loc = locMeteors [i];
loc.Y += elapsed * SPEED_METEOR;
locMeteors [i] = loc;
}
// add a new laser?
laserElapsed += elapsed;
if (gamepad1.IsButtonDown (Buttons.A)) {
if (laserElapsed >= laserDelay) {
var loc =
new Vector2 (
locShip.X + texShip.Width / 2 - texLaser.Width / 2,
locShip.Y);
locLasers.Add (loc);
laserElapsed = 0.0f;
}
}
// update existing lasers
for (int i = 0; i < locLasers.Count; i++) {
var loc = locLasers [i];
loc.Y -= elapsed * SPEED_LASER;
locLasers [i] = loc;
}
// add a new enemy laser?
for (int i = 0; i < locEnemyShips.Count; i++) {
var loc = locEnemyShips [i];
loc.Z += elapsed;
if (loc.Z >= INIT_ENEMY_LASER_DELAY) {
var locLaser =
new Vector2 (
loc.X + texEnemyShip.Width / 2 - texEnemyLaser.Width / 2,
loc.Y + texEnemyShip.Height);
locEnemyLasers.Add (locLaser);
loc.Z = 0.0f;
}
locEnemyShips [i] = loc;
}
// update existing enemy lasers
for (int i = 0; i < locEnemyLasers.Count; i++) {
var loc = locEnemyLasers [i];
loc.Y += elapsed * SPEED_LASER;
locEnemyLasers [i] = loc;
}
// check for collisions
CheckForCollisions ();
DoHousekeeping ();
}
base.Update(gameTime);
}
// check for collisions
protected void CheckForCollisions () {
// --------------------
// meteor hit by laser?
// --------------------
var rectMeteor = Rectangle.Empty;
var rectLaser = texLaser.Bounds;
// check all meteor instances
for (int iMeteor = 0; iMeteor < locMeteors.Count; iMeteor++) {
// create a rectangle, current location and size of meteor
var locMeteor = locMeteors [iMeteor];
rectMeteor = texMeteors [(int)locMeteor.Z].Bounds;
rectMeteor.X = (int)locMeteor.X;
rectMeteor.Y = (int)locMeteor.Y;
// check all laser instances
for (int iLaser = 0; iLaser < locLasers.Count; iLaser++) {
// create a rectangle, current location and size of laser
var locLaser = locLasers [iLaser];
rectLaser.X = (int)locLaser.X;
rectLaser.Y = (int)locLaser.Y;
// does laser touch meteor?
if (rectLaser.Intersects (rectMeteor)) {
locMeteors.RemoveAt (iMeteor);
iMeteor--;
locLasers.RemoveAt (iLaser);
iLaser--;
break;
}
}
}
// --------------------
// ship hit by meteor?
// --------------------
rectMeteor = Rectangle.Empty;
var rectShip = texShip.Bounds;
rectShip.X = (int)locShip.X;
rectShip.Y = (int)locShip.Y;
// check all meteor instances
for (int iMeteor = 0; iMeteor < locMeteors.Count; iMeteor++) {
// create a rectangle, current location and size of meteor
var locMeteor = locMeteors [iMeteor];
rectMeteor = texMeteors [(int)locMeteor.Z].Bounds;
rectMeteor.X = (int)locMeteor.X;
rectMeteor.Y = (int)locMeteor.Y;
// does meteor touch ship?
if (rectShip.Intersects (rectMeteor)) {
locMeteors.RemoveAt (iMeteor);
iMeteor--;
shipDamageLevel =
Math.Min (texShipDamage.Count - 1, shipDamageLevel + 1);
break;
}
}
// --------------------
// ship hit by laser?
// --------------------
// check all laser instances
for (int iLaser = 0; iLaser < locEnemyLasers.Count; iLaser++) {
// create a rectangle, current location and size of laser
var locLaser = locEnemyLasers [iLaser];
rectLaser.X = (int)locLaser.X;
rectLaser.Y = (int)locLaser.Y;
// does laser touch ship?
if (rectLaser.Intersects (rectShip)) {
locEnemyLasers.RemoveAt (iLaser);
iLaser--;
shipDamageLevel =
Math.Min (texShipDamage.Count - 1, shipDamageLevel + 1);
break;
}
}
// --------------------
// enemy hit by laser?
// --------------------
var rectEnemy = Rectangle.Empty;
// check all meteor instances
for (int iEnemy = 0; iEnemy < locEnemyShips.Count; iEnemy++) {
// create a rectangle, current location and size of enemy ship
var locEnemy = locEnemyShips [iEnemy];
rectEnemy = texEnemyShip.Bounds;
rectEnemy.X = (int)locEnemy.X;
rectEnemy.Y = (int)locEnemy.Y;
// check all laser instances
for (int iLaser = 0; iLaser < locLasers.Count; iLaser++) {
// create a rectangle, current location and size of laser
var locLaser = locLasers [iLaser];
rectLaser.X = (int)locLaser.X;
rectLaser.Y = (int)locLaser.Y;
// does laser touch enemy ship?
if (rectLaser.Intersects (rectEnemy)) {
locEnemyShips.RemoveAt (iEnemy);
iEnemy--;
locLasers.RemoveAt (iLaser);
iLaser--;
break;
}
}
}
}
// NEW: remove unused objects
protected void DoHousekeeping () {
// our lasers
var rect = texLaser.Bounds;
for (int i = 0; i < locLasers.Count; i++) {
rect.X = (int)locLasers [i].X;
rect.Y = (int)locLasers [i].Y;
if (!rectViewBounds.Intersects (rect)) {
locLasers.RemoveAt (i);
i--;
}
}
// enemy lasers
rect = texEnemyLaser.Bounds;
for (int i = 0; i < locEnemyLasers.Count; i++) {
rect.X = (int)locEnemyLasers [i].X;
rect.Y = (int)locEnemyLasers [i].Y;
if (!rectViewBounds.Intersects (rect)) {
locEnemyLasers.RemoveAt (i);
i--;
}
}
// enemy ships
rect = texEnemyShip.Bounds;
for (int i = 0; i < locEnemyShips.Count; i++) {
rect.X = (int)locEnemyShips [i].X;
rect.Y = (int)locEnemyShips [i].Y;
if (!rectViewBounds.Intersects (rect)) {
locEnemyShips.RemoveAt (i);
i--;
}
}
// meteors
for (int i = 0; i < locMeteors.Count; i++) {
rect = texMeteors[(int)locMeteors[i].Z].Bounds;
rect.X = (int)locMeteors [i].X;
rect.Y = (int)locMeteors [i].Y;
if (!rectViewBounds.Intersects (rect)) {
locMeteors.RemoveAt (i);
i--;
}
}
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear (Color.CornflowerBlue);
spriteBatch.Begin ();
// draw our space image at current location, filling screen
var loc = locStars;
while (loc.Y < rectViewBounds.Bottom) {
loc.X = 0.0f;
while (loc.X < rectViewBounds.Right) {
spriteBatch.Draw (texStars, loc, Color.White);
loc.X += texStars.Bounds.Width;
}
loc.Y += texStars.Bounds.Height;
}
// draw lasers
for (int i = 0; i < locLasers.Count; i++) {
spriteBatch.Draw (texLaser, locLasers [i], Color.White);
}
// draw our spaceship image at current location
spriteBatch.Draw (texShip, locShip, Color.White);
// draw ship damage, if any
if (shipDamageLevel >= 0) {
spriteBatch.Draw (
texShipDamage[shipDamageLevel],
locShip,
Color.White);
}
// draw meteors
for (int i = 0; i < locMeteors.Count; i++) {
var locMeteor = locMeteors [i];
var iTexture = (int)locMeteor.Z;
spriteBatch.Draw (
texMeteors[iTexture],
new Vector2(locMeteor.X, locMeteor.Y),
Color.White);
}
// draw enemy lasers
for (int i = 0; i < locEnemyLasers.Count; i++) {
spriteBatch.Draw (texEnemyLaser, locEnemyLasers[i], Color.White);
}
// draw enemy ships
for (int i = 0; i < locEnemyShips.Count; i++) {
loc = new Vector2 (locEnemyShips [i].X, locEnemyShips [i].Y);
spriteBatch.Draw (texEnemyShip, loc, Color.White);
}
spriteBatch.End ();
base.Draw (gameTime);
}
}
}
| |
using System;
using System.Linq;
using SquabPie.Mono.Cecil;
using SquabPie.Mono.Cecil.Cil;
using NUnit.Framework;
namespace SquabPie.Mono.Cecil.Tests {
[TestFixture]
public class MethodBodyTests : BaseTestFixture {
[Test]
public void MultiplyMethod ()
{
TestIL ("hello.il", module => {
var foo = module.GetType ("Foo");
Assert.IsNotNull (foo);
var bar = foo.GetMethod ("Bar");
Assert.IsNotNull (bar);
Assert.IsTrue (bar.IsIL);
AssertCode (@"
.locals init (System.Int32 V_0)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: call System.Void Foo::Baz(System.Int32)
IL_000a: ret
", bar);
});
}
[Test]
public void PrintStringEmpty ()
{
TestIL ("hello.il", module => {
var foo = module.GetType ("Foo");
Assert.IsNotNull (foo);
var print_empty = foo.GetMethod ("PrintEmpty");
Assert.IsNotNull (print_empty);
AssertCode (@"
.locals ()
IL_0000: ldsfld System.String System.String::Empty
IL_0005: call System.Void System.Console::WriteLine(System.String)
IL_000a: ret
", print_empty);
});
}
[Test]
public void Branch ()
{
TestModule ("libhello.dll", module => {
var lib = module.GetType ("Library");
Assert.IsNotNull (lib);
var method = lib.GetMethod ("GetHelloString");
Assert.IsNotNull (method);
AssertCode (@"
.locals init (System.String V_0)
IL_0000: nop
IL_0001: ldstr ""hello world of tomorrow""
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
", method);
});
}
[Test]
public void Switch ()
{
TestModule ("switch.exe", module => {
var program = module.GetType ("Program");
Assert.IsNotNull (program);
var method = program.GetMethod ("Main");
Assert.IsNotNull (method);
AssertCode (@"
.locals init (System.Int32 V_0)
IL_0000: ldarg.0
IL_0001: ldlen
IL_0002: conv.i4
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: ldc.i4.8
IL_0006: bgt.s IL_0026
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: sub
IL_000b: switch (IL_0032, IL_0034, IL_0038, IL_0034)
IL_0020: ldloc.0
IL_0021: ldc.i4.8
IL_0022: beq.s IL_0036
IL_0024: br.s IL_0038
IL_0026: ldloc.0
IL_0027: ldc.i4.s 16
IL_0029: beq.s IL_0036
IL_002b: ldloc.0
IL_002c: ldc.i4.s 32
IL_002e: beq.s IL_0036
IL_0030: br.s IL_0038
IL_0032: ldc.i4.0
IL_0033: ret
IL_0034: ldc.i4.1
IL_0035: ret
IL_0036: ldc.i4.2
IL_0037: ret
IL_0038: ldc.i4.s 42
IL_003a: ret
", method);
});
}
[Test]
public void MethodSpec ()
{
TestIL ("methodspecs.il", module => {
var tamtam = module.GetType ("Tamtam");
var bar = tamtam.GetMethod ("Bar");
Assert.IsNotNull (bar);
AssertCode (@"
.locals ()
IL_0000: ldc.i4.2
IL_0001: call System.Void Tamtam::Foo<System.Int32>(TFoo)
IL_0006: ret
", bar);
});
}
[Test]
public void NestedTryCatchFinally ()
{
TestModule ("catch.exe", module => {
var program = module.GetType ("Program");
var main = program.GetMethod ("Main");
Assert.IsNotNull (main);
AssertCode (@"
.locals ()
IL_0000: call System.Void Program::Foo()
IL_0005: leave.s IL_000d
IL_0007: call System.Void Program::Baz()
IL_000c: endfinally
IL_000d: leave.s IL_001f
IL_000f: pop
IL_0010: call System.Void Program::Bar()
IL_0015: leave.s IL_001f
IL_0017: pop
IL_0018: call System.Void Program::Bar()
IL_001d: leave.s IL_001f
IL_001f: leave.s IL_0027
IL_0021: call System.Void Program::Baz()
IL_0026: endfinally
IL_0027: ret
.try IL_0000 to IL_0007 finally handler IL_0007 to IL_000d
.try IL_0000 to IL_000f catch System.ArgumentException handler IL_000f to IL_0017
.try IL_0000 to IL_000f catch System.Exception handler IL_0017 to IL_001f
.try IL_0000 to IL_0021 finally handler IL_0021 to IL_0027
", main);
});
}
[Test]
public void FunctionPointersAndCallSites ()
{
TestModule ("fptr.exe", module => {
var type = module.Types [0];
var start = type.GetMethod ("Start");
Assert.IsNotNull (start);
AssertCode (@"
.locals init ()
IL_0000: ldc.i4.1
IL_0001: call method System.Int32 *(System.Int32) MakeDecision::Decide()
IL_0006: calli System.Int32(System.Int32)
IL_000b: call System.Void System.Console::WriteLine(System.Int32)
IL_0010: ldc.i4.1
IL_0011: call method System.Int32 *(System.Int32) MakeDecision::Decide()
IL_0016: calli System.Int32(System.Int32)
IL_001b: call System.Void System.Console::WriteLine(System.Int32)
IL_0020: ldc.i4.1
IL_0021: call method System.Int32 *(System.Int32) MakeDecision::Decide()
IL_0026: calli System.Int32(System.Int32)
IL_002b: call System.Void System.Console::WriteLine(System.Int32)
IL_0030: ret
", start);
}, verify: false);
}
[Test]
public void ThisParameter ()
{
TestIL ("hello.il", module => {
var type = module.GetType ("Foo");
var method = type.GetMethod ("Gazonk");
Assert.IsNotNull (method);
AssertCode (@"
.locals ()
IL_0000: ldarg 0
IL_0004: pop
IL_0005: ret
", method);
Assert.AreEqual (method.Body.ThisParameter.ParameterType, type);
Assert.AreEqual (method.Body.ThisParameter, method.Body.Instructions [0].Operand);
});
}
[Test]
public void ThisParameterStaticMethod ()
{
var static_method = typeof (ModuleDefinition).ToDefinition ().Methods.Where (m => m.IsStatic).First ();
Assert.IsNull (static_method.Body.ThisParameter);
}
[Test]
public void ThisParameterPrimitive ()
{
var int32 = typeof (int).ToDefinition ();
var int_to_string = int32.Methods.Where (m => m.Name == "ToString" && m.Parameters.Count == 0).First();
Assert.IsNotNull (int_to_string);
var this_parameter_type = int_to_string.Body.ThisParameter.ParameterType;
Assert.IsTrue (this_parameter_type.IsByReference);
var element_type = ((ByReferenceType) this_parameter_type).ElementType;
Assert.AreEqual (int32, element_type);
}
[Test]
public void ThisParameterValueType ()
{
var token = typeof (MetadataToken).ToDefinition ();
var token_to_string = token.Methods.Where (m => m.Name == "ToString" && m.Parameters.Count == 0).First ();
Assert.IsNotNull (token_to_string);
var this_parameter_type = token_to_string.Body.ThisParameter.ParameterType;
Assert.IsTrue (this_parameter_type.IsByReference);
var element_type = ((ByReferenceType) this_parameter_type).ElementType;
Assert.AreEqual (token, element_type);
}
[Test]
public void ThisParameterObject ()
{
var module = typeof (MethodBodyTests).ToDefinition ().Module;
var @object = module.TypeSystem.Object.Resolve ();
var method = @object.Methods.Where (m => m.HasBody).First ();
var type = method.Body.ThisParameter.ParameterType;
Assert.IsFalse (type.IsValueType);
Assert.IsFalse (type.IsPrimitive);
Assert.IsFalse (type.IsPointer);
}
[Test]
public void FilterMaxStack ()
{
TestIL ("hello.il", module => {
var type = module.GetType ("Foo");
var method = type.GetMethod ("TestFilter");
Assert.IsNotNull (method);
Assert.AreEqual (2, method.Body.MaxStackSize);
});
}
[Test]
public void Iterator ()
{
TestModule ("iterator.exe", module => {
var method = module.GetType ("Program").GetMethod ("GetLittleArgs");
Assert.IsNotNull (method.Body);
});
}
[Test]
public void LoadString ()
{
TestCSharp ("CustomAttributes.cs", module => {
var type = module.GetType ("FooAttribute");
var get_fiou = type.GetMethod ("get_Fiou");
Assert.IsNotNull (get_fiou);
var ldstr = get_fiou.Body.Instructions.Where (i => i.OpCode == OpCodes.Ldstr).First ();
Assert.AreEqual ("fiou", ldstr.Operand);
});
}
[Test]
public void UnattachedMethodBody ()
{
var system_void = typeof (void).ToDefinition ();
var method = new MethodDefinition ("NewMethod", MethodAttributes.Assembly | MethodAttributes.Static, system_void);
var body = new MethodBody (method);
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ret);
method.Body = body;
Assert.AreEqual (body, method.Body);
}
static void AssertCode (string expected, MethodDefinition method)
{
Assert.IsTrue (method.HasBody);
Assert.IsNotNull (method.Body);
Assert.AreEqual (Normalize (expected), Normalize (Formatter.FormatMethodBody (method)));
}
static string Normalize (string str)
{
return str.Trim ().Replace ("\r\n", "\n");
}
[Test]
public void AddInstruction ()
{
var object_ref = new TypeReference ("System", "Object", null, null, false);
var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref);
var body = new MethodBody (method);
var il = body.GetILProcessor ();
var first = il.Create (OpCodes.Nop);
var second = il.Create (OpCodes.Nop);
body.Instructions.Add (first);
body.Instructions.Add (second);
Assert.IsNull (first.Previous);
Assert.AreEqual (second, first.Next);
Assert.AreEqual (first, second.Previous);
Assert.IsNull (second.Next);
}
[Test]
public void InsertInstruction ()
{
var object_ref = new TypeReference ("System", "Object", null, null, false);
var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref);
var body = new MethodBody (method);
var il = body.GetILProcessor ();
var first = il.Create (OpCodes.Nop);
var second = il.Create (OpCodes.Nop);
var third = il.Create (OpCodes.Nop);
body.Instructions.Add (first);
body.Instructions.Add (third);
Assert.IsNull (first.Previous);
Assert.AreEqual (third, first.Next);
Assert.AreEqual (first, third.Previous);
Assert.IsNull (third.Next);
body.Instructions.Insert (1, second);
Assert.IsNull (first.Previous);
Assert.AreEqual (second, first.Next);
Assert.AreEqual (first, second.Previous);
Assert.AreEqual (third, second.Next);
Assert.AreEqual (second, third.Previous);
Assert.IsNull (third.Next);
}
[Test]
public void InsertAfterLastInstruction ()
{
var object_ref = new TypeReference ("System", "Object", null, null, false);
var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref);
var body = new MethodBody (method);
var il = body.GetILProcessor ();
var first = il.Create (OpCodes.Nop);
var second = il.Create (OpCodes.Nop);
var third = il.Create (OpCodes.Nop);
body.Instructions.Add (first);
body.Instructions.Add (second);
Assert.IsNull (first.Previous);
Assert.AreEqual (second, first.Next);
Assert.AreEqual (first, second.Previous);
Assert.IsNull (second.Next);
body.Instructions.Insert (2, third);
Assert.IsNull (first.Previous);
Assert.AreEqual (second, first.Next);
Assert.AreEqual (first, second.Previous);
Assert.AreEqual (third, second.Next);
Assert.AreEqual (second, third.Previous);
Assert.IsNull (third.Next);
}
[Test]
public void RemoveInstruction ()
{
var object_ref = new TypeReference ("System", "Object", null, null, false);
var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref);
var body = new MethodBody (method);
var il = body.GetILProcessor ();
var first = il.Create (OpCodes.Nop);
var second = il.Create (OpCodes.Nop);
var third = il.Create (OpCodes.Nop);
body.Instructions.Add (first);
body.Instructions.Add (second);
body.Instructions.Add (third);
Assert.IsNull (first.Previous);
Assert.AreEqual (second, first.Next);
Assert.AreEqual (first, second.Previous);
Assert.AreEqual (third, second.Next);
Assert.AreEqual (second, third.Previous);
Assert.IsNull (third.Next);
body.Instructions.Remove (second);
Assert.IsNull (first.Previous);
Assert.AreEqual (third, first.Next);
Assert.AreEqual (first, third.Previous);
Assert.IsNull (third.Next);
}
}
}
| |
// 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.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
namespace System
{
public static class Console
{
// Unlike many other buffer sizes throughout .NET, which often only affect performance, this buffer size has a
// functional impact on interactive console apps, where the size of the buffer passed to ReadFile/Console impacts
// how many characters the cmd window will allow to be typed as part of a single line. It also does affect perf,
// in particular when input is redirected and data may be consumed from a larger source. This 4K default size is the
// same as is currently used by most other environments/languages tried.
internal const int ReadBufferSize = 4096;
// There's no visible functional impact to the write buffer size, and as we auto flush on every write,
// there's little benefit to having a large buffer. So we use a smaller buffer size to reduce working set.
private const int WriteBufferSize = 256;
private static object InternalSyncObject = new object(); // for synchronizing changing of Console's static fields
private static TextReader? s_in;
private static TextWriter? s_out, s_error;
private static Encoding? s_inputEncoding;
private static Encoding? s_outputEncoding;
private static bool s_isOutTextWriterRedirected = false;
private static bool s_isErrorTextWriterRedirected = false;
private static ConsoleCancelEventHandler? s_cancelCallbacks;
private static ConsolePal.ControlCHandlerRegistrar? s_registrar;
internal static T EnsureInitialized<T>([NotNull] ref T? field, Func<T> initializer) where T : class =>
LazyInitializer.EnsureInitialized(ref field, ref InternalSyncObject, initializer);
public static TextReader In => EnsureInitialized(ref s_in, () => ConsolePal.GetOrCreateReader());
public static Encoding InputEncoding
{
get
{
return EnsureInitialized(ref s_inputEncoding, () => ConsolePal.InputEncoding);
}
set
{
CheckNonNull(value, nameof(value));
lock (InternalSyncObject)
{
// Set the terminal console encoding.
ConsolePal.SetConsoleInputEncoding(value);
Volatile.Write(ref s_inputEncoding, (Encoding)value.Clone());
// We need to reinitialize 'Console.In' in the next call to s_in
// This will discard the current StreamReader, potentially
// losing buffered data.
Volatile.Write(ref s_in, null);
}
}
}
public static Encoding OutputEncoding
{
get
{
return EnsureInitialized(ref s_outputEncoding, () => ConsolePal.OutputEncoding);
}
set
{
CheckNonNull(value, nameof(value));
lock (InternalSyncObject)
{
// Set the terminal console encoding.
ConsolePal.SetConsoleOutputEncoding(value);
// Before changing the code page we need to flush the data
// if Out hasn't been redirected. Also, have the next call to
// s_out reinitialize the console code page.
if (Volatile.Read(ref s_out) != null && !s_isOutTextWriterRedirected)
{
s_out!.Flush();
Volatile.Write(ref s_out, null);
}
if (Volatile.Read(ref s_error) != null && !s_isErrorTextWriterRedirected)
{
s_error!.Flush();
Volatile.Write(ref s_error, null);
}
Volatile.Write(ref s_outputEncoding, (Encoding)value.Clone());
}
}
}
public static bool KeyAvailable
{
get
{
if (IsInputRedirected)
{
throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile);
}
return ConsolePal.KeyAvailable;
}
}
public static ConsoleKeyInfo ReadKey()
{
return ConsolePal.ReadKey(false);
}
public static ConsoleKeyInfo ReadKey(bool intercept)
{
return ConsolePal.ReadKey(intercept);
}
public static TextWriter Out => EnsureInitialized(ref s_out, () => CreateOutputWriter(OpenStandardOutput()));
public static TextWriter Error => EnsureInitialized(ref s_error, () => CreateOutputWriter(OpenStandardError()));
private static TextWriter CreateOutputWriter(Stream outputStream)
{
return TextWriter.Synchronized(outputStream == Stream.Null ?
StreamWriter.Null :
new StreamWriter(
stream: outputStream,
encoding: OutputEncoding.RemovePreamble(), // This ensures no prefix is written to the stream.
bufferSize: WriteBufferSize,
leaveOpen: true)
{
AutoFlush = true
});
}
private static StrongBox<bool>? _isStdInRedirected;
private static StrongBox<bool>? _isStdOutRedirected;
private static StrongBox<bool>? _isStdErrRedirected;
public static bool IsInputRedirected
{
get
{
StrongBox<bool> redirected = EnsureInitialized(ref _isStdInRedirected, () => new StrongBox<bool>(ConsolePal.IsInputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsOutputRedirected
{
get
{
StrongBox<bool> redirected = EnsureInitialized(ref _isStdOutRedirected, () => new StrongBox<bool>(ConsolePal.IsOutputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsErrorRedirected
{
get
{
StrongBox<bool> redirected = EnsureInitialized(ref _isStdErrRedirected, () => new StrongBox<bool>(ConsolePal.IsErrorRedirectedCore()));
return redirected.Value;
}
}
public static int CursorSize
{
get { return ConsolePal.CursorSize; }
set { ConsolePal.CursorSize = value; }
}
public static bool NumberLock
{
get { return ConsolePal.NumberLock; }
}
public static bool CapsLock
{
get { return ConsolePal.CapsLock; }
}
internal const ConsoleColor UnknownColor = (ConsoleColor)(-1);
public static ConsoleColor BackgroundColor
{
get { return ConsolePal.BackgroundColor; }
set { ConsolePal.BackgroundColor = value; }
}
public static ConsoleColor ForegroundColor
{
get { return ConsolePal.ForegroundColor; }
set { ConsolePal.ForegroundColor = value; }
}
public static void ResetColor()
{
ConsolePal.ResetColor();
}
public static int BufferWidth
{
get { return ConsolePal.BufferWidth; }
set { ConsolePal.BufferWidth = value; }
}
public static int BufferHeight
{
get { return ConsolePal.BufferHeight; }
set { ConsolePal.BufferHeight = value; }
}
public static void SetBufferSize(int width, int height)
{
ConsolePal.SetBufferSize(width, height);
}
public static int WindowLeft
{
get { return ConsolePal.WindowLeft; }
set { ConsolePal.WindowLeft = value; }
}
public static int WindowTop
{
get { return ConsolePal.WindowTop; }
set { ConsolePal.WindowTop = value; }
}
public static int WindowWidth
{
get { return ConsolePal.WindowWidth; }
set { ConsolePal.WindowWidth = value; }
}
public static int WindowHeight
{
get { return ConsolePal.WindowHeight; }
set { ConsolePal.WindowHeight = value; }
}
public static void SetWindowPosition(int left, int top)
{
ConsolePal.SetWindowPosition(left, top);
}
public static void SetWindowSize(int width, int height)
{
ConsolePal.SetWindowSize(width, height);
}
public static int LargestWindowWidth
{
get { return ConsolePal.LargestWindowWidth; }
}
public static int LargestWindowHeight
{
get { return ConsolePal.LargestWindowHeight; }
}
public static bool CursorVisible
{
get { return ConsolePal.CursorVisible; }
set { ConsolePal.CursorVisible = value; }
}
public static int CursorLeft
{
get { return ConsolePal.CursorLeft; }
set { SetCursorPosition(value, CursorTop); }
}
public static int CursorTop
{
get { return ConsolePal.CursorTop; }
set { SetCursorPosition(CursorLeft, value); }
}
public static string Title
{
get { return ConsolePal.Title; }
set
{
ConsolePal.Title = value ?? throw new ArgumentNullException(nameof(value));
}
}
public static void Beep()
{
ConsolePal.Beep();
}
public static void Beep(int frequency, int duration)
{
ConsolePal.Beep(frequency, duration);
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop)
{
ConsolePal.MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, ' ', ConsoleColor.Black, BackgroundColor);
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor)
{
ConsolePal.MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, sourceChar, sourceForeColor, sourceBackColor);
}
public static void Clear()
{
ConsolePal.Clear();
}
public static void SetCursorPosition(int left, int top)
{
// Basic argument validation. The PAL implementation may provide further validation.
if (left < 0 || left >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (top < 0 || top >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
ConsolePal.SetCursorPosition(left, top);
}
public static event ConsoleCancelEventHandler? CancelKeyPress
{
add
{
lock (InternalSyncObject)
{
s_cancelCallbacks += value;
// If we haven't registered our control-C handler, do it.
if (s_registrar == null)
{
s_registrar = new ConsolePal.ControlCHandlerRegistrar();
s_registrar.Register();
}
}
}
remove
{
lock (InternalSyncObject)
{
s_cancelCallbacks -= value;
if (s_registrar != null && s_cancelCallbacks == null)
{
s_registrar.Unregister();
s_registrar = null;
}
}
}
}
public static bool TreatControlCAsInput
{
get { return ConsolePal.TreatControlCAsInput; }
set { ConsolePal.TreatControlCAsInput = value; }
}
public static Stream OpenStandardInput()
{
return ConsolePal.OpenStandardInput();
}
public static Stream OpenStandardInput(int bufferSize)
{
// bufferSize is ignored, other than in argument validation, even in the .NET Framework
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
return OpenStandardInput();
}
public static Stream OpenStandardOutput()
{
return ConsolePal.OpenStandardOutput();
}
public static Stream OpenStandardOutput(int bufferSize)
{
// bufferSize is ignored, other than in argument validation, even in the .NET Framework
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
return OpenStandardOutput();
}
public static Stream OpenStandardError()
{
return ConsolePal.OpenStandardError();
}
public static Stream OpenStandardError(int bufferSize)
{
// bufferSize is ignored, other than in argument validation, even in the .NET Framework
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
return OpenStandardError();
}
public static void SetIn(TextReader newIn)
{
CheckNonNull(newIn, nameof(newIn));
newIn = SyncTextReader.GetSynchronizedTextReader(newIn);
lock (InternalSyncObject)
{
Volatile.Write(ref s_in, newIn);
}
}
public static void SetOut(TextWriter newOut)
{
CheckNonNull(newOut, nameof(newOut));
newOut = TextWriter.Synchronized(newOut);
Volatile.Write(ref s_isOutTextWriterRedirected, true);
lock (InternalSyncObject)
{
Volatile.Write(ref s_out, newOut);
}
}
public static void SetError(TextWriter newError)
{
CheckNonNull(newError, nameof(newError));
newError = TextWriter.Synchronized(newError);
Volatile.Write(ref s_isErrorTextWriterRedirected, true);
lock (InternalSyncObject)
{
Volatile.Write(ref s_error, newError);
}
}
private static void CheckNonNull(object obj, string paramName)
{
if (obj == null)
throw new ArgumentNullException(paramName);
}
//
// Give a hint to the code generator to not inline the common console methods. The console methods are
// not performance critical. It is unnecessary code bloat to have them inlined.
//
// Moreover, simple repros for codegen bugs are often console-based. It is tedious to manually filter out
// the inlined console writelines from them.
//
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int Read()
{
return In.Read();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static string? ReadLine()
{
return In.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine()
{
Out.WriteLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(bool value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[]? buffer)
{
Out.WriteLine(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer, int index, int count)
{
Out.WriteLine(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(decimal value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(double value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(float value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(int value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(uint value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(long value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(ulong value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(object? value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(string? value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(string format, object? arg0)
{
Out.WriteLine(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(string format, object? arg0, object? arg1)
{
Out.WriteLine(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(string format, object? arg0, object? arg1, object? arg2)
{
Out.WriteLine(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(string format, params object?[]? arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.WriteLine(format, null, null); // faster than Out.WriteLine(format, (Object)arg);
else
Out.WriteLine(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(string format, object? arg0)
{
Out.Write(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(string format, object? arg0, object? arg1)
{
Out.Write(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(string format, object? arg0, object? arg1, object? arg2)
{
Out.Write(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(string format, params object?[]? arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.Write(format, null, null); // faster than Out.Write(format, (Object)arg);
else
Out.Write(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(bool value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[]? buffer)
{
Out.Write(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer, int index, int count)
{
Out.Write(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(double value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(decimal value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(float value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(int value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(uint value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(long value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(ulong value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(object? value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(string? value)
{
Out.Write(value);
}
internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey)
{
ConsoleCancelEventHandler? handler = s_cancelCallbacks;
if (handler == null)
{
return false;
}
var args = new ConsoleCancelEventArgs(controlKey);
handler(null, args);
return args.Cancel;
}
}
}
| |
using System;
using System.Threading;
using System.Diagnostics;
namespace Amib.Threading.Internal
{
/// <summary>
/// Holds a callback delegate and the state for that delegate.
/// </summary>
public partial class WorkItem : IHasWorkItemPriority
{
#region WorkItemState enum
/// <summary>
/// Indicates the state of the work item in the thread pool
/// </summary>
private enum WorkItemState
{
InQueue = 0, // Nexts: InProgress, Canceled
InProgress = 1, // Nexts: Completed, Canceled
Completed = 2, // Stays Completed
Canceled = 3, // Stays Canceled
}
private static bool IsValidStatesTransition(WorkItemState currentState, WorkItemState nextState)
{
bool valid = false;
switch (currentState)
{
case WorkItemState.InQueue:
valid = (WorkItemState.InProgress == nextState) || (WorkItemState.Canceled == nextState);
break;
case WorkItemState.InProgress:
valid = (WorkItemState.Completed == nextState) || (WorkItemState.Canceled == nextState);
break;
case WorkItemState.Completed:
case WorkItemState.Canceled:
// Cannot be changed
break;
default:
// Unknown state
Debug.Assert(false);
break;
}
return valid;
}
#endregion
#region Fields
/// <summary>
/// Callback delegate for the callback.
/// </summary>
private readonly WorkItemCallback _callback;
/// <summary>
/// State with which to call the callback delegate.
/// </summary>
private object _state;
#if !(_WINDOWS_CE) && !(_SILVERLIGHT) && !(WINDOWS_PHONE) && !(NO_SYSTEM_WEB)
/// <summary>
/// Stores the caller's context
/// </summary>
private readonly CallerThreadContext _callerContext;
#endif
/// <summary>
/// Holds the result of the mehtod
/// </summary>
private object _result;
/// <summary>
/// Hold the exception if the method threw it
/// </summary>
private Exception _exception;
/// <summary>
/// Hold the state of the work item
/// </summary>
private WorkItemState _workItemState;
/// <summary>
/// A ManualResetEvent to indicate that the result is ready
/// </summary>
private ManualResetEvent _workItemCompleted;
/// <summary>
/// A reference count to the _workItemCompleted.
/// When it reaches to zero _workItemCompleted is Closed
/// </summary>
private int _workItemCompletedRefCount;
/// <summary>
/// Represents the result state of the work item
/// </summary>
private readonly WorkItemResult _workItemResult;
/// <summary>
/// Work item info
/// </summary>
private readonly WorkItemInfo _workItemInfo;
/// <summary>
/// Called when the WorkItem starts
/// </summary>
private event WorkItemStateCallback _workItemStartedEvent;
/// <summary>
/// Called when the WorkItem completes
/// </summary>
private event WorkItemStateCallback _workItemCompletedEvent;
/// <summary>
/// A reference to an object that indicates whatever the
/// WorkItemsGroup has been canceled
/// </summary>
private CanceledWorkItemsGroup _canceledWorkItemsGroup = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup;
/// <summary>
/// A reference to an object that indicates whatever the
/// SmartThreadPool has been canceled
/// </summary>
private CanceledWorkItemsGroup _canceledSmartThreadPool = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup;
/// <summary>
/// The work item group this work item belong to.
/// </summary>
private readonly IWorkItemsGroup _workItemsGroup;
/// <summary>
/// The thread that executes this workitem.
/// This field is available for the period when the work item is executed, before and after it is null.
/// </summary>
private Thread _executingThread;
/// <summary>
/// The absulote time when the work item will be timeout
/// </summary>
private long _expirationTime;
#region Performance Counter fields
/// <summary>
/// Stores how long the work item waited on the stp queue
/// </summary>
private Stopwatch _waitingOnQueueStopwatch;
/// <summary>
/// Stores how much time it took the work item to execute after it went out of the queue
/// </summary>
private Stopwatch _processingStopwatch;
#endregion
#endregion
#region Properties
public TimeSpan WaitingTime
{
get
{
return _waitingOnQueueStopwatch.Elapsed;
}
}
public TimeSpan ProcessTime
{
get
{
return _processingStopwatch.Elapsed;
}
}
internal WorkItemInfo WorkItemInfo
{
get
{
return _workItemInfo;
}
}
#endregion
#region Construction
/// <summary>
/// Initialize the callback holding object.
/// </summary>
/// <param name="workItemsGroup">The workItemGroup of the workitem</param>
/// <param name="workItemInfo">The WorkItemInfo of te workitem</param>
/// <param name="callback">Callback delegate for the callback.</param>
/// <param name="state">State with which to call the callback delegate.</param>
///
/// We assume that the WorkItem object is created within the thread
/// that meant to run the callback
public WorkItem(
IWorkItemsGroup workItemsGroup,
WorkItemInfo workItemInfo,
WorkItemCallback callback,
object state)
{
_workItemsGroup = workItemsGroup;
_workItemInfo = workItemInfo;
#if !(_WINDOWS_CE) && !(_SILVERLIGHT) && !(WINDOWS_PHONE) && !(NO_SYSTEM_WEB)
if (_workItemInfo.UseCallerCallContext || _workItemInfo.UseCallerHttpContext)
{
_callerContext = CallerThreadContext.Capture(_workItemInfo.UseCallerCallContext, _workItemInfo.UseCallerHttpContext);
}
#endif
_callback = callback;
_state = state;
_workItemResult = new WorkItemResult(this);
Initialize();
}
internal void Initialize()
{
// The _workItemState is changed directly instead of using the SetWorkItemState
// method since we don't want to go throught IsValidStateTransition.
_workItemState = WorkItemState.InQueue;
_workItemCompleted = null;
_workItemCompletedRefCount = 0;
_waitingOnQueueStopwatch = new Stopwatch();
_processingStopwatch = new Stopwatch();
_expirationTime =
_workItemInfo.Timeout > 0 ?
DateTime.UtcNow.Ticks + _workItemInfo.Timeout * TimeSpan.TicksPerMillisecond :
long.MaxValue;
}
internal bool WasQueuedBy(IWorkItemsGroup workItemsGroup)
{
return (workItemsGroup == _workItemsGroup);
}
#endregion
#region Methods
internal CanceledWorkItemsGroup CanceledWorkItemsGroup
{
get { return _canceledWorkItemsGroup; }
set { _canceledWorkItemsGroup = value; }
}
internal CanceledWorkItemsGroup CanceledSmartThreadPool
{
get { return _canceledSmartThreadPool; }
set { _canceledSmartThreadPool = value; }
}
/// <summary>
/// Change the state of the work item to in progress if it wasn't canceled.
/// </summary>
/// <returns>
/// Return true on success or false in case the work item was canceled.
/// If the work item needs to run a post execute then the method will return true.
/// </returns>
public bool StartingWorkItem()
{
_waitingOnQueueStopwatch.Stop();
_processingStopwatch.Start();
lock (this)
{
if (IsCanceled)
{
bool result = false;
if ((_workItemInfo.PostExecuteWorkItemCallback != null) &&
((_workItemInfo.CallToPostExecute & CallToPostExecute.WhenWorkItemCanceled) == CallToPostExecute.WhenWorkItemCanceled))
{
result = true;
}
return result;
}
Debug.Assert(WorkItemState.InQueue == GetWorkItemState());
// No need for a lock yet, only after the state has changed to InProgress
_executingThread = Thread.CurrentThread;
SetWorkItemState(WorkItemState.InProgress);
}
return true;
}
/// <summary>
/// Execute the work item and the post execute
/// </summary>
public void Execute()
{
CallToPostExecute currentCallToPostExecute = 0;
// Execute the work item if we are in the correct state
switch (GetWorkItemState())
{
case WorkItemState.InProgress:
currentCallToPostExecute |= CallToPostExecute.WhenWorkItemNotCanceled;
ExecuteWorkItem();
break;
case WorkItemState.Canceled:
currentCallToPostExecute |= CallToPostExecute.WhenWorkItemCanceled;
break;
default:
Debug.Assert(false);
throw new NotSupportedException();
}
// Run the post execute as needed
if ((currentCallToPostExecute & _workItemInfo.CallToPostExecute) != 0)
{
PostExecute();
}
_processingStopwatch.Stop();
}
internal void FireWorkItemCompleted()
{
try
{
if (null != _workItemCompletedEvent)
{
_workItemCompletedEvent(this);
}
}
catch // Suppress exceptions
{ }
}
internal void FireWorkItemStarted()
{
try
{
if (null != _workItemStartedEvent)
{
_workItemStartedEvent(this);
}
}
catch // Suppress exceptions
{ }
}
/// <summary>
/// Execute the work item
/// </summary>
private void ExecuteWorkItem()
{
#if !(_WINDOWS_CE) && !(_SILVERLIGHT) && !(WINDOWS_PHONE) && !(NO_SYSTEM_WEB)
CallerThreadContext ctc = null;
if (null != _callerContext)
{
ctc = CallerThreadContext.Capture(_callerContext.CapturedCallContext, _callerContext.CapturedHttpContext);
CallerThreadContext.Apply(_callerContext);
}
#endif
Exception exception = null;
object result = null;
try
{
try
{
result = _callback(_state);
}
catch (Exception e)
{
// Save the exception so we can rethrow it later
exception = e;
}
// Remove the value of the execution thread, so it will be impossible to cancel the work item,
// since it is already completed.
// Cancelling a work item that already completed may cause the abortion of the next work item!!!
Thread executionThread = Interlocked.CompareExchange(ref _executingThread, null, _executingThread);
if (null == executionThread)
{
// Oops! we are going to be aborted..., Wait here so we can catch the ThreadAbortException
Thread.Sleep(60 * 1000);
// If after 1 minute this thread was not aborted then let it continue working.
}
}
// We must treat the ThreadAbortException or else it will be stored in the exception variable
catch (ThreadAbortException tae)
{
tae.GetHashCode();
// Check if the work item was cancelled
// If we got a ThreadAbortException and the STP is not shutting down, it means the
// work items was cancelled.
if (!SmartThreadPool.CurrentThreadEntry.AssociatedSmartThreadPool.IsShuttingdown)
{
#if !(_WINDOWS_CE) && !(_SILVERLIGHT) && !(WINDOWS_PHONE)
Thread.ResetAbort();
#endif
}
}
#if !(_WINDOWS_CE) && !(_SILVERLIGHT) && !(WINDOWS_PHONE) && !(NO_SYSTEM_WEB)
if (null != _callerContext)
{
CallerThreadContext.Apply(ctc);
}
#endif
if (!SmartThreadPool.IsWorkItemCanceled)
{
SetResult(result, exception);
}
}
/// <summary>
/// Runs the post execute callback
/// </summary>
private void PostExecute()
{
if (null != _workItemInfo.PostExecuteWorkItemCallback)
{
try
{
_workItemInfo.PostExecuteWorkItemCallback(_workItemResult);
}
catch (Exception e)
{
Debug.Assert(null != e);
}
}
}
/// <summary>
/// Set the result of the work item to return
/// </summary>
/// <param name="result">The result of the work item</param>
/// <param name="exception">The exception that was throw while the workitem executed, null
/// if there was no exception.</param>
internal void SetResult(object result, Exception exception)
{
_result = result;
_exception = exception;
SignalComplete(false);
}
/// <summary>
/// Returns the work item result
/// </summary>
/// <returns>The work item result</returns>
internal IWorkItemResult GetWorkItemResult()
{
return _workItemResult;
}
/// <summary>
/// Wait for all work items to complete
/// </summary>
/// <param name="waitableResults">Array of work item result objects</param>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
/// <param name="exitContext">
/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
/// </param>
/// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
/// <returns>
/// true when every work item in waitableResults has completed; otherwise false.
/// </returns>
internal static bool WaitAll(
IWaitableResult[] waitableResults,
int millisecondsTimeout,
bool exitContext,
WaitHandle cancelWaitHandle)
{
if (0 == waitableResults.Length)
{
return true;
}
bool success;
WaitHandle[] waitHandles = new WaitHandle[waitableResults.Length];
GetWaitHandles(waitableResults, waitHandles);
if ((null == cancelWaitHandle) && (waitHandles.Length <= 64))
{
success = STPEventWaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext);
}
else
{
success = true;
int millisecondsLeft = millisecondsTimeout;
Stopwatch stopwatch = Stopwatch.StartNew();
WaitHandle[] whs;
if (null != cancelWaitHandle)
{
whs = new WaitHandle[] { null, cancelWaitHandle };
}
else
{
whs = new WaitHandle[] { null };
}
bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
// Iterate over the wait handles and wait for each one to complete.
// We cannot use WaitHandle.WaitAll directly, because the cancelWaitHandle
// won't affect it.
// Each iteration we update the time left for the timeout.
for (int i = 0; i < waitableResults.Length; ++i)
{
// WaitAny don't work with negative numbers
if (!waitInfinitely && (millisecondsLeft < 0))
{
success = false;
break;
}
whs[0] = waitHandles[i];
int result = STPEventWaitHandle.WaitAny(whs, millisecondsLeft, exitContext);
if ((result > 0) || (STPEventWaitHandle.WaitTimeout == result))
{
success = false;
break;
}
if (!waitInfinitely)
{
// Update the time left to wait
millisecondsLeft = millisecondsTimeout - (int)stopwatch.ElapsedMilliseconds;
}
}
}
// Release the wait handles
ReleaseWaitHandles(waitableResults);
return success;
}
/// <summary>
/// Waits for any of the work items in the specified array to complete, cancel, or timeout
/// </summary>
/// <param name="waitableResults">Array of work item result objects</param>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
/// <param name="exitContext">
/// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
/// </param>
/// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
/// <returns>
/// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
/// </returns>
internal static int WaitAny(
IWaitableResult[] waitableResults,
int millisecondsTimeout,
bool exitContext,
WaitHandle cancelWaitHandle)
{
WaitHandle[] waitHandles;
if (null != cancelWaitHandle)
{
waitHandles = new WaitHandle[waitableResults.Length + 1];
GetWaitHandles(waitableResults, waitHandles);
waitHandles[waitableResults.Length] = cancelWaitHandle;
}
else
{
waitHandles = new WaitHandle[waitableResults.Length];
GetWaitHandles(waitableResults, waitHandles);
}
int result = STPEventWaitHandle.WaitAny(waitHandles, millisecondsTimeout, exitContext);
// Treat cancel as timeout
if (null != cancelWaitHandle)
{
if (result == waitableResults.Length)
{
result = STPEventWaitHandle.WaitTimeout;
}
}
ReleaseWaitHandles(waitableResults);
return result;
}
/// <summary>
/// Fill an array of wait handles with the work items wait handles.
/// </summary>
/// <param name="waitableResults">An array of work item results</param>
/// <param name="waitHandles">An array of wait handles to fill</param>
private static void GetWaitHandles(
IWaitableResult[] waitableResults,
WaitHandle[] waitHandles)
{
for (int i = 0; i < waitableResults.Length; ++i)
{
WorkItemResult wir = waitableResults[i].GetWorkItemResult() as WorkItemResult;
Debug.Assert(null != wir, "All waitableResults must be WorkItemResult objects");
waitHandles[i] = wir.GetWorkItem().GetWaitHandle();
}
}
/// <summary>
/// Release the work items' wait handles
/// </summary>
/// <param name="waitableResults">An array of work item results</param>
private static void ReleaseWaitHandles(IWaitableResult[] waitableResults)
{
for (int i = 0; i < waitableResults.Length; ++i)
{
WorkItemResult wir = (WorkItemResult)waitableResults[i].GetWorkItemResult();
wir.GetWorkItem().ReleaseWaitHandle();
}
}
#endregion
#region Private Members
private WorkItemState GetWorkItemState()
{
lock (this)
{
if (WorkItemState.Completed == _workItemState)
{
return _workItemState;
}
long nowTicks = DateTime.UtcNow.Ticks;
if (WorkItemState.Canceled != _workItemState && nowTicks > _expirationTime)
{
_workItemState = WorkItemState.Canceled;
}
if (WorkItemState.InProgress == _workItemState)
{
return _workItemState;
}
if (CanceledSmartThreadPool.IsCanceled || CanceledWorkItemsGroup.IsCanceled)
{
return WorkItemState.Canceled;
}
return _workItemState;
}
}
/// <summary>
/// Sets the work item's state
/// </summary>
/// <param name="workItemState">The state to set the work item to</param>
private void SetWorkItemState(WorkItemState workItemState)
{
lock (this)
{
if (IsValidStatesTransition(_workItemState, workItemState))
{
_workItemState = workItemState;
}
}
}
/// <summary>
/// Signals that work item has been completed or canceled
/// </summary>
/// <param name="canceled">Indicates that the work item has been canceled</param>
private void SignalComplete(bool canceled)
{
SetWorkItemState(canceled ? WorkItemState.Canceled : WorkItemState.Completed);
lock (this)
{
// If someone is waiting then signal.
if (null != _workItemCompleted)
{
_workItemCompleted.Set();
}
}
}
internal void WorkItemIsQueued()
{
_waitingOnQueueStopwatch.Start();
}
#endregion
#region Members exposed by WorkItemResult
/// <summary>
/// Cancel the work item if it didn't start running yet.
/// </summary>
/// <returns>Returns true on success or false if the work item is in progress or already completed</returns>
private bool Cancel(bool abortExecution)
{
#if (_WINDOWS_CE)
if(abortExecution)
{
throw new ArgumentOutOfRangeException("abortExecution", "WindowsCE doesn't support this feature");
}
#endif
bool success = false;
bool signalComplete = false;
lock (this)
{
switch (GetWorkItemState())
{
case WorkItemState.Canceled:
//Debug.WriteLine("Work item already canceled");
if (abortExecution)
{
Thread executionThread = Interlocked.CompareExchange(ref _executingThread, null, _executingThread);
if (null != executionThread)
{
executionThread.Abort(); // "Cancel"
// No need to signalComplete, because we already cancelled this work item
// so it already signaled its completion.
//signalComplete = true;
}
}
success = true;
break;
case WorkItemState.Completed:
//Debug.WriteLine("Work item cannot be canceled");
break;
case WorkItemState.InProgress:
if (abortExecution)
{
Thread executionThread = Interlocked.CompareExchange(ref _executingThread, null, _executingThread);
if (null != executionThread)
{
executionThread.Abort(); // "Cancel"
success = true;
signalComplete = true;
}
}
else
{
success = true;
signalComplete = true;
}
break;
case WorkItemState.InQueue:
// Signal to the wait for completion that the work
// item has been completed (canceled). There is no
// reason to wait for it to get out of the queue
signalComplete = true;
//Debug.WriteLine("Work item canceled");
success = true;
break;
}
if (signalComplete)
{
SignalComplete(true);
}
}
return success;
}
/// <summary>
/// Get the result of the work item.
/// If the work item didn't run yet then the caller waits for the result, timeout, or cancel.
/// In case of error the method throws and exception
/// </summary>
/// <returns>The result of the work item</returns>
private object GetResult(
int millisecondsTimeout,
bool exitContext,
WaitHandle cancelWaitHandle)
{
Exception e;
object result = GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e);
if (null != e)
{
throw new WorkItemResultException("The work item caused an excpetion, see the inner exception for details", e);
}
return result;
}
/// <summary>
/// Get the result of the work item.
/// If the work item didn't run yet then the caller waits for the result, timeout, or cancel.
/// In case of error the e argument is filled with the exception
/// </summary>
/// <returns>The result of the work item</returns>
private object GetResult(
int millisecondsTimeout,
bool exitContext,
WaitHandle cancelWaitHandle,
out Exception e)
{
e = null;
// Check for cancel
if (WorkItemState.Canceled == GetWorkItemState())
{
throw new WorkItemCancelException("Work item canceled");
}
// Check for completion
if (IsCompleted)
{
e = _exception;
return _result;
}
// If no cancelWaitHandle is provided
if (null == cancelWaitHandle)
{
WaitHandle wh = GetWaitHandle();
bool timeout = !STPEventWaitHandle.WaitOne(wh, millisecondsTimeout, exitContext);
ReleaseWaitHandle();
if (timeout)
{
throw new WorkItemTimeoutException("Work item timeout");
}
}
else
{
WaitHandle wh = GetWaitHandle();
int result = STPEventWaitHandle.WaitAny(new WaitHandle[] { wh, cancelWaitHandle });
ReleaseWaitHandle();
switch (result)
{
case 0:
// The work item signaled
// Note that the signal could be also as a result of canceling the
// work item (not the get result)
break;
case 1:
case STPEventWaitHandle.WaitTimeout:
throw new WorkItemTimeoutException("Work item timeout");
default:
Debug.Assert(false);
break;
}
}
// Check for cancel
if (WorkItemState.Canceled == GetWorkItemState())
{
throw new WorkItemCancelException("Work item canceled");
}
Debug.Assert(IsCompleted);
e = _exception;
// Return the result
return _result;
}
/// <summary>
/// A wait handle to wait for completion, cancel, or timeout
/// </summary>
private WaitHandle GetWaitHandle()
{
lock (this)
{
if (null == _workItemCompleted)
{
_workItemCompleted = EventWaitHandleFactory.CreateManualResetEvent(IsCompleted);
}
++_workItemCompletedRefCount;
}
return _workItemCompleted;
}
private void ReleaseWaitHandle()
{
lock (this)
{
if (null != _workItemCompleted)
{
--_workItemCompletedRefCount;
if (0 == _workItemCompletedRefCount)
{
_workItemCompleted.Close();
_workItemCompleted = null;
}
}
}
}
/// <summary>
/// Returns true when the work item has completed or canceled
/// </summary>
private bool IsCompleted
{
get
{
lock (this)
{
WorkItemState workItemState = GetWorkItemState();
return ((workItemState == WorkItemState.Completed) ||
(workItemState == WorkItemState.Canceled));
}
}
}
/// <summary>
/// Returns true when the work item has canceled
/// </summary>
public bool IsCanceled
{
get
{
lock (this)
{
return (GetWorkItemState() == WorkItemState.Canceled);
}
}
}
#endregion
#region IHasWorkItemPriority Members
/// <summary>
/// Returns the priority of the work item
/// </summary>
public WorkItemPriority WorkItemPriority
{
get
{
return _workItemInfo.WorkItemPriority;
}
}
#endregion
internal event WorkItemStateCallback OnWorkItemStarted
{
add
{
_workItemStartedEvent += value;
}
remove
{
_workItemStartedEvent -= value;
}
}
internal event WorkItemStateCallback OnWorkItemCompleted
{
add
{
_workItemCompletedEvent += value;
}
remove
{
_workItemCompletedEvent -= value;
}
}
public void DisposeOfState()
{
if (_workItemInfo.DisposeOfStateObjects)
{
IDisposable disp = _state as IDisposable;
if (null != disp)
{
disp.Dispose();
_state = null;
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace UniAppKids.ExternServiceController.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Spring.Collections;
using Spring.Util;
using Spring.Validation;
namespace Spring.DataBinding
{
/// <summary>
/// Abstract base class for <see cref="IBinding"/> implementations.
/// </summary>
/// <author>Aleksandar Seovic</author>
public abstract class AbstractBinding : IBinding
{
#region Fields
/// <summary>
/// The name of the always filled error provider
/// </summary>
public static readonly string ALL_BINDINGERRORS_PROVIDER = "__all_bindingerrors";
// each Binding instance needs its own ID
private readonly string BINDING_ID = Guid.NewGuid().ToString("N");
private BindingDirection direction = BindingDirection.Bidirectional;
private BindingErrorMessage errorMessage;
private string[] errorProviders;
#endregion
#region Properties
/// <summary>
/// Gets or sets a flag specifying whether this binding is valid.
/// </summary>
/// <value>
/// <c>true</c> if this binding evaluated without errors;
/// <c>false</c> otherwise.
/// </value>
public bool IsValid(IValidationErrors errors)
{
if (errors == null) return true;
IList<ErrorMessage> errorList = errors.GetErrors(ALL_BINDINGERRORS_PROVIDER);
return (errorList == null) || (!errorList.Contains(this.ErrorMessage));
}
/// <summary>
/// Marks this binding's state as invalid for this validationErrors collection.
/// Returns false if <paramref name="validationErrors"/> is null.
/// </summary>
/// <param name="validationErrors"></param>
/// <returns>false, if validationErrors is null</returns>
protected bool SetInvalid(IValidationErrors validationErrors)
{
if (validationErrors != null)
{
foreach (string provider in this.ErrorProviders)
{
validationErrors.AddError(provider, this.ErrorMessage);
}
return true;
}
return false;
}
///<summary>
/// Gets the unique ID of this binding instance.
///</summary>
public string Id
{
get { return BINDING_ID; }
}
/// <summary>
/// Gets or sets the <see cref="BindingDirection"/>.
/// </summary>
/// <value>The binding direction.</value>
public BindingDirection Direction
{
get { return direction; }
set { direction = value; }
}
/// <summary>
/// Gets the error message.
/// </summary>
/// <value>The error message.</value>
public BindingErrorMessage ErrorMessage
{
get { return errorMessage; }
}
/// <summary>
/// Gets the error providers.
/// </summary>
public string[] ErrorProviders
{
get { return errorProviders; }
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Object"></see> class.
/// </summary>
protected AbstractBinding()
{
this.errorMessage = new BindingErrorMessage( this.Id, "Binding-Error");
this.errorProviders = new string[] { ALL_BINDINGERRORS_PROVIDER };
}
#region IBinding Implementation
/// <summary>
/// Binds source object to target object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
public virtual void BindSourceToTarget(object source, object target, IValidationErrors validationErrors)
{
BindSourceToTarget(source, target, validationErrors, null);
}
/// <summary>
/// Binds target object to source object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
public virtual void BindTargetToSource(object source, object target, IValidationErrors validationErrors)
{
BindTargetToSource(source, target, validationErrors, null);
}
/// <summary>
/// Binds source object to target object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
/// <param name="variables">
/// Variables that should be used during expression evaluation.
/// </param>
public abstract void BindSourceToTarget(object source, object target, IValidationErrors validationErrors, IDictionary<string, object> variables);
/// <summary>
/// Binds target object to source object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
/// <param name="variables">
/// Variables that should be used during expression evaluation.
/// </param>
public abstract void BindTargetToSource(object source, object target, IValidationErrors validationErrors, IDictionary<string, object> variables);
/// <summary>
/// Sets error message that should be displayed in the case
/// of a non-fatal binding error.
/// </summary>
/// <param name="messageId">
/// Resource ID of the error message.
/// </param>
/// <param name="errorProviders">
/// List of error providers message should be added to.
/// </param>
public void SetErrorMessage(string messageId, params string[] errorProviders)
{
AssertUtils.ArgumentHasText(messageId, "messageId");
if (errorProviders == null || errorProviders.Length == 0)
{
throw new ArgumentException("At least one error provider has to be specified.", "providers");
}
this.errorMessage = new BindingErrorMessage(this.BINDING_ID, messageId, null);
Set providers = new HashedSet();
providers.Add(ALL_BINDINGERRORS_PROVIDER);
providers.AddAll(errorProviders);
errorProviders = new string[providers.Count];
providers.CopyTo(errorProviders, 0);
this.errorProviders = errorProviders;
}
#endregion
///<summary>
///Determines whether the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>.
///</summary>
///<returns>
///true if the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>; otherwise, false.
///</returns>
///<param name="obj">The <see cref="T:System.Object"></see> to compare with the current <see cref="T:System.Object"></see>. </param><filterpriority>2</filterpriority>
public override bool Equals(object obj)
{
AbstractBinding other = obj as AbstractBinding;
return (other != null) && (this.Id == other.Id);
}
///<summary>
///Serves as a hash function for a particular type. <see cref="M:System.Object.GetHashCode"></see> is suitable for use in hashing algorithms and data structures like a hash table.
///</summary>
///<returns>
///A hash code for the current <see cref="T:System.Object"></see>.
///</returns>
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Threading;
using System.Collections;
using OpenSource.UPnP;
using OpenSource.UPnP.AV;
using OpenSource.Utilities;
using OpenSource.UPnP.AV.CdsMetadata;
namespace OpenSource.UPnP.AV.RENDERER.CP
{
/// <summary>
/// AVRenderer Abstraction.
/// <para>
/// This is the container class that is used to interact with a Renderer at the physical level.
/// This object exposes all the events and methods necessary to manage rendering sessions, otherwise known as <see cref="OpenSource.UPnP.AVRENDERERSTACK.AVConnection"/>
/// To instansiate a new session, simply invoke <see cref="OpenSource.UPnP.AVRENDERERSTACK.AVRenderer.CreateConnection"/> and pass in IMediaResource(s) or IMediaItem(s). The
/// abstraction layer will automatically handle play list generation based on the capabilities of the renderer, and
/// will automatically determine which MediaItems are renderable on the device based on renderer capabilities.
/// </para>
/// <para>
/// The main points of interest in this object are the events you should subscribe to, when managing/controlling a renderer
/// <list type="bullet">
/// <item>
/// <term><see cref="OpenSource.UPnP.AVRENDERERSTACK.AVRenderer.OnCreateConnection"/></term>
/// <description>New Connection was created</description>
/// </item>
/// <item>
/// <term><see cref="OpenSource.UPnP.AVRENDERERSTACK.AVRenderer.OnRecycledConnection"/></term>
/// <description>Connection was reused</description>
/// </item>
/// <term><see cref="OpenSource.UPnP.AVRENDERERSTACK.AVRenderer.OnRemovedConnection"/></term>
/// <description>Connection was deleted</description>
/// <item>
/// </item>
/// </list>
/// </para>
/// </summary>
public class AVRenderer
{
private Hashtable PlayListTable = Hashtable.Synchronized(new Hashtable());
private object CreateConnectionLock = new object();
private int PendingCreateConnection = 0;
private LifeTimeMonitor ConnectionMonitor = new LifeTimeMonitor();
public delegate void EventRenewalFailureHandler(AVRenderer sender);
private WeakEvent EventRenewalFailureEvent = new WeakEvent();
public event EventRenewalFailureHandler OnEventRenewalFailure
{
add
{
EventRenewalFailureEvent.Register(value);
}
remove
{
EventRenewalFailureEvent.UnRegister(value);
}
}
protected bool DontEverDelete = false;
/// <summary>
/// The reasons the AVRenderer will report that a CreateConnection attempt failed.
/// </summary>
public enum CreateFailedReason
{
/// <summary>
/// This means that the MediaType(s) supported by the renderer do not match that of the given IMediaResource
/// </summary>
UNSUPPORTED_MEDIA_ITEM,
/// <summary>
/// This has many possible reasons. Some of which include an error in handling the request on the server side, or not enough
/// resources being available on the server, or too many connections on the server, etc.
/// </summary>
CREATE_ATTEMPT_DENIED,
SetAVTransport_FAILED,
}
public delegate void OnInitializedHandler(AVRenderer sender);
public event OnInitializedHandler OnInitialized;
private bool __Init = false;
public bool IsInit
{
get
{
return(__Init);
}
}
public delegate void FailedConnectionHandler(AVRenderer sender, CreateFailedReason reason, object Tag);
private WeakEvent OnCreateConnectionFailedEvent = new WeakEvent();
private WeakEvent OnCreateConnectionFailedEvent2 = new WeakEvent();
/// <summary>
/// This will be fired when a CreateConnection attempt failed
/// </summary>
public event FailedConnectionHandler OnCreateConnectionFailed
{
add
{
OnCreateConnectionFailedEvent.Register(value);
}
remove
{
OnCreateConnectionFailedEvent.UnRegister(value);
}
}
/// <summary>
/// This event is used exclusively by the AVPlayList class. It is triggered the same
/// as the other OnCreateConnection event, except this one also triggers
/// when PrepareForConnection completes
/// </summary>
internal event FailedConnectionHandler OnCreateConnectionFailed2
{
add
{
OnCreateConnectionFailedEvent2.Register(value);
}
remove
{
OnCreateConnectionFailedEvent2.UnRegister(value);
}
}
public delegate void ConnectionHandler(AVRenderer sender, AVConnection r, object Tag);
private WeakEvent OnCreateConnectionEvent = new WeakEvent();
private WeakEvent OnCreateConnectionEvent2 = new WeakEvent();
/// <summary>
/// This will be fired when a CreateConnection attempt resulted in a new Session
/// </summary>
public event ConnectionHandler OnCreateConnection
{
add
{
OnCreateConnectionEvent.Register(value);
}
remove
{
OnCreateConnectionEvent.UnRegister(value);
}
}
/// <summary>
/// This event is used exclusively by the AVPlayList class. It is triggered the same
/// as the other OnCreateConnection event, except this one also triggers
/// when PrepareForConnection completes
/// </summary>
internal event ConnectionHandler OnCreateConnection2
{
add
{
OnCreateConnectionEvent2.Register(value);
}
remove
{
OnCreateConnectionEvent2.UnRegister(value);
}
}
private WeakEvent OnRecycledConnectionEvent = new WeakEvent();
private WeakEvent OnRecycledConnectionEvent2 = new WeakEvent();
/// <summary>
/// This will be fired when a CreateConnection attempt resulted in the reuse of an existing connection.
/// </summary>
public event ConnectionHandler OnRecycledConnection
{
add
{
OnRecycledConnectionEvent.Register(value);
}
remove
{
OnRecycledConnectionEvent.UnRegister(value);
}
}
/// <summary>
/// This event is used exclusively by the AVPlayList class. It is triggered the same
/// as the other OnRecycledConnection event, except this one also triggers
/// when PrepareForConnection completes
/// </summary>
internal event ConnectionHandler OnRecycledConnection2
{
add
{
OnRecycledConnectionEvent2.Register(value);
}
remove
{
OnRecycledConnectionEvent2.UnRegister(value);
}
}
private WeakEvent OnRemovedConnectionEvent = new WeakEvent();
/// <summary>
/// This will be fired when a connection has closed
/// </summary>
public event ConnectionHandler OnRemovedConnection
{
add
{
OnRemovedConnectionEvent.Register(value);
}
remove
{
OnRemovedConnectionEvent.UnRegister(value);
}
}
internal CpConnectionManager ConnectionManager;
internal UPnPDevice MainDevice;
protected ArrayList InstanceList = new ArrayList();
protected ArrayList ProtocolInfoList = new ArrayList();
protected Hashtable HandleTable = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// This returns the UPnPDevice object associated with this renderer
/// </summary>
public UPnPDevice device
{
get
{
return(MainDevice);
}
}
/// <summary>
/// This constructor is called with the UPnPDevice that contains the services of a MediaRenderer device.
/// </summary>
/// <param name="device">The UPnPDevice</param>
public AVRenderer(UPnPDevice device)
{
OpenSource.Utilities.InstanceTracker.Add(this);
this.ConnectionMonitor.OnExpired += new LifeTimeMonitor.LifeTimeHandler(ConnectionMonitorSink);
MainDevice = device;
ConnectionManager = new CpConnectionManager(device.GetServices(CpConnectionManager.SERVICE_NAME)[0]);
ConnectionManager.OnStateVariable_CurrentConnectionIDs += new CpConnectionManager.StateVariableModifiedHandler_CurrentConnectionIDs(ConnectionIDEventSink);
ConnectionManager._subscribe(90);
//TODO: Fails to compile after using generated code from DeviceBuilderV23. Seems like CpConnectionManager.PeriodicRenewFailedHandler is no longer defined?
//ConnectionManager.OnPeriodicRenewFailed += new CpConnectionManager.PeriodicRenewFailedHandler(PeriodicRenewFailedSink);
// Grab initial state of the ConnectionManager Service
if(ConnectionManager.HasAction_GetProtocolInfo)
{
ConnectionManager.GetProtocolInfo(null,new CpConnectionManager.Delegate_OnResult_GetProtocolInfo(GetProtocolInfoSink));
}
if(ConnectionManager.HasAction_GetCurrentConnectionIDs)
{
ConnectionManager.GetCurrentConnectionIDs(null,new CpConnectionManager.Delegate_OnResult_GetCurrentConnectionIDs(IDSink));
}
if(ConnectionManager.HasAction_PrepareForConnection==false)
{
lock(InstanceList)
{
AVConnection ac = new AVConnection(MainDevice,0,0,0,new AVConnection.OnReadyHandler(ReadySink), null);
ac._Parent = this;
DontEverDelete = true;
if(InstanceList.Count==0) InstanceList.Add(ac);
}
/* Wait for Ready
if(InstanceList.Count>0)
{
if(OnCreateConnection!=null) OnCreateConnection(this,(AVConnection)InstanceList[0],Guid.NewGuid().GetHashCode());
}
*/
}
}
protected void PeriodicRenewFailedSink(CpConnectionManager sender)
{
EventRenewalFailureEvent.Fire(this);
}
public void ReSync()
{
if(ConnectionManager.HasAction_GetCurrentConnectionIDs)
{
ConnectionManager.GetCurrentConnectionIDs(null,new CpConnectionManager.Delegate_OnResult_GetCurrentConnectionIDs(IDSink));
}
}
/// <summary>
/// This method can be triggered 30 seconds after an event was received
/// notifying us what ConnectionIDs are valid. There could be a 30 seconds delay, because
/// if there are pending connection attempts, this event may not contain the complete ID list,
/// so we need to wait for PrepareForConnection to return. Or vice versa. If PrepareForConnection
/// returns with its ID, we need to make sure the event arrived, because otherwise we
/// could receive an event without that connection id, and the CP may think that the ID we just added
/// was deleted, which is bad... Very bad race conditions here :)
/// </summary>
/// <param name="sender"></param>
/// <param name="obj"></param>
private void ConnectionMonitorSink(LifeTimeMonitor sender, object obj)
{
// Lets fetch information about the connection id specicifed in obj
ConnectionManager.GetCurrentConnectionInfo((int)obj,null,new CpConnectionManager.Delegate_OnResult_GetCurrentConnectionInfo(ConnectionInfoSink));
}
/// <summary>
/// This returns a debugging object for the ConnectionManager
/// </summary>
public UPnPServiceWatcher ConnectionManagerWatcher
{
get
{
return(new UPnPServiceWatcher(MainDevice.GetServices(CpConnectionManager.SERVICE_NAME)[0],null));
}
}
/// <summary>
/// This returns a debugging object for the AVTransport
/// </summary>
public UPnPServiceWatcher AVTransportWatcher
{
get
{
return(new UPnPServiceWatcher(MainDevice.GetServices(CpAVTransport.SERVICE_NAME)[0],null));
}
}
/// <summary>
/// This returns a debugging object for the RenderingControl
/// </summary>
public UPnPServiceWatcher RenderingControlWatcher
{
get
{
return(new UPnPServiceWatcher(MainDevice.GetServices(CpRenderingControl.SERVICE_NAME)[0],null));
}
}
/// <summary>
/// This method is triggered whenever a ConnectionManagerEvent arrives, which tells us
/// all of the current ConnectionIDs
/// </summary>
/// <param name="sender">The CpConnectionManager class that sent the event</param>
/// <param name="CurrentIDs">A CSV list of ConnectionIDs</param>
protected void ConnectionIDEventSink(CpConnectionManager sender, string CurrentIDs)
{
// We need to return immediately if this flag is set.
// This flag is only set if PrepareForConnection in not implemented on this
// renderer, in which case, there will be a default ConnectionID of 0, which
// must never disappear.
if(DontEverDelete == true) return;
// This is a temp collection used to create an index of the ConnectionIDs that
// were recieved in this event
Hashtable h = new Hashtable();
// This is a temp parser used to parse the CSV list of IDs
DText p = new DText();
p.ATTRMARK = ",";
if(CurrentIDs!="")
{
p[0] = CurrentIDs;
int len = p.DCOUNT();
for(int i=1;i<=len;++i)
{
// Adding a ConnectionID into the temp collection
h[Int32.Parse(p[i])] = "";
}
}
// Lets find ones that were removed first
foreach(AVConnection a in Connections)
{
if(h.ContainsKey(a.ConnectionID)==false)
{
// This ID was removed
InstanceList.Remove(a);
a.Dispose();
OnRemovedConnectionEvent.Fire(this,a,Guid.NewGuid().GetHashCode());
}
}
// Now lets look for new ones... This is easy
IDSink(sender, CurrentIDs,null,Guid.NewGuid().GetHashCode());
}
/// <summary>
/// This returns the supported Protocols for the Renderer
/// </summary>
public ProtocolInfoString[] ProtocolInfoStrings
{
get
{
return((ProtocolInfoString[])ProtocolInfoList.ToArray(typeof(ProtocolInfoString)));
}
}
/// <summary>
/// This method is called when an AsyncCall to GetProtocolInfo completes
/// </summary>
/// <param name="sender"></param>
/// <param name="Source"></param>
/// <param name="Sink"></param>
/// <param name="e"></param>
/// <param name="Handle"></param>
protected void GetProtocolInfoSink(CpConnectionManager sender, System.String Source, System.String Sink, UPnPInvokeException e, object Handle)
{
if(e!=null) return;
if(Sink=="") return;
// This is a temp parser to parse the supported ProtocolInfo values
DText p = new DText();
p.ATTRMARK = ",";
p[0] = Sink;
int len = p.DCOUNT();
ProtocolInfoString istring;
for(int i=1;i<=len;++i)
{
istring = new ProtocolInfoString(p[i]);
// Add each individual entry
ProtocolInfoList.Add(istring);
}
if(!this.__Init)
{
this.__Init = true;
// Upon discovery of a renderer, we can't return the renderer to the user
// until we at least parsed the supported ProtocolInfo values, otherwise
// the user will experience incorrect behavior. Since we have just parsed
// these values, we can fire this event.
if(this.OnInitialized!=null) OnInitialized(this);
}
}
/// <summary>
/// This is used to determine if the renderer supports a given protocol type.
/// </summary>
/// <param name="ProtocolInfo">The ProtocolInfo you wish to check</param>
/// <returns>true if supported</returns>
public bool SupportsProtocolInfo(ProtocolInfoString ProtocolInfo)
{
bool RetVal = false;
foreach(ProtocolInfoString pis in ProtocolInfoList)
{
if(pis.Matches(ProtocolInfo))
{
RetVal = true;
break;
}
}
return(RetVal);
}
/*
public SortedList SortResourcesByAddress(IMediaResource[] resources)
{
long matchValue;
SortedList retVal = new SortedList();
// Iterate through all resources and sort them according
// to a bitwise-AND comparison of the IP address for the
// resource's URI and the target renderer's IP address.
foreach (IMediaResource res in resources)
{
try
{
Uri uri = new Uri(res.ContentUri);
if (uri.HostNameType == UriHostNameType.IPv4)
{
System.Net.IPAddress ipaddr = System.Net.IPAddress.Parse(uri.Host);
matchValue = this.MainDevice.RemoteEndPoint.Address.Address & ipaddr.Address;
retVal.Add(matchValue, res);
}
}
catch
{
retVal.Add(0, res);
}
}
return retVal;
}
public SortedList SortResourcesByProtocolInfo(IMediaResource resources)
{
long matchValue;
SortedList retVal = new SortedList();
// Iterate through all resources and sort them according
// to a bitwise-AND comparison of the IP address for the
// resource's URI and the target renderer's IP address.
foreach (IMediaResource res in resources)
{
matchValue = this.ProtocolInfoList.Count + 1;
foreach (ProtocolInfoString pis in this.ProtocolInfoList)
{
matchValue--;
if (pis.Matches(res.ProtocolInfo))
{
retVal.Add(matchValue, res);
}
}
}
return retVal;
}
*/
public IMediaResource GetBestMatch(IMediaResource[] resources)
{
long bestIpMatch = 0xFFFFFFFF;
int bestProtInfoMatch = 0;
long reverseThis;
System.Net.IPAddress ipaddr;
IMediaResource bestMatch = null;
foreach (IMediaResource res in resources)
{
long ipMatch = 0;
int piMatch = 0;
piMatch = this.ProtocolInfoList.Count + 1;
foreach(ProtocolInfoString pis in this.ProtocolInfoList)
{
piMatch--;
if(pis.Matches(res.ProtocolInfo)) { break; }
}
if (piMatch > 0)
{
ipMatch = 0;
try
{
Uri uri = new Uri(res.ContentUri);
if (uri.HostNameType == UriHostNameType.IPv4)
{
ipaddr = System.Net.IPAddress.Parse(uri.Host);
reverseThis = (this.MainDevice.RemoteEndPoint.Address.Address ^ ipaddr.Address);
ipMatch =
((reverseThis & 0x000000ff) << 24) |
((reverseThis & 0x0000ff00) << 8) |
((reverseThis & 0x00ff0000) >> 8) |
((reverseThis & 0xff000000) >> 24);
}
}
catch
{
ipMatch = 0xFFFFFFFF;
}
}
if (
(ipMatch < bestIpMatch) ||
((ipMatch == bestIpMatch) && (piMatch > bestProtInfoMatch))
)
{
bestMatch = res;
bestIpMatch = ipMatch;
bestProtInfoMatch = piMatch;
}
}
return bestMatch;
}
/// <summary>
/// This returns the interface on which this Control Point uses to reach the renderer
/// </summary>
public System.Net.IPAddress Interface
{
get
{
return(MainDevice.InterfaceToHost);
}
}
/// <summary>
/// This property lets the user know if this renderer has implemented the
/// PrepareForConnection method in the ConnectionManager service.
/// </summary>
public bool HasConnectionHandling
{
get
{
return(this.ConnectionManager.HasAction_PrepareForConnection);
}
}
/// <summary>
/// The UPnP Friendly name of the Renderer
/// </summary>
public string FriendlyName
{
get
{
return(MainDevice.FriendlyName);
}
}
/// <summary>
/// The UPnP UniqueDeviceName of the renderer
/// </summary>
public string UniqueDeviceName
{
get
{
return(MainDevice.UniqueDeviceName);
}
}
/// <summary>
/// This method is called when an Async call to PrepareForConnection returns. Only
/// the AVPlayList class will ever call that method.
/// </summary>
/// <param name="sender"></param>
/// <param name="RemoteProtocolInfo"></param>
/// <param name="PeerConnectionManager"></param>
/// <param name="PeerConnectionID"></param>
/// <param name="Direction"></param>
/// <param name="ConnectionID"></param>
/// <param name="AVTransportID"></param>
/// <param name="RcsID"></param>
/// <param name="e"></param>
/// <param name="Handle"></param>
protected void PrepareForConnectionSink(CpConnectionManager sender, System.String RemoteProtocolInfo, System.String PeerConnectionManager, System.Int32 PeerConnectionID, CpConnectionManager.Enum_A_ARG_TYPE_Direction Direction, System.Int32 ConnectionID, System.Int32 AVTransportID, System.Int32 RcsID, UPnPInvokeException e, object Handle)
{
AVConnection c = null;
bool IsNew = true;
if(e!=null)
{
// Since only the AVPlayList class will call PrepareForConnection, we need to fire
// this other event, because it's too early to notify the user. Only AVPlayList needs
// to know about this, so it can continue to setup the connection for the user
OnCreateConnectionFailedEvent2.Fire(this,AVRenderer.CreateFailedReason.CREATE_ATTEMPT_DENIED,Handle);
return;
}
lock(InstanceList)
{
foreach(AVConnection a in InstanceList)
{
if(a.ConnectionID==ConnectionID)
{
// We Already Have this ID From somewhere
IsNew = false;
c = a;
break;
}
}
if(IsNew==true)
{
// Does not Exist
c = new AVConnection(MainDevice, AVTransportID, RcsID, ConnectionID,new AVConnection.OnReadyHandler(_ReadySink), Handle);
c._Parent = this;
InstanceList.Add(c);
}
}
if(IsNew==true)
{
// Wait for Ready event from the AVConnection, since we can't return it
// until it is initialized.
}
else
{
// Recycled
OnRecycledConnectionEvent2.Fire(this,c,Handle);
}
}
protected void CreateConnectionEx(object _state)
{
object[] state = (object[])_state;
string ConnectionInfoString = (string)state[0];
string PeerConnectionManagerString = (string)state[1];
int Handle = (int)state[2];
OnRecycledConnectionEvent2.Fire(this,(AVConnection)this.InstanceList[0],Handle);
}
/// <summary>
/// This method is used to call the PrepareForConnection method on the renderer
/// if it is implemented. Only AVPlayList should call this method, which is why
/// this is an internal method.
/// </summary>
/// <param name="ConnectionInfoString"></param>
/// <param name="PeerConnectionManagerString"></param>
/// <param name="PeerConnectionID"></param>
internal void CreateConnection(string ConnectionInfoString, string PeerConnectionManagerString, int PeerConnectionID)
{
CreateConnection(ConnectionInfoString,PeerConnectionManagerString,PeerConnectionID,null);
}
/// <summary>
/// This is invoked to instantiate a new rendering session. Same as other internal CreateConnection
/// method, but this one has an extra user object that can be passed. The other method will
/// actually call this one, and pass null.
/// </summary>
/// <param name="ConnectionInfoString">The ProtocolInfo for the session you wish to begin</param>
/// <param name="PeerConnectionManagerString">Information about the source of the new stream. Forward slash if none.</param>
/// <param name="PeerConnectionID">The ID of the source. -1 if none</param>
/// <returns>Unique Handle</returns>
internal void CreateConnection(string ConnectionInfoString, string PeerConnectionManagerString, int PeerConnectionID, object Tag)
{
// If this renderer implements PrepareForConnection we must do some more
// processing.
if(ConnectionManager.HasAction_PrepareForConnection)
{
ConnectionManager.PrepareForConnection(ConnectionInfoString,
PeerConnectionManagerString,
PeerConnectionID,
CpConnectionManager.Enum_A_ARG_TYPE_Direction.INPUT,
Tag,
new CpConnectionManager.Delegate_OnResult_PrepareForConnection(PrepareForConnectionSink));
return;
}
// If this renderer does not implement PrepareForConnection, then we just notify
// that we are recycling the ConnectionID that we are already using
OnRecycledConnectionEvent2.Fire(this,(AVConnection)this.InstanceList[0],Tag);
}
/// <summary>
/// This method just checks a MediaContainer, and lets the user know
/// if this renderer is capable of renderering it. Note, that compatible
/// in the sense of how the AV spec defines compatible. This does NOT
/// gaurantee that it will actually be able to be renderered on the device.
/// </summary>
/// <param name="Container"></param>
/// <returns></returns>
public bool IsCompatible(IMediaContainer Container)
{
foreach(IMediaItem item in Container.Items)
{
foreach(IMediaResource r in item.MergedResources)
{
if(SupportsProtocolInfo(r.ProtocolInfo)) return(true);
}
}
return(false);
}
/// <summary>
/// Create a new Session on the renderer to play this IMediaContainer
/// </summary>
/// <param name="Container">Container to render</param>
public void CreateConnection(IMediaContainer Container)
{
CreateConnection(Container,null);
}
public void CreateConnection(IMediaContainer Container, object Tag)
{
if (Container.MergedResources.Length > 0)
{
CreateConnection(this.GetBestMatch(Container.MergedResources));
}
else
{
ArrayList RList = new ArrayList();
foreach(IMediaItem item in Container.Items)
{
foreach(IMediaResource r in item.MergedResources)
{
if(SupportsProtocolInfo(r.ProtocolInfo))
{
RList.Add(r);
break;
}
}
}
if(RList.Count==0)
{
OnCreateConnectionFailedEvent.Fire(this,CreateFailedReason.UNSUPPORTED_MEDIA_ITEM,Tag);
return;
}
CreateConnection((IMediaResource[])RList.ToArray(typeof(IMediaResource)),Tag);
}
}
/// <summary>
/// This method just checks a MediaItem, and lets the user know
/// if this renderer is capable of renderering it. Note, that compatible
/// in the sense of how the AV spec defines compatible. This does NOT
/// gaurantee that it will actually be able to be renderered on the device.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool IsCompatible(IMediaItem item)
{
return(IsCompatible(new IMediaItem[1]{item}));
}
/// <summary>
/// Creates a new session on the renderer to play this IMediaItem
/// </summary>
/// <param name="item"></param>
public void CreateConnection(IMediaItem item)
{
CreateConnection(item,null);
}
/// <summary>
/// Creates a new session on the renderer to play this array of IMediaItems.
/// This stack will take care of figuring out how to do it, whether it involves
/// creating a playlist, what type of playlist, or to fake a playlist.
/// </summary>
/// <param name="items">Array of items to play</param>
public void CreateConnection(IMediaItem[] items)
{
CreateConnection(items,null);
}
public void CreateConnection(IMediaItem item, object Tag)
{
CreateConnection(new IMediaItem[1]{item},Tag);
}
public void CreateConnection(IMediaItem[] items, object Tag)
{
ArrayList RList = new ArrayList();
foreach(IMediaItem item in items)
{
IMediaResource res = GetBestMatch(item.MergedResources);
if (res != null) RList.Add(res);
// foreach(IMediaResource resource in item.MergedResources)
// {
// if(this.SupportsProtocolInfo(resource.ProtocolInfo))
// {
// // Use this resource
// RList.Add(resource);
// break;
// }
// }
}
if(RList.Count==0)
{
OnCreateConnectionFailedEvent.Fire(this,CreateFailedReason.UNSUPPORTED_MEDIA_ITEM,Tag);
return;
}
CreateConnection((IMediaResource[])RList.ToArray(typeof(IMediaResource)),Tag);
}
/// <summary>
/// This lets the user verify that at least on of the items specified can be
/// rendered on the device. NOTE that this is according to the AV spec and its use
/// of the ProtocolInfo value field. This does NOT gaurantee that this can actually
/// be played on the renderer.
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
public bool IsCompatible(IMediaItem[] items)
{
foreach(IMediaItem item in items)
{
foreach(IMediaResource r in item.MergedResources)
{
if(SupportsProtocolInfo(r.ProtocolInfo)) return(true);
}
}
return(false);
}
/// <summary>
/// This lets the user verify that at least on of the resources specified can be
/// rendered on the device. NOTE that this is according to the AV spec and its use
/// of the ProtocolInfo value field. This does NOT gaurantee that this can actually
/// be played on the renderer.
/// </summary>
/// <param name="resources"></param>
/// <returns></returns>
public bool IsCompatible(IMediaResource[] resources)
{
foreach(IMediaResource r in resources)
{
if(SupportsProtocolInfo(r.ProtocolInfo)) return(true);
}
return(false);
}
/// <summary>
/// Creates a new session on the renderer to play this array of resources.
/// This stack will take care of figuring out how to do it, whether it involves
/// creating a playlist, what type of playlist, or to fake a playlist.
/// </summary>
/// <param name="resources"></param>
public void CreateConnection(IMediaResource[] resources)
{
CreateConnection(resources,null);
}
/// <summary>
/// This is invoked when you wish to instantiate a new rendering session.
/// </summary>
/// <param name="resources">the IMediaResource(s) you wish to render</param>
/// <returns>Unique Handle</returns>
public void CreateConnection(IMediaResource[] resources, object Tag)
{
lock(this.CreateConnectionLock)
{
++this.PendingCreateConnection;
}
AVPlayList pl = new AVPlayList(this,resources,new AVPlayList.ReadyHandler(PlayListSink), new AVPlayList.FailedHandler(PlayListFailedSink),Tag);
PlayListTable[pl.GetHashCode()] = pl;
}
protected void PlayListFailedSink(AVPlayList sender, AVRenderer.CreateFailedReason reason)
{
PlayListTable.Remove(sender.GetHashCode());
OnCreateConnectionFailedEvent.Fire(this,reason,sender.PlayListHandle);
}
protected void PlayListSink(AVPlayList sender, AVConnection c, object Tag)
{
PlayListTable.Remove(sender.GetHashCode());
lock(this.CreateConnectionLock)
{
--this.PendingCreateConnection;
if(this.PendingCreateConnection<0) PendingCreateConnection = 0;
ConnectionMonitor.Remove(c.ConnectionID);
}
if(sender.IsRecycled)
{
OnRecycledConnectionEvent.Fire(this,c,Tag);
}
else
{
OnCreateConnectionEvent.Fire(this,c,Tag);
}
}
public void CreateConnection(IMediaResource media)
{
CreateConnection(media,null);
}
public void CreateConnection(IMediaResource media, object Tag)
{
CreateConnection(new IMediaResource[1]{media}, Tag);
}
/// <summary>
/// This returns an IList of the current AVConnections
/// </summary>
public IList Connections
{
get
{
return((IList)InstanceList.Clone());
}
}
/// <summary>
/// This is called by the discovery object when the render device disappeared
/// off the network.
/// </summary>
internal void Removed()
{
foreach(AVConnection c in this.Connections)
{
c.Dispose();
}
this.ConnectionManager.Dispose();
}
/// <summary>
/// This method is called whenever we need to inspect a list of ConnectionIDs
/// to see if any of them are new
/// </summary>
/// <param name="sender"></param>
/// <param name="IDString"></param>
/// <param name="e"></param>
/// <param name="Handle"></param>
protected void IDSink(CpConnectionManager sender, string IDString, UPnPInvokeException e, object Handle)
{
if((e!=null) || (IDString=="")) return;
// This is a temp parser that will parse the CSV list of IDs
DText p = new DText();
p.ATTRMARK = ",";
p[0] = IDString;
int len = p.DCOUNT();
for(int i=1;i<=len;++i)
{
// bool FOUND = false;
int cid = int.Parse(p[i].Trim());
// lock(InstanceList)
// {
// foreach(AVConnection _AVC in InstanceList)
// {
// if(_AVC.ConnectionID == cid)
// {
// FOUND = true;
// break;
// }
// }
// }
lock(this.CreateConnectionLock)
{
if(this.PendingCreateConnection==0)
{
ConnectionManager.GetCurrentConnectionInfo(cid,null,new CpConnectionManager.Delegate_OnResult_GetCurrentConnectionInfo(ConnectionInfoSink));
}
else
{
// We possible need to wait a maximum of 30 seconds, just in case events arrive
// that involve this connection ID. When/if that happens, we will remove this
// object from the monitor, and continue directly.
this.ConnectionMonitor.Add(cid,30);
}
}
}
}
private void ReadySink(AVConnection sender, object Tag)
{
OnCreateConnectionEvent.Fire(this,sender,Tag);
}
private void _ReadySink(AVConnection sender, object Tag)
{
OnCreateConnectionEvent2.Fire(this,sender,Tag);
}
/// <summary>
/// This method is called on a regular interval from a single thread. This is
/// giving the renderer a thread to poll the device for position information.
/// The AVConnection object will only poll if it is in the PLAY state, otherwise
/// it will just return immediately.
/// </summary>
internal void _Poll()
{
foreach(AVConnection C in Connections)
{
C._Poll();
}
}
protected void ConnectionInfoSink(CpConnectionManager sender, System.Int32 ConnectionID, System.Int32 RcsID, System.Int32 AVTransportID, System.String ProtocolInfo, System.String PeerConnectionManager, System.Int32 PeerConnectionID, CpConnectionManager.Enum_A_ARG_TYPE_Direction Direction, CpConnectionManager.Enum_A_ARG_TYPE_ConnectionStatus Status, UPnPInvokeException e, object Handle)
{
if(e!=null) return;
AVConnection av=null;
lock(InstanceList)
{
foreach(AVConnection a in InstanceList)
{
if(a.ConnectionID==ConnectionID)
{
av = a;
break;
}
}
if(av==null)
{
av = new AVConnection(MainDevice, AVTransportID, RcsID, ConnectionID,new AVConnection.OnReadyHandler(ReadySink), Handle);
av._Parent = this;
InstanceList.Add(av);
}
else
{
return; // Don't need to trigger event
}
}
// Wait for Ready before sending OnCreateConnection
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// MonoTests.System.ComponentModel.ReferenceConverterTest
//
// Author:
// Ivan N. Zlatev <contact@i-nz.net>
//
// Copyright (C) 2008 Ivan N. Zlatev
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.ComponentModel.Tests
{
public class ReferenceConverterTest
{
class TestReferenceService : IReferenceService
{
private Dictionary<string, object> references;
public TestReferenceService()
{
references = new Dictionary<string, object>();
}
public void AddReference(string name, object reference)
{
references[name] = reference;
}
public void ClearReferences()
{
references.Clear();
}
public IComponent GetComponent(object reference)
{
return null;
}
public string GetName(object reference)
{
foreach (KeyValuePair<string, object> entry in references)
{
if (entry.Value == reference)
return entry.Key;
}
return null;
}
public object GetReference(string name)
{
if (!references.ContainsKey(name))
return null;
return references[name];
}
public object[] GetReferences()
{
object[] array = new object[references.Values.Count];
references.Values.CopyTo(array, 0);
return array;
}
public object[] GetReferences(Type baseType)
{
object[] references = GetReferences();
List<object> filtered = new List<object>();
foreach (object reference in references)
{
if (baseType.IsInstanceOfType(reference))
filtered.Add(reference);
}
return filtered.ToArray();
}
}
private class TestTypeDescriptorContext : ITypeDescriptorContext
{
private IReferenceService reference_service = null;
private IContainer container = null;
public TestTypeDescriptorContext()
{
}
public TestTypeDescriptorContext(IReferenceService referenceService)
{
reference_service = referenceService;
}
public IContainer Container
{
get { return container; }
set { container = value; }
}
public object Instance
{
get { return null; }
}
public PropertyDescriptor PropertyDescriptor
{
get { return null; }
}
public void OnComponentChanged()
{
}
public bool OnComponentChanging()
{
return true;
}
public object GetService(Type serviceType)
{
if (serviceType == typeof(IReferenceService))
return reference_service;
return null;
}
}
private interface ITestInterface
{
}
private class TestComponent : Component
{
}
[Fact]
public void CanConvertFrom()
{
ReferenceConverter converter = new ReferenceConverter(typeof(ITestInterface));
// without context
Assert.False(converter.CanConvertFrom(null, typeof(string)));
// with context
Assert.True(converter.CanConvertFrom(new TestTypeDescriptorContext(), typeof(string)));
}
[Fact]
public void ConvertFrom()
{
ReferenceConverter converter = new ReferenceConverter(typeof(ITestInterface));
string referenceName = "reference name";
// no context
Assert.Null(converter.ConvertFrom(null, null, referenceName));
TestComponent component = new TestComponent();
// context with IReferenceService
TestReferenceService referenceService = new TestReferenceService();
referenceService.AddReference(referenceName, component);
TestTypeDescriptorContext context = new TestTypeDescriptorContext(referenceService);
Assert.Same(component, converter.ConvertFrom(context, null, referenceName));
// context with Component without IReferenceService
Container container = new Container();
container.Add(component, referenceName);
context = new TestTypeDescriptorContext();
context.Container = container;
Assert.Same(component, converter.ConvertFrom(context, null, referenceName));
}
[Fact]
public void ConvertTo()
{
RemoteExecutor.Invoke(() =>
{
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
ReferenceConverter remoteConverter = new ReferenceConverter(typeof(ITestInterface));
Assert.Equal("(none)", (string)remoteConverter.ConvertTo(null, null, null, typeof(string)));
}).Dispose();
ReferenceConverter converter = new ReferenceConverter(typeof(ITestInterface));
string referenceName = "reference name";
TestComponent component = new TestComponent();
// no context
Assert.Equal(string.Empty, (string)converter.ConvertTo(null, null, component, typeof(string)));
// context with IReferenceService
TestReferenceService referenceService = new TestReferenceService();
referenceService.AddReference(referenceName, component);
TestTypeDescriptorContext context = new TestTypeDescriptorContext(referenceService);
Assert.Equal(referenceName, (string)converter.ConvertTo(context, null, component, typeof(string)));
// context with Component without IReferenceService
Container container = new Container();
container.Add(component, referenceName);
context = new TestTypeDescriptorContext();
context.Container = container;
Assert.Equal(referenceName, (string)converter.ConvertTo(context, null, component, typeof(string)));
}
[Fact]
public void CanConvertTo()
{
ReferenceConverter converter = new ReferenceConverter(typeof(ITestInterface));
Assert.True(converter.CanConvertTo(new TestTypeDescriptorContext(), typeof(string)));
}
[Fact]
public void GetStandardValues()
{
ReferenceConverter converter = new ReferenceConverter(typeof(TestComponent));
TestComponent component1 = new TestComponent();
TestComponent component2 = new TestComponent();
TestReferenceService referenceService = new TestReferenceService();
referenceService.AddReference("reference name 1", component1);
referenceService.AddReference("reference name 2", component2);
ITypeDescriptorContext context = new TestTypeDescriptorContext(referenceService);
TypeConverter.StandardValuesCollection values = converter.GetStandardValues(context);
Assert.NotNull(values);
// 2 components + 1 null value
Assert.Equal(3, values.Count);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using MartinKRC2.Data;
using MartinKRC2.Models;
using MartinKRC2.ViewModels.ResourcesViewModels;
using Microsoft.AspNetCore.Http;
namespace MartinKRC2.Controllers
{
public class ResourcesController : Controller
{
private readonly ApplicationDbContext _context;
public ResourcesController(ApplicationDbContext context)
{
_context = context;
}
// GET: Resources
public async Task<IActionResult> Index()
{
return View(await _context.Resource.ToListAsync());
}
// GET: Resources/Create
public async Task<IActionResult> Create()
{
var resourceGroups = new List<SelectListItem>();
foreach (var item in await _context.ResourceGroup.ToListAsync())
{
resourceGroups.Add(new SelectListItem() { Text = item.Title, Value = item.Id.ToString() });
}
var talks = new List<SelectListItem>();
foreach (var item in await _context.Talk.ToListAsync())
{
talks.Add(new SelectListItem() { Text = item.Title, Value = item.Id.ToString() });
}
var vm = new CreateViewModel() {
Resource = new Resource(),
ResourceGroups = resourceGroups,
Talks = talks
};
return View(vm);
}
// POST: Resources/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Resource resource)
{
if (ModelState.IsValid)
{
_context.Add(resource);
await _context.SaveChangesAsync();
//update Resource Groups
await CreateUpdateResourceGroupMappings(resource.Id, Request.Form["ResourceGroupIds"].ToList());
//update Talks
await CreateUpdateTalkMappings(resource.Id, Request.Form["TalkIds"].ToList());
return RedirectToAction("Index");
}
return View(resource);
}
// GET: Resources/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var resource = await _context.Resource.Include(o => o.ResourceResourceGroups).SingleOrDefaultAsync(m => m.Id == id);
if (resource == null)
{
return NotFound();
}
//get Resource <> Resource Group mappings for this Resource
var selectedResourceGroups = await _context.ResourceResourceGroup.Where(o => o.ResourceId == id).ToListAsync();
var resourceGroups = new List<SelectListItem>();
foreach (var item in await _context.ResourceGroup.ToListAsync())
{
//figure out if this Resource Group is selected for this Resource
var isSelected = (selectedResourceGroups.Where(o => o.ResourceGroupId == item.Id).Count() > 0);
//construct and add Select List Item
var selectListItem = new SelectListItem()
{
Text = item.Title,
Value = item.Id.ToString(),
Selected = isSelected
};
resourceGroups.Add(selectListItem);
}
//get Resource <> Talk mappings for this Resource
var selectedTalks = await _context.ResourceTalk.Where(o => o.ResourceId == id).ToListAsync();
var talks = new List<SelectListItem>();
foreach (var item in await _context.Talk.ToListAsync())
{
//figure out if this Talk is selected for this Resource
var isSelected = (selectedTalks.Where(o => o.TalkId == item.Id).Count() > 0);
//construct and add Select List Item
var selectListItem = new SelectListItem()
{
Text = item.Title,
Value = item.Id.ToString(),
Selected = isSelected
};
talks.Add(selectListItem);
}
var vm = new EditViewModel()
{
Resource = resource,
ResourceGroups = resourceGroups,
Talks = talks
};
return View(vm);
}
// POST: Resources/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, Resource resource)
{
if (id != resource.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
//update Resource
_context.Update(resource);
await _context.SaveChangesAsync();
//update Resource Groups
await CreateUpdateResourceGroupMappings(id, Request.Form["ResourceGroupIds"].ToList());
//update Talks
await CreateUpdateTalkMappings(id, Request.Form["TalkIds"].ToList());
}
catch (DbUpdateConcurrencyException)
{
if (!ResourceExists(resource.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(resource);
}
// GET: Resources/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var resource = await _context.Resource.SingleOrDefaultAsync(m => m.Id == id);
if (resource == null)
{
return NotFound();
}
return View(resource);
}
// POST: Resources/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
//delete Resource <> Resource Group mappings
await DeleteResourceGroupMappings(id);
//delete Resource <> Talk mappings
await DeleteTalkMappings(id);
//delete Resource
var resource = await _context.Resource.SingleOrDefaultAsync(m => m.Id == id);
_context.Resource.Remove(resource);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool ResourceExists(int id)
{
return _context.Resource.Any(e => e.Id == id);
}
private async Task<bool> CreateUpdateResourceGroupMappings(int resourceId, List<string> resourceGroupIds)
{
try
{
await DeleteResourceGroupMappings(resourceId);
//add Resource <> ResourceGroup mappings based on submitted form
foreach (var resourceGroupId in resourceGroupIds)
{
_context.ResourceResourceGroup.Add(new ResourceResourceGroup()
{
ResourceId = resourceId,
ResourceGroupId = Convert.ToInt32(resourceGroupId)
});
}
await _context.SaveChangesAsync();
return true;
}
catch
{
return false;
}
}
private async Task<bool> DeleteResourceGroupMappings(int resourceId)
{
try
{
_context.ResourceResourceGroup.RemoveRange(_context.ResourceResourceGroup.Where(o => o.ResourceId == resourceId));
await _context.SaveChangesAsync();
return true;
}
catch
{
return false;
}
}
private async Task<bool> CreateUpdateTalkMappings(int resourceId, List<string> talkIds)
{
try
{
await DeleteTalkMappings(resourceId);
//add Resource <> Talk mappings based on submitted form
foreach (var talkId in talkIds)
{
_context.ResourceTalk.Add(new ResourceTalk()
{
ResourceId = resourceId,
TalkId = Convert.ToInt32(talkId)
});
}
await _context.SaveChangesAsync();
return true;
}
catch
{
return false;
}
}
private async Task<bool> DeleteTalkMappings(int resourceId)
{
try
{
_context.ResourceTalk.RemoveRange(_context.ResourceTalk.Where(o => o.ResourceId == resourceId));
await _context.SaveChangesAsync();
return true;
}
catch
{
return false;
}
}
}
}
| |
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
using System.Text;
using Com.Adobe.Xmp;
using Com.Adobe.Xmp.Impl.Xpath;
using Com.Adobe.Xmp.Options;
using Com.Adobe.Xmp.Properties;
using Sharpen;
namespace Com.Adobe.Xmp.Impl
{
/// <since>11.08.2006</since>
public class XMPUtilsImpl : XMPConst
{
private const int UckNormal = 0;
private const int UckSpace = 1;
private const int UckComma = 2;
private const int UckSemicolon = 3;
private const int UckQuote = 4;
private const int UckControl = 5;
/// <summary>Private constructor, as</summary>
private XMPUtilsImpl()
{
}
// EMPTY
/// <seealso cref="Com.Adobe.Xmp.XMPUtils.CatenateArrayItems(Com.Adobe.Xmp.XMPMeta, string, string, string, string, bool)"/>
/// <param name="xmp">The XMP object containing the array to be catenated.</param>
/// <param name="schemaNS">
/// The schema namespace URI for the array. Must not be null or
/// the empty string.
/// </param>
/// <param name="arrayName">
/// The name of the array. May be a general path expression, must
/// not be null or the empty string. Each item in the array must
/// be a simple string value.
/// </param>
/// <param name="separator">
/// The string to be used to separate the items in the catenated
/// string. Defaults to "; ", ASCII semicolon and space
/// (U+003B, U+0020).
/// </param>
/// <param name="quotes">
/// The characters to be used as quotes around array items that
/// contain a separator. Defaults to '"'
/// </param>
/// <param name="allowCommas">Option flag to control the catenation.</param>
/// <returns>Returns the string containing the catenated array items.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">Forwards the Exceptions from the metadata processing</exception>
public static string CatenateArrayItems(XMPMeta xmp, string schemaNS, string arrayName, string separator, string quotes, bool allowCommas)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(arrayName);
ParameterAsserts.AssertImplementation(xmp);
if (separator == null || separator.Length == 0)
{
separator = "; ";
}
if (quotes == null || quotes.Length == 0)
{
quotes = "\"";
}
XMPMetaImpl xmpImpl = (XMPMetaImpl)xmp;
XMPNode arrayNode = null;
XMPNode currItem = null;
// Return an empty result if the array does not exist,
// hurl if it isn't the right form.
XMPPath arrayPath = XMPPathParser.ExpandXPath(schemaNS, arrayName);
arrayNode = XMPNodeUtils.FindNode(xmpImpl.GetRoot(), arrayPath, false, null);
if (arrayNode == null)
{
return string.Empty;
}
else
{
if (!arrayNode.GetOptions().IsArray() || arrayNode.GetOptions().IsArrayAlternate())
{
throw new XMPException("Named property must be non-alternate array", XMPErrorConstants.Badparam);
}
}
// Make sure the separator is OK.
CheckSeparator(separator);
// Make sure the open and close quotes are a legitimate pair.
char openQuote = quotes[0];
char closeQuote = CheckQuotes(quotes, openQuote);
// Build the result, quoting the array items, adding separators.
// Hurl if any item isn't simple.
StringBuilder catinatedString = new StringBuilder();
for (Iterator it = arrayNode.IterateChildren(); it.HasNext(); )
{
currItem = (XMPNode)it.Next();
if (currItem.GetOptions().IsCompositeProperty())
{
throw new XMPException("Array items must be simple", XMPErrorConstants.Badparam);
}
string str = ApplyQuotes(currItem.GetValue(), openQuote, closeQuote, allowCommas);
catinatedString.Append(str);
if (it.HasNext())
{
catinatedString.Append(separator);
}
}
return catinatedString.ToString();
}
/// <summary>
/// see
/// <see cref="Com.Adobe.Xmp.XMPUtils.SeparateArrayItems(Com.Adobe.Xmp.XMPMeta, string, string, string, Com.Adobe.Xmp.Options.PropertyOptions, bool)"/>
/// </summary>
/// <param name="xmp">The XMP object containing the array to be updated.</param>
/// <param name="schemaNS">
/// The schema namespace URI for the array. Must not be null or
/// the empty string.
/// </param>
/// <param name="arrayName">
/// The name of the array. May be a general path expression, must
/// not be null or the empty string. Each item in the array must
/// be a simple string value.
/// </param>
/// <param name="catedStr">The string to be separated into the array items.</param>
/// <param name="arrayOptions">Option flags to control the separation.</param>
/// <param name="preserveCommas">Flag if commas shall be preserved</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">Forwards the Exceptions from the metadata processing</exception>
public static void SeparateArrayItems(XMPMeta xmp, string schemaNS, string arrayName, string catedStr, PropertyOptions arrayOptions, bool preserveCommas)
{
ParameterAsserts.AssertSchemaNS(schemaNS);
ParameterAsserts.AssertArrayName(arrayName);
if (catedStr == null)
{
throw new XMPException("Parameter must not be null", XMPErrorConstants.Badparam);
}
ParameterAsserts.AssertImplementation(xmp);
XMPMetaImpl xmpImpl = (XMPMetaImpl)xmp;
// Keep a zero value, has special meaning below.
XMPNode arrayNode = SeparateFindCreateArray(schemaNS, arrayName, arrayOptions, xmpImpl);
// Extract the item values one at a time, until the whole input string is done.
string itemValue;
int itemStart;
int itemEnd;
int nextKind = UckNormal;
int charKind = UckNormal;
char ch = (char)0;
char nextChar = (char)0;
itemEnd = 0;
int endPos = catedStr.Length;
while (itemEnd < endPos)
{
// Skip any leading spaces and separation characters. Always skip commas here.
// They can be kept when within a value, but not when alone between values.
for (itemStart = itemEnd; itemStart < endPos; itemStart++)
{
ch = catedStr[itemStart];
charKind = ClassifyCharacter(ch);
if (charKind == UckNormal || charKind == UckQuote)
{
break;
}
}
if (itemStart >= endPos)
{
break;
}
if (charKind != UckQuote)
{
// This is not a quoted value. Scan for the end, create an array
// item from the substring.
for (itemEnd = itemStart; itemEnd < endPos; itemEnd++)
{
ch = catedStr[itemEnd];
charKind = ClassifyCharacter(ch);
if (charKind == UckNormal || charKind == UckQuote || (charKind == UckComma && preserveCommas))
{
continue;
}
else
{
if (charKind != UckSpace)
{
break;
}
else
{
if ((itemEnd + 1) < endPos)
{
ch = catedStr[itemEnd + 1];
nextKind = ClassifyCharacter(ch);
if (nextKind == UckNormal || nextKind == UckQuote || (nextKind == UckComma && preserveCommas))
{
continue;
}
}
}
}
// Anything left?
break;
}
// Have multiple spaces, or a space followed by a
// separator.
itemValue = Sharpen.Runtime.Substring(catedStr, itemStart, itemEnd);
}
else
{
// Accumulate quoted values into a local string, undoubling
// internal quotes that
// match the surrounding quotes. Do not undouble "unmatching"
// quotes.
char openQuote = ch;
char closeQuote = GetClosingQuote(openQuote);
itemStart++;
// Skip the opening quote;
itemValue = string.Empty;
for (itemEnd = itemStart; itemEnd < endPos; itemEnd++)
{
ch = catedStr[itemEnd];
charKind = ClassifyCharacter(ch);
if (charKind != UckQuote || !IsSurroundingQuote(ch, openQuote, closeQuote))
{
// This is not a matching quote, just append it to the
// item value.
itemValue += ch;
}
else
{
// This is a "matching" quote. Is it doubled, or the
// final closing quote?
// Tolerate various edge cases like undoubled opening
// (non-closing) quotes,
// or end of input.
if ((itemEnd + 1) < endPos)
{
nextChar = catedStr[itemEnd + 1];
nextKind = ClassifyCharacter(nextChar);
}
else
{
nextKind = UckSemicolon;
nextChar = (char)0x3B;
}
if (ch == nextChar)
{
// This is doubled, copy it and skip the double.
itemValue += ch;
// Loop will add in charSize.
itemEnd++;
}
else
{
if (!IsClosingingQuote(ch, openQuote, closeQuote))
{
// This is an undoubled, non-closing quote, copy it.
itemValue += ch;
}
else
{
// This is an undoubled closing quote, skip it and
// exit the loop.
itemEnd++;
break;
}
}
}
}
}
// Add the separated item to the array.
// Keep a matching old value in case it had separators.
int foundIndex = -1;
for (int oldChild = 1; oldChild <= arrayNode.GetChildrenLength(); oldChild++)
{
if (itemValue.Equals(arrayNode.GetChild(oldChild).GetValue()))
{
foundIndex = oldChild;
break;
}
}
XMPNode newItem = null;
if (foundIndex < 0)
{
newItem = new XMPNode(XMPConstConstants.ArrayItemName, itemValue, null);
arrayNode.AddChild(newItem);
}
}
}
/// <summary>Utility to find or create the array used by <code>separateArrayItems()</code>.</summary>
/// <param name="schemaNS">a the namespace fo the array</param>
/// <param name="arrayName">the name of the array</param>
/// <param name="arrayOptions">the options for the array if newly created</param>
/// <param name="xmp">the xmp object</param>
/// <returns>Returns the array node.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">Forwards exceptions</exception>
private static XMPNode SeparateFindCreateArray(string schemaNS, string arrayName, PropertyOptions arrayOptions, XMPMetaImpl xmp)
{
arrayOptions = XMPNodeUtils.VerifySetOptions(arrayOptions, null);
if (!arrayOptions.IsOnlyArrayOptions())
{
throw new XMPException("Options can only provide array form", XMPErrorConstants.Badoptions);
}
// Find the array node, make sure it is OK. Move the current children
// aside, to be readded later if kept.
XMPPath arrayPath = XMPPathParser.ExpandXPath(schemaNS, arrayName);
XMPNode arrayNode = XMPNodeUtils.FindNode(xmp.GetRoot(), arrayPath, false, null);
if (arrayNode != null)
{
// The array exists, make sure the form is compatible. Zero
// arrayForm means take what exists.
PropertyOptions arrayForm = arrayNode.GetOptions();
if (!arrayForm.IsArray() || arrayForm.IsArrayAlternate())
{
throw new XMPException("Named property must be non-alternate array", XMPErrorConstants.Badxpath);
}
if (arrayOptions.EqualArrayTypes(arrayForm))
{
throw new XMPException("Mismatch of specified and existing array form", XMPErrorConstants.Badxpath);
}
}
else
{
// *** Right error?
// The array does not exist, try to create it.
// don't modify the options handed into the method
arrayNode = XMPNodeUtils.FindNode(xmp.GetRoot(), arrayPath, true, arrayOptions.SetArray(true));
if (arrayNode == null)
{
throw new XMPException("Failed to create named array", XMPErrorConstants.Badxpath);
}
}
return arrayNode;
}
/// <seealso cref="Com.Adobe.Xmp.XMPUtils.RemoveProperties(Com.Adobe.Xmp.XMPMeta, string, string, bool, bool)"/>
/// <param name="xmp">The XMP object containing the properties to be removed.</param>
/// <param name="schemaNS">
/// Optional schema namespace URI for the properties to be
/// removed.
/// </param>
/// <param name="propName">Optional path expression for the property to be removed.</param>
/// <param name="doAllProperties">
/// Option flag to control the deletion: do internal properties in
/// addition to external properties.
/// </param>
/// <param name="includeAliases">
/// Option flag to control the deletion: Include aliases in the
/// "named schema" case above.
/// </param>
/// <exception cref="Com.Adobe.Xmp.XMPException">If metadata processing fails</exception>
public static void RemoveProperties(XMPMeta xmp, string schemaNS, string propName, bool doAllProperties, bool includeAliases)
{
ParameterAsserts.AssertImplementation(xmp);
XMPMetaImpl xmpImpl = (XMPMetaImpl)xmp;
if (propName != null && propName.Length > 0)
{
// Remove just the one indicated property. This might be an alias,
// the named schema might not actually exist. So don't lookup the
// schema node.
if (schemaNS == null || schemaNS.Length == 0)
{
throw new XMPException("Property name requires schema namespace", XMPErrorConstants.Badparam);
}
XMPPath expPath = XMPPathParser.ExpandXPath(schemaNS, propName);
XMPNode propNode = XMPNodeUtils.FindNode(xmpImpl.GetRoot(), expPath, false, null);
if (propNode != null)
{
if (doAllProperties || !Utils.IsInternalProperty(expPath.GetSegment(XMPPath.StepSchema).GetName(), expPath.GetSegment(XMPPath.StepRootProp).GetName()))
{
XMPNode parent = propNode.GetParent();
parent.RemoveChild(propNode);
if (parent.GetOptions().IsSchemaNode() && !parent.HasChildren())
{
// remove empty schema node
parent.GetParent().RemoveChild(parent);
}
}
}
}
else
{
if (schemaNS != null && schemaNS.Length > 0)
{
// Remove all properties from the named schema. Optionally include
// aliases, in which case
// there might not be an actual schema node.
// XMP_NodePtrPos schemaPos;
XMPNode schemaNode = XMPNodeUtils.FindSchemaNode(xmpImpl.GetRoot(), schemaNS, false);
if (schemaNode != null)
{
if (RemoveSchemaChildren(schemaNode, doAllProperties))
{
xmpImpl.GetRoot().RemoveChild(schemaNode);
}
}
if (includeAliases)
{
// We're removing the aliases also. Look them up by their
// namespace prefix.
// But that takes more code and the extra speed isn't worth it.
// Lookup the XMP node
// from the alias, to make sure the actual exists.
XMPAliasInfo[] aliases = XMPMetaFactory.GetSchemaRegistry().FindAliases(schemaNS);
for (int i = 0; i < aliases.Length; i++)
{
XMPAliasInfo info = aliases[i];
XMPPath path = XMPPathParser.ExpandXPath(info.GetNamespace(), info.GetPropName());
XMPNode actualProp = XMPNodeUtils.FindNode(xmpImpl.GetRoot(), path, false, null);
if (actualProp != null)
{
XMPNode parent = actualProp.GetParent();
parent.RemoveChild(actualProp);
}
}
}
}
else
{
// Remove all appropriate properties from all schema. In this case
// we don't have to be
// concerned with aliases, they are handled implicitly from the
// actual properties.
for (Iterator it = xmpImpl.GetRoot().IterateChildren(); it.HasNext(); )
{
XMPNode schema = (XMPNode)it.Next();
if (RemoveSchemaChildren(schema, doAllProperties))
{
it.Remove();
}
}
}
}
}
/// <seealso cref="Com.Adobe.Xmp.XMPUtils.AppendProperties(Com.Adobe.Xmp.XMPMeta, Com.Adobe.Xmp.XMPMeta, bool, bool)"/>
/// <param name="source">The source XMP object.</param>
/// <param name="destination">The destination XMP object.</param>
/// <param name="doAllProperties">Do internal properties in addition to external properties.</param>
/// <param name="replaceOldValues">Replace the values of existing properties.</param>
/// <param name="deleteEmptyValues">Delete destination values if source property is empty.</param>
/// <exception cref="Com.Adobe.Xmp.XMPException">Forwards the Exceptions from the metadata processing</exception>
public static void AppendProperties(XMPMeta source, XMPMeta destination, bool doAllProperties, bool replaceOldValues, bool deleteEmptyValues)
{
ParameterAsserts.AssertImplementation(source);
ParameterAsserts.AssertImplementation(destination);
XMPMetaImpl src = (XMPMetaImpl)source;
XMPMetaImpl dest = (XMPMetaImpl)destination;
for (Iterator it = src.GetRoot().IterateChildren(); it.HasNext(); )
{
XMPNode sourceSchema = (XMPNode)it.Next();
// Make sure we have a destination schema node
XMPNode destSchema = XMPNodeUtils.FindSchemaNode(dest.GetRoot(), sourceSchema.GetName(), false);
bool createdSchema = false;
if (destSchema == null)
{
destSchema = new XMPNode(sourceSchema.GetName(), sourceSchema.GetValue(), new PropertyOptions().SetSchemaNode(true));
dest.GetRoot().AddChild(destSchema);
createdSchema = true;
}
// Process the source schema's children.
for (Iterator ic = sourceSchema.IterateChildren(); ic.HasNext(); )
{
XMPNode sourceProp = (XMPNode)ic.Next();
if (doAllProperties || !Utils.IsInternalProperty(sourceSchema.GetName(), sourceProp.GetName()))
{
AppendSubtree(dest, sourceProp, destSchema, replaceOldValues, deleteEmptyValues);
}
}
if (!destSchema.HasChildren() && (createdSchema || deleteEmptyValues))
{
// Don't create an empty schema / remove empty schema.
dest.GetRoot().RemoveChild(destSchema);
}
}
}
/// <summary>
/// Remove all schema children according to the flag
/// <code>doAllProperties</code>.
/// </summary>
/// <remarks>
/// Remove all schema children according to the flag
/// <code>doAllProperties</code>. Empty schemas are automatically remove
/// by <code>XMPNode</code>
/// </remarks>
/// <param name="schemaNode">a schema node</param>
/// <param name="doAllProperties">flag if all properties or only externals shall be removed.</param>
/// <returns>Returns true if the schema is empty after the operation.</returns>
private static bool RemoveSchemaChildren(XMPNode schemaNode, bool doAllProperties)
{
for (Iterator it = schemaNode.IterateChildren(); it.HasNext(); )
{
XMPNode currProp = (XMPNode)it.Next();
if (doAllProperties || !Utils.IsInternalProperty(schemaNode.GetName(), currProp.GetName()))
{
it.Remove();
}
}
return !schemaNode.HasChildren();
}
/// <seealso cref="AppendProperties(Com.Adobe.Xmp.XMPMeta, Com.Adobe.Xmp.XMPMeta, bool, bool, bool)"/>
/// <param name="destXMP">The destination XMP object.</param>
/// <param name="sourceNode">the source node</param>
/// <param name="destParent">the parent of the destination node</param>
/// <param name="replaceOldValues">Replace the values of existing properties.</param>
/// <param name="deleteEmptyValues">
/// flag if properties with empty values should be deleted
/// in the destination object.
/// </param>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
private static void AppendSubtree(XMPMetaImpl destXMP, XMPNode sourceNode, XMPNode destParent, bool replaceOldValues, bool deleteEmptyValues)
{
XMPNode destNode = XMPNodeUtils.FindChildNode(destParent, sourceNode.GetName(), false);
bool valueIsEmpty = false;
if (deleteEmptyValues)
{
valueIsEmpty = sourceNode.GetOptions().IsSimple() ? sourceNode.GetValue() == null || sourceNode.GetValue().Length == 0 : !sourceNode.HasChildren();
}
if (deleteEmptyValues && valueIsEmpty)
{
if (destNode != null)
{
destParent.RemoveChild(destNode);
}
}
else
{
if (destNode == null)
{
// The one easy case, the destination does not exist.
destParent.AddChild((XMPNode)sourceNode.Clone());
}
else
{
if (replaceOldValues)
{
// The destination exists and should be replaced.
destXMP.SetNode(destNode, sourceNode.GetValue(), sourceNode.GetOptions(), true);
destParent.RemoveChild(destNode);
destNode = (XMPNode)sourceNode.Clone();
destParent.AddChild(destNode);
}
else
{
// The destination exists and is not totally replaced. Structs and
// arrays are merged.
PropertyOptions sourceForm = sourceNode.GetOptions();
PropertyOptions destForm = destNode.GetOptions();
if (sourceForm != destForm)
{
return;
}
if (sourceForm.IsStruct())
{
// To merge a struct process the fields recursively. E.g. add simple missing fields.
// The recursive call to AppendSubtree will handle deletion for fields with empty
// values.
for (Iterator it = sourceNode.IterateChildren(); it.HasNext(); )
{
XMPNode sourceField = (XMPNode)it.Next();
AppendSubtree(destXMP, sourceField, destNode, replaceOldValues, deleteEmptyValues);
if (deleteEmptyValues && !destNode.HasChildren())
{
destParent.RemoveChild(destNode);
}
}
}
else
{
if (sourceForm.IsArrayAltText())
{
// Merge AltText arrays by the "xml:lang" qualifiers. Make sure x-default is first.
// Make a special check for deletion of empty values. Meaningful in AltText arrays
// because the "xml:lang" qualifier provides unambiguous source/dest correspondence.
for (Iterator it = sourceNode.IterateChildren(); it.HasNext(); )
{
XMPNode sourceItem = (XMPNode)it.Next();
if (!sourceItem.HasQualifier() || !XMPConstConstants.XmlLang.Equals(sourceItem.GetQualifier(1).GetName()))
{
continue;
}
int destIndex = XMPNodeUtils.LookupLanguageItem(destNode, sourceItem.GetQualifier(1).GetValue());
if (deleteEmptyValues && (sourceItem.GetValue() == null || sourceItem.GetValue().Length == 0))
{
if (destIndex != -1)
{
destNode.RemoveChild(destIndex);
if (!destNode.HasChildren())
{
destParent.RemoveChild(destNode);
}
}
}
else
{
if (destIndex == -1)
{
// Not replacing, keep the existing item.
if (!XMPConstConstants.XDefault.Equals(sourceItem.GetQualifier(1).GetValue()) || !destNode.HasChildren())
{
sourceItem.CloneSubtree(destNode);
}
else
{
XMPNode destItem = new XMPNode(sourceItem.GetName(), sourceItem.GetValue(), sourceItem.GetOptions());
sourceItem.CloneSubtree(destItem);
destNode.AddChild(1, destItem);
}
}
}
}
}
else
{
if (sourceForm.IsArray())
{
// Merge other arrays by item values. Don't worry about order or duplicates. Source
// items with empty values do not cause deletion, that conflicts horribly with
// merging.
for (Iterator @is = sourceNode.IterateChildren(); @is.HasNext(); )
{
XMPNode sourceItem = (XMPNode)@is.Next();
bool match = false;
for (Iterator id = destNode.IterateChildren(); id.HasNext(); )
{
XMPNode destItem = (XMPNode)id.Next();
if (ItemValuesMatch(sourceItem, destItem))
{
match = true;
}
}
if (!match)
{
destNode = (XMPNode)sourceItem.Clone();
destParent.AddChild(destNode);
}
}
}
}
}
}
}
}
}
/// <summary>Compares two nodes including its children and qualifier.</summary>
/// <param name="leftNode">an <code>XMPNode</code></param>
/// <param name="rightNode">an <code>XMPNode</code></param>
/// <returns>Returns true if the nodes are equal, false otherwise.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException">Forwards exceptions to the calling method.</exception>
private static bool ItemValuesMatch(XMPNode leftNode, XMPNode rightNode)
{
PropertyOptions leftForm = leftNode.GetOptions();
PropertyOptions rightForm = rightNode.GetOptions();
if (leftForm.Equals(rightForm))
{
return false;
}
if (leftForm.GetOptions() == 0)
{
// Simple nodes, check the values and xml:lang qualifiers.
if (!leftNode.GetValue().Equals(rightNode.GetValue()))
{
return false;
}
if (leftNode.GetOptions().GetHasLanguage() != rightNode.GetOptions().GetHasLanguage())
{
return false;
}
if (leftNode.GetOptions().GetHasLanguage() && !leftNode.GetQualifier(1).GetValue().Equals(rightNode.GetQualifier(1).GetValue()))
{
return false;
}
}
else
{
if (leftForm.IsStruct())
{
// Struct nodes, see if all fields match, ignoring order.
if (leftNode.GetChildrenLength() != rightNode.GetChildrenLength())
{
return false;
}
for (Iterator it = leftNode.IterateChildren(); it.HasNext(); )
{
XMPNode leftField = (XMPNode)it.Next();
XMPNode rightField = XMPNodeUtils.FindChildNode(rightNode, leftField.GetName(), false);
if (rightField == null || !ItemValuesMatch(leftField, rightField))
{
return false;
}
}
}
else
{
// Array nodes, see if the "leftNode" values are present in the
// "rightNode", ignoring order, duplicates,
// and extra values in the rightNode-> The rightNode is the
// destination for AppendProperties.
System.Diagnostics.Debug.Assert(leftForm.IsArray());
for (Iterator il = leftNode.IterateChildren(); il.HasNext(); )
{
XMPNode leftItem = (XMPNode)il.Next();
bool match = false;
for (Iterator ir = rightNode.IterateChildren(); ir.HasNext(); )
{
XMPNode rightItem = (XMPNode)ir.Next();
if (ItemValuesMatch(leftItem, rightItem))
{
match = true;
break;
}
}
if (!match)
{
return false;
}
}
}
}
return true;
}
// All of the checks passed.
/// <summary>Make sure the separator is OK.</summary>
/// <remarks>
/// Make sure the separator is OK. It must be one semicolon surrounded by
/// zero or more spaces. Any of the recognized semicolons or spaces are
/// allowed.
/// </remarks>
/// <param name="separator"/>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
private static void CheckSeparator(string separator)
{
bool haveSemicolon = false;
for (int i = 0; i < separator.Length; i++)
{
int charKind = ClassifyCharacter(separator[i]);
if (charKind == UckSemicolon)
{
if (haveSemicolon)
{
throw new XMPException("Separator can have only one semicolon", XMPErrorConstants.Badparam);
}
haveSemicolon = true;
}
else
{
if (charKind != UckSpace)
{
throw new XMPException("Separator can have only spaces and one semicolon", XMPErrorConstants.Badparam);
}
}
}
if (!haveSemicolon)
{
throw new XMPException("Separator must have one semicolon", XMPErrorConstants.Badparam);
}
}
/// <summary>
/// Make sure the open and close quotes are a legitimate pair and return the
/// correct closing quote or an exception.
/// </summary>
/// <param name="quotes">opened and closing quote in a string</param>
/// <param name="openQuote">the open quote</param>
/// <returns>Returns a corresponding closing quote.</returns>
/// <exception cref="Com.Adobe.Xmp.XMPException"/>
private static char CheckQuotes(string quotes, char openQuote)
{
char closeQuote;
int charKind = ClassifyCharacter(openQuote);
if (charKind != UckQuote)
{
throw new XMPException("Invalid quoting character", XMPErrorConstants.Badparam);
}
if (quotes.Length == 1)
{
closeQuote = openQuote;
}
else
{
closeQuote = quotes[1];
charKind = ClassifyCharacter(closeQuote);
if (charKind != UckQuote)
{
throw new XMPException("Invalid quoting character", XMPErrorConstants.Badparam);
}
}
if (closeQuote != GetClosingQuote(openQuote))
{
throw new XMPException("Mismatched quote pair", XMPErrorConstants.Badparam);
}
return closeQuote;
}
/// <summary>
/// Classifies the character into normal chars, spaces, semicola, quotes,
/// control chars.
/// </summary>
/// <param name="ch">a char</param>
/// <returns>Return the character kind.</returns>
private static int ClassifyCharacter(char ch)
{
if (Spaces.IndexOf(ch) >= 0 || (unchecked((int)(0x2000)) <= ch && ch <= unchecked((int)(0x200B))))
{
return UckSpace;
}
else
{
if (Commas.IndexOf(ch) >= 0)
{
return UckComma;
}
else
{
if (Semicola.IndexOf(ch) >= 0)
{
return UckSemicolon;
}
else
{
if (Quotes.IndexOf(ch) >= 0 || (unchecked((int)(0x3008)) <= ch && ch <= unchecked((int)(0x300F))) || (unchecked((int)(0x2018)) <= ch && ch <= unchecked((int)(0x201F))))
{
return UckQuote;
}
else
{
if (ch < unchecked((int)(0x0020)) || Controls.IndexOf(ch) >= 0)
{
return UckControl;
}
else
{
// Assume typical case.
return UckNormal;
}
}
}
}
}
}
/// <param name="openQuote">the open quote char</param>
/// <returns>Returns the matching closing quote for an open quote.</returns>
private static char GetClosingQuote(char openQuote)
{
switch (openQuote)
{
case (char)0x0022:
{
return (char)0x0022;
}
case (char)0x00AB:
{
// ! U+0022 is both opening and closing.
// Not interpreted as brackets anymore
// case 0x005B:
// return 0x005D;
return (char)0x00BB;
}
case (char)0x00BB:
{
// ! U+00AB and U+00BB are reversible.
return (char)0x00AB;
}
case (char)0x2015:
{
return (char)0x2015;
}
case (char)0x2018:
{
// ! U+2015 is both opening and closing.
return (char)0x2019;
}
case (char)0x201A:
{
return (char)0x201B;
}
case (char)0x201C:
{
return (char)0x201D;
}
case (char)0x201E:
{
return (char)0x201F;
}
case (char)0x2039:
{
return (char)0x203A;
}
case (char)0x203A:
{
// ! U+2039 and U+203A are reversible.
return (char)0x2039;
}
case (char)0x3008:
{
return (char)0x3009;
}
case (char)0x300A:
{
return (char)0x300B;
}
case (char)0x300C:
{
return (char)0x300D;
}
case (char)0x300E:
{
return (char)0x300F;
}
case (char)0x301D:
{
return (char)0x301F;
}
default:
{
// ! U+301E also closes U+301D.
return (char)0;
}
}
}
/// <summary>Add quotes to the item.</summary>
/// <param name="item">the array item</param>
/// <param name="openQuote">the open quote character</param>
/// <param name="closeQuote">the closing quote character</param>
/// <param name="allowCommas">flag if commas are allowed</param>
/// <returns>Returns the value in quotes.</returns>
private static string ApplyQuotes(string item, char openQuote, char closeQuote, bool allowCommas)
{
if (item == null)
{
item = string.Empty;
}
bool prevSpace = false;
int charOffset;
int charKind;
// See if there are any separators in the value. Stop at the first
// occurrance. This is a bit
// tricky in order to make typical typing work conveniently. The purpose
// of applying quotes
// is to preserve the values when splitting them back apart. That is
// CatenateContainerItems
// and SeparateContainerItems must round trip properly. For the most
// part we only look for
// separators here. Internal quotes, as in -- Irving "Bud" Jones --
// won't cause problems in
// the separation. An initial quote will though, it will make the value
// look quoted.
int i;
for (i = 0; i < item.Length; i++)
{
char ch = item[i];
charKind = ClassifyCharacter(ch);
if (i == 0 && charKind == UckQuote)
{
break;
}
if (charKind == UckSpace)
{
// Multiple spaces are a separator.
if (prevSpace)
{
break;
}
prevSpace = true;
}
else
{
prevSpace = false;
if ((charKind == UckSemicolon || charKind == UckControl) || (charKind == UckComma && !allowCommas))
{
break;
}
}
}
if (i < item.Length)
{
// Create a quoted copy, doubling any internal quotes that match the
// outer ones. Internal quotes did not stop the "needs quoting"
// search, but they do need
// doubling. So we have to rescan the front of the string for
// quotes. Handle the special
// case of U+301D being closed by either U+301E or U+301F.
StringBuilder newItem = new StringBuilder(item.Length + 2);
int splitPoint;
for (splitPoint = 0; splitPoint <= i; splitPoint++)
{
if (ClassifyCharacter(item[i]) == UckQuote)
{
break;
}
}
// Copy the leading "normal" portion.
newItem.Append(openQuote).Append(Sharpen.Runtime.Substring(item, 0, splitPoint));
for (charOffset = splitPoint; charOffset < item.Length; charOffset++)
{
newItem.Append(item[charOffset]);
if (ClassifyCharacter(item[charOffset]) == UckQuote && IsSurroundingQuote(item[charOffset], openQuote, closeQuote))
{
newItem.Append(item[charOffset]);
}
}
newItem.Append(closeQuote);
item = newItem.ToString();
}
return item;
}
/// <param name="ch">a character</param>
/// <param name="openQuote">the opening quote char</param>
/// <param name="closeQuote">the closing quote char</param>
/// <returns>Return it the character is a surrounding quote.</returns>
private static bool IsSurroundingQuote(char ch, char openQuote, char closeQuote)
{
return ch == openQuote || IsClosingingQuote(ch, openQuote, closeQuote);
}
/// <param name="ch">a character</param>
/// <param name="openQuote">the opening quote char</param>
/// <param name="closeQuote">the closing quote char</param>
/// <returns>Returns true if the character is a closing quote.</returns>
private static bool IsClosingingQuote(char ch, char openQuote, char closeQuote)
{
return ch == closeQuote || (openQuote == unchecked((int)(0x301D)) && ch == unchecked((int)(0x301E)) || ch == unchecked((int)(0x301F)));
}
/// <summary>
/// U+0022 ASCII space<br />
/// U+3000, ideographic space<br />
/// U+303F, ideographic half fill space<br />
/// U+2000..U+200B, en quad through zero width space
/// </summary>
private const string Spaces = "\u0020\u3000\u303F";
/// <summary>
/// U+002C, ASCII comma<br />
/// U+FF0C, full width comma<br />
/// U+FF64, half width ideographic comma<br />
/// U+FE50, small comma<br />
/// U+FE51, small ideographic comma<br />
/// U+3001, ideographic comma<br />
/// U+060C, Arabic comma<br />
/// U+055D, Armenian comma
/// </summary>
private const string Commas = "\u002C\uFF0C\uFF64\uFE50\uFE51\u3001\u060C\u055D";
/// <summary>
/// U+003B, ASCII semicolon<br />
/// U+FF1B, full width semicolon<br />
/// U+FE54, small semicolon<br />
/// U+061B, Arabic semicolon<br />
/// U+037E, Greek "semicolon" (really a question mark)
/// </summary>
private const string Semicola = "\u003B\uFF1B\uFE54\u061B\u037E";
/// <summary>
/// U+0022 ASCII quote<br />
/// The square brackets are not interpreted as quotes anymore (bug #2674672)
/// (ASCII '[' (0x5B) and ']' (0x5D) are used as quotes in Chinese and
/// Korean.)<br />
/// U+00AB and U+00BB, guillemet quotes<br />
/// U+3008..U+300F, various quotes.<br />
/// U+301D..U+301F, double prime quotes.<br />
/// U+2015, dash quote.<br />
/// U+2018..U+201F, various quotes.<br />
/// U+2039 and U+203A, guillemet quotes.
/// </summary>
private const string Quotes = "\"\u00AB\u00BB\u301D\u301E\u301F\u2015\u2039\u203A";
/// <summary>
/// U+0000..U+001F ASCII controls<br />
/// U+2028, line separator.<br />
/// U+2029, paragraph separator.
/// </summary>
private const string Controls = "\u2028\u2029";
// "\"\u005B\u005D\u00AB\u00BB\u301D\u301E\u301F\u2015\u2039\u203A";
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
[CustomEditor(typeof(Puppet2D_IKHandle))]
public class Puppet2D_IKHandleEditor : Editor
{
public string[] IkType = { "Basic 3 Bone", "Multi Bone" };
// private List<Quaternion> bindPose;
// private List<Transform> bindBones;
public void OnEnable()
{
Puppet2D_IKHandle myTarget = (Puppet2D_IKHandle)target;
//myTarget.startTransform = myTarget.topJointTransform;
myTarget.endTransform = myTarget.bottomJointTransform;
}
public override void OnInspectorGUI()
{
Puppet2D_IKHandle myTarget = (Puppet2D_IKHandle)target;
GUI.changed = false;
// DrawDefaultInspector();
EditorGUI.BeginChangeCheck ();
myTarget.numberIkBonesIndex = EditorGUILayout.Popup("IK Type", myTarget.numberIkBonesIndex, IkType);//The popup menu is displayed simple as that
if (EditorGUI.EndChangeCheck ())
{
if (myTarget.numberIkBonesIndex == 0)
resetIK (myTarget);
else
{
myTarget.bindPose = new List<Vector3> ();
myTarget.bindBones = new List<Transform> ();
myTarget.bindPose.Clear ();
myTarget.bindBones.Clear ();
Transform node = myTarget.bottomJointTransform;
while (true)
{
if (node == null)
break;
myTarget.bindBones.Add (node);
myTarget.bindPose.Add (node.localEulerAngles);
node = node.parent;
}
setEndBone (myTarget);
}
}
if ((target as Puppet2D_IKHandle).numberIkBonesIndex == 0)
{
myTarget.Flip = EditorGUILayout.Toggle ("Flip", myTarget.Flip);
myTarget.SquashAndStretch = EditorGUILayout.Toggle ("SquashAndStretch", myTarget.SquashAndStretch);
myTarget.Scale = EditorGUILayout.Toggle ("Scale", myTarget.Scale);
}
else
{
EditorGUI.BeginChangeCheck ();
myTarget.numberOfBones = EditorGUILayout.IntField("Number of Bones", myTarget.numberOfBones);
if (EditorGUI.EndChangeCheck ())
{
setEndBone (myTarget);
}
myTarget.iterations = EditorGUILayout.IntField("Iterations", myTarget.iterations);
myTarget.damping = EditorGUILayout.Slider("Dampening", myTarget.damping, 0f, 1f);
EditorGUI.BeginChangeCheck ();
myTarget.limitBones = EditorGUILayout.Toggle ("Limits", myTarget.limitBones);
if (EditorGUI.EndChangeCheck ())
{
setEndBone (myTarget);
}
if(GUILayout.Button("Reset"))
{
resetIK(myTarget);
myTarget.transform.localPosition = Vector3.zero;
}
}
if(GUI.changed)
EditorUtility.SetDirty(myTarget);
}
public void resetIK(Puppet2D_IKHandle myTarget)
{
myTarget.enabled = false;
//myTarget.transform.localPosition = Vector3.zero;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < myTarget.bindBones.Count; j++)
{
myTarget.bindBones [j].localRotation = Quaternion.Euler( myTarget.bindPose[j]);
}
}
myTarget.enabled = true;
}
public void setEndBone(Puppet2D_IKHandle myTarget)
{
myTarget.angleLimits.Clear();
myTarget.angleLimitTransform.Clear();
if (myTarget.numberOfBones < 2)
myTarget.numberOfBones = 2;
Puppet2D_GlobalControl[] globalCtrlScripts = Transform.FindObjectsOfType<Puppet2D_GlobalControl> ();
myTarget.endTransform = myTarget.bottomJointTransform;
myTarget.startTransform = myTarget.endTransform;
bool unlockedBone = true;
for(int i=0;i<myTarget.numberOfBones-1;i++)
{
if (myTarget.startTransform.parent != null)
{
for (int j = 0; j < globalCtrlScripts.Length; j++)
{
if (myTarget.startTransform.parent.GetComponent<Puppet2D_GlobalControl>())
{
myTarget.numberOfBones = i + 1;
unlockedBone = false;
}
foreach (Puppet2D_ParentControl ParentControl in globalCtrlScripts[j]._ParentControls)
{
if (ParentControl.bone.transform == myTarget.startTransform.parent)
{
myTarget.numberOfBones = i + 1;
unlockedBone = false;
}
}
foreach (Puppet2D_SplineControl splineCtrl in globalCtrlScripts[j]._SplineControls)
{
foreach (GameObject bone in splineCtrl.bones)
{
if (bone.transform == myTarget.startTransform.parent)
{
myTarget.numberOfBones = i + 1;
unlockedBone = false;
}
}
}
}
if (unlockedBone)
{
if(myTarget.startTransform != myTarget.endTransform && myTarget.limitBones)
{
Vector2 limit = new Vector2 ();
Transform limitTransform = myTarget.startTransform;
Vector3 newEulerAngle = new Vector3 (limitTransform.localEulerAngles.x % 360,
limitTransform.localEulerAngles.y % 360,
limitTransform.localEulerAngles.z % 360);
if (newEulerAngle.x < 0)
newEulerAngle.x += 360;
if (newEulerAngle.y < 0)
newEulerAngle.y += 360;
if (newEulerAngle.z < 0)
newEulerAngle.z += 360;
myTarget.startTransform.localEulerAngles = newEulerAngle;
float rangedVal = limitTransform.localEulerAngles.z % 360;
if( rangedVal > 0 && rangedVal < 180)
{
limit = new Vector2(0, 180);
myTarget.angleLimits.Add (limit);
myTarget.angleLimitTransform.Add (limitTransform);
}
else if( rangedVal > 180 && rangedVal < 360)
{
limit = new Vector2(180, 360);
myTarget.angleLimits.Add (limit);
myTarget.angleLimitTransform.Add (limitTransform);
}
else if( rangedVal > -180 && rangedVal < 0)
{
limit = new Vector2(-180, 0);
myTarget.angleLimits.Add (limit);
myTarget.angleLimitTransform.Add (limitTransform);
}
else if( rangedVal > -360 && rangedVal < -180)
{
limit = new Vector2(-360, -180);
myTarget.angleLimits.Add (limit);
myTarget.angleLimitTransform.Add (limitTransform);
}
}
myTarget.startTransform = myTarget.startTransform.parent;
}
}
else
myTarget.numberOfBones = i + 1;
}
//CreateNodeCache (myTarget);
// Debug.Log ("start " + myTarget.startTransform + " end " + myTarget.endTransform);
}
// void CreateNodeCache(Puppet2D_IKHandle myTarget)
// {
// // Cache optimization
// myTarget.nodeCache = new Dictionary<Transform, AngleLimitNode>(myTarget.angleLimits.Count);
// foreach (var node in myTarget.angleLimits)
// if (!myTarget.nodeCache.ContainsKey(node.Transform))
// myTarget.nodeCache.Add(node.Transform, node);
// }
}
| |
using System;
using static OneOf.Functions;
namespace OneOf
{
public class OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> : IOneOf
{
readonly T0 _value0;
readonly T1 _value1;
readonly T2 _value2;
readonly T3 _value3;
readonly T4 _value4;
readonly T5 _value5;
readonly T6 _value6;
readonly T7 _value7;
readonly T8 _value8;
readonly T9 _value9;
readonly T10 _value10;
readonly T11 _value11;
readonly T12 _value12;
readonly T13 _value13;
readonly T14 _value14;
readonly T15 _value15;
readonly T16 _value16;
readonly T17 _value17;
readonly T18 _value18;
readonly int _index;
protected OneOfBase(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> input)
{
_index = input.Index;
switch (_index)
{
case 0: _value0 = input.AsT0; break;
case 1: _value1 = input.AsT1; break;
case 2: _value2 = input.AsT2; break;
case 3: _value3 = input.AsT3; break;
case 4: _value4 = input.AsT4; break;
case 5: _value5 = input.AsT5; break;
case 6: _value6 = input.AsT6; break;
case 7: _value7 = input.AsT7; break;
case 8: _value8 = input.AsT8; break;
case 9: _value9 = input.AsT9; break;
case 10: _value10 = input.AsT10; break;
case 11: _value11 = input.AsT11; break;
case 12: _value12 = input.AsT12; break;
case 13: _value13 = input.AsT13; break;
case 14: _value14 = input.AsT14; break;
case 15: _value15 = input.AsT15; break;
case 16: _value16 = input.AsT16; break;
case 17: _value17 = input.AsT17; break;
case 18: _value18 = input.AsT18; break;
default: throw new InvalidOperationException();
}
}
public object Value =>
_index switch
{
0 => _value0,
1 => _value1,
2 => _value2,
3 => _value3,
4 => _value4,
5 => _value5,
6 => _value6,
7 => _value7,
8 => _value8,
9 => _value9,
10 => _value10,
11 => _value11,
12 => _value12,
13 => _value13,
14 => _value14,
15 => _value15,
16 => _value16,
17 => _value17,
18 => _value18,
_ => throw new InvalidOperationException()
};
public int Index => _index;
public bool IsT0 => _index == 0;
public bool IsT1 => _index == 1;
public bool IsT2 => _index == 2;
public bool IsT3 => _index == 3;
public bool IsT4 => _index == 4;
public bool IsT5 => _index == 5;
public bool IsT6 => _index == 6;
public bool IsT7 => _index == 7;
public bool IsT8 => _index == 8;
public bool IsT9 => _index == 9;
public bool IsT10 => _index == 10;
public bool IsT11 => _index == 11;
public bool IsT12 => _index == 12;
public bool IsT13 => _index == 13;
public bool IsT14 => _index == 14;
public bool IsT15 => _index == 15;
public bool IsT16 => _index == 16;
public bool IsT17 => _index == 17;
public bool IsT18 => _index == 18;
public T0 AsT0 =>
_index == 0 ?
_value0 :
throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}");
public T1 AsT1 =>
_index == 1 ?
_value1 :
throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}");
public T2 AsT2 =>
_index == 2 ?
_value2 :
throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}");
public T3 AsT3 =>
_index == 3 ?
_value3 :
throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}");
public T4 AsT4 =>
_index == 4 ?
_value4 :
throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}");
public T5 AsT5 =>
_index == 5 ?
_value5 :
throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}");
public T6 AsT6 =>
_index == 6 ?
_value6 :
throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}");
public T7 AsT7 =>
_index == 7 ?
_value7 :
throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}");
public T8 AsT8 =>
_index == 8 ?
_value8 :
throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}");
public T9 AsT9 =>
_index == 9 ?
_value9 :
throw new InvalidOperationException($"Cannot return as T9 as result is T{_index}");
public T10 AsT10 =>
_index == 10 ?
_value10 :
throw new InvalidOperationException($"Cannot return as T10 as result is T{_index}");
public T11 AsT11 =>
_index == 11 ?
_value11 :
throw new InvalidOperationException($"Cannot return as T11 as result is T{_index}");
public T12 AsT12 =>
_index == 12 ?
_value12 :
throw new InvalidOperationException($"Cannot return as T12 as result is T{_index}");
public T13 AsT13 =>
_index == 13 ?
_value13 :
throw new InvalidOperationException($"Cannot return as T13 as result is T{_index}");
public T14 AsT14 =>
_index == 14 ?
_value14 :
throw new InvalidOperationException($"Cannot return as T14 as result is T{_index}");
public T15 AsT15 =>
_index == 15 ?
_value15 :
throw new InvalidOperationException($"Cannot return as T15 as result is T{_index}");
public T16 AsT16 =>
_index == 16 ?
_value16 :
throw new InvalidOperationException($"Cannot return as T16 as result is T{_index}");
public T17 AsT17 =>
_index == 17 ?
_value17 :
throw new InvalidOperationException($"Cannot return as T17 as result is T{_index}");
public T18 AsT18 =>
_index == 18 ?
_value18 :
throw new InvalidOperationException($"Cannot return as T18 as result is T{_index}");
public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11, Action<T12> f12, Action<T13> f13, Action<T14> f14, Action<T15> f15, Action<T16> f16, Action<T17> f17, Action<T18> f18)
{
if (_index == 0 && f0 != null)
{
f0(_value0);
return;
}
if (_index == 1 && f1 != null)
{
f1(_value1);
return;
}
if (_index == 2 && f2 != null)
{
f2(_value2);
return;
}
if (_index == 3 && f3 != null)
{
f3(_value3);
return;
}
if (_index == 4 && f4 != null)
{
f4(_value4);
return;
}
if (_index == 5 && f5 != null)
{
f5(_value5);
return;
}
if (_index == 6 && f6 != null)
{
f6(_value6);
return;
}
if (_index == 7 && f7 != null)
{
f7(_value7);
return;
}
if (_index == 8 && f8 != null)
{
f8(_value8);
return;
}
if (_index == 9 && f9 != null)
{
f9(_value9);
return;
}
if (_index == 10 && f10 != null)
{
f10(_value10);
return;
}
if (_index == 11 && f11 != null)
{
f11(_value11);
return;
}
if (_index == 12 && f12 != null)
{
f12(_value12);
return;
}
if (_index == 13 && f13 != null)
{
f13(_value13);
return;
}
if (_index == 14 && f14 != null)
{
f14(_value14);
return;
}
if (_index == 15 && f15 != null)
{
f15(_value15);
return;
}
if (_index == 16 && f16 != null)
{
f16(_value16);
return;
}
if (_index == 17 && f17 != null)
{
f17(_value17);
return;
}
if (_index == 18 && f18 != null)
{
f18(_value18);
return;
}
throw new InvalidOperationException();
}
public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11, Func<T12, TResult> f12, Func<T13, TResult> f13, Func<T14, TResult> f14, Func<T15, TResult> f15, Func<T16, TResult> f16, Func<T17, TResult> f17, Func<T18, TResult> f18)
{
if (_index == 0 && f0 != null)
{
return f0(_value0);
}
if (_index == 1 && f1 != null)
{
return f1(_value1);
}
if (_index == 2 && f2 != null)
{
return f2(_value2);
}
if (_index == 3 && f3 != null)
{
return f3(_value3);
}
if (_index == 4 && f4 != null)
{
return f4(_value4);
}
if (_index == 5 && f5 != null)
{
return f5(_value5);
}
if (_index == 6 && f6 != null)
{
return f6(_value6);
}
if (_index == 7 && f7 != null)
{
return f7(_value7);
}
if (_index == 8 && f8 != null)
{
return f8(_value8);
}
if (_index == 9 && f9 != null)
{
return f9(_value9);
}
if (_index == 10 && f10 != null)
{
return f10(_value10);
}
if (_index == 11 && f11 != null)
{
return f11(_value11);
}
if (_index == 12 && f12 != null)
{
return f12(_value12);
}
if (_index == 13 && f13 != null)
{
return f13(_value13);
}
if (_index == 14 && f14 != null)
{
return f14(_value14);
}
if (_index == 15 && f15 != null)
{
return f15(_value15);
}
if (_index == 16 && f16 != null)
{
return f16(_value16);
}
if (_index == 17 && f17 != null)
{
return f17(_value17);
}
if (_index == 18 && f18 != null)
{
return f18(_value18);
}
throw new InvalidOperationException();
}
public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT0 ? AsT0 : default;
remainder = _index switch
{
0 => default,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT0;
}
public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT1 ? AsT1 : default;
remainder = _index switch
{
0 => AsT0,
1 => default,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT1;
}
public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT2 ? AsT2 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => default,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT2;
}
public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT3 ? AsT3 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => default,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT3;
}
public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT4 ? AsT4 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => default,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT4;
}
public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT5 ? AsT5 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => default,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT5;
}
public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT6 ? AsT6 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => default,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT6;
}
public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT7 ? AsT7 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => default,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT7;
}
public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT8 ? AsT8 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => default,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT8;
}
public bool TryPickT9(out T9 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT9 ? AsT9 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => default,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT9;
}
public bool TryPickT10(out T10 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT10 ? AsT10 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => default,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT10;
}
public bool TryPickT11(out T11 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T12, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT11 ? AsT11 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => default,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT11;
}
public bool TryPickT12(out T12 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T13, T14, T15, T16, T17, T18> remainder)
{
value = IsT12 ? AsT12 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => default,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT12;
}
public bool TryPickT13(out T13 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T14, T15, T16, T17, T18> remainder)
{
value = IsT13 ? AsT13 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => default,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT13;
}
public bool TryPickT14(out T14 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T15, T16, T17, T18> remainder)
{
value = IsT14 ? AsT14 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => default,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT14;
}
public bool TryPickT15(out T15 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T16, T17, T18> remainder)
{
value = IsT15 ? AsT15 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => default,
16 => AsT16,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT15;
}
public bool TryPickT16(out T16 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T17, T18> remainder)
{
value = IsT16 ? AsT16 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => default,
17 => AsT17,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT16;
}
public bool TryPickT17(out T17 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T18> remainder)
{
value = IsT17 ? AsT17 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => default,
18 => AsT18,
_ => throw new InvalidOperationException()
};
return this.IsT17;
}
public bool TryPickT18(out T18 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> remainder)
{
value = IsT18 ? AsT18 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
12 => AsT12,
13 => AsT13,
14 => AsT14,
15 => AsT15,
16 => AsT16,
17 => AsT17,
18 => default,
_ => throw new InvalidOperationException()
};
return this.IsT18;
}
bool Equals(OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> other) =>
_index == other._index &&
_index switch
{
0 => Equals(_value0, other._value0),
1 => Equals(_value1, other._value1),
2 => Equals(_value2, other._value2),
3 => Equals(_value3, other._value3),
4 => Equals(_value4, other._value4),
5 => Equals(_value5, other._value5),
6 => Equals(_value6, other._value6),
7 => Equals(_value7, other._value7),
8 => Equals(_value8, other._value8),
9 => Equals(_value9, other._value9),
10 => Equals(_value10, other._value10),
11 => Equals(_value11, other._value11),
12 => Equals(_value12, other._value12),
13 => Equals(_value13, other._value13),
14 => Equals(_value14, other._value14),
15 => Equals(_value15, other._value15),
16 => Equals(_value16, other._value16),
17 => Equals(_value17, other._value17),
18 => Equals(_value18, other._value18),
_ => false
};
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj)) {
return true;
}
return obj is OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> o && Equals(o);
}
public override string ToString() =>
_index switch {
0 => FormatValue(_value0),
1 => FormatValue(_value1),
2 => FormatValue(_value2),
3 => FormatValue(_value3),
4 => FormatValue(_value4),
5 => FormatValue(_value5),
6 => FormatValue(_value6),
7 => FormatValue(_value7),
8 => FormatValue(_value8),
9 => FormatValue(_value9),
10 => FormatValue(_value10),
11 => FormatValue(_value11),
12 => FormatValue(_value12),
13 => FormatValue(_value13),
14 => FormatValue(_value14),
15 => FormatValue(_value15),
16 => FormatValue(_value16),
17 => FormatValue(_value17),
18 => FormatValue(_value18),
_ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.")
};
public override int GetHashCode()
{
unchecked
{
int hashCode = _index switch
{
0 => _value0?.GetHashCode(),
1 => _value1?.GetHashCode(),
2 => _value2?.GetHashCode(),
3 => _value3?.GetHashCode(),
4 => _value4?.GetHashCode(),
5 => _value5?.GetHashCode(),
6 => _value6?.GetHashCode(),
7 => _value7?.GetHashCode(),
8 => _value8?.GetHashCode(),
9 => _value9?.GetHashCode(),
10 => _value10?.GetHashCode(),
11 => _value11?.GetHashCode(),
12 => _value12?.GetHashCode(),
13 => _value13?.GetHashCode(),
14 => _value14?.GetHashCode(),
15 => _value15?.GetHashCode(),
16 => _value16?.GetHashCode(),
17 => _value17?.GetHashCode(),
18 => _value18?.GetHashCode(),
_ => 0
} ?? 0;
return (hashCode*397) ^ _index;
}
}
}
}
| |
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>
/// Delivery Addresses Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KADDataSet : EduHubDataSet<KAD>
{
/// <inheritdoc />
public override string Name { get { return "KAD"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KADDataSet(EduHubContext Context)
: base(Context)
{
Index_KADKEY = new Lazy<Dictionary<string, KAD>>(() => this.ToDictionary(i => i.KADKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KAD" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KAD" /> fields for each CSV column header</returns>
internal override Action<KAD, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KAD, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "KADKEY":
mapper[i] = (e, v) => e.KADKEY = v;
break;
case "ADDRESS01":
mapper[i] = (e, v) => e.ADDRESS01 = v;
break;
case "ADDRESS02":
mapper[i] = (e, v) => e.ADDRESS02 = v;
break;
case "ADDRESS03":
mapper[i] = (e, v) => e.ADDRESS03 = 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="KAD" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KAD" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KAD" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KAD}"/> of entities</returns>
internal override IEnumerable<KAD> ApplyDeltaEntities(IEnumerable<KAD> Entities, List<KAD> DeltaEntities)
{
HashSet<string> Index_KADKEY = new HashSet<string>(DeltaEntities.Select(i => i.KADKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.KADKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_KADKEY.Remove(entity.KADKEY);
if (entity.KADKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, KAD>> Index_KADKEY;
#endregion
#region Index Methods
/// <summary>
/// Find KAD by KADKEY field
/// </summary>
/// <param name="KADKEY">KADKEY value used to find KAD</param>
/// <returns>Related KAD entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KAD FindByKADKEY(string KADKEY)
{
return Index_KADKEY.Value[KADKEY];
}
/// <summary>
/// Attempt to find KAD by KADKEY field
/// </summary>
/// <param name="KADKEY">KADKEY value used to find KAD</param>
/// <param name="Value">Related KAD entity</param>
/// <returns>True if the related KAD entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByKADKEY(string KADKEY, out KAD Value)
{
return Index_KADKEY.Value.TryGetValue(KADKEY, out Value);
}
/// <summary>
/// Attempt to find KAD by KADKEY field
/// </summary>
/// <param name="KADKEY">KADKEY value used to find KAD</param>
/// <returns>Related KAD entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KAD TryFindByKADKEY(string KADKEY)
{
KAD value;
if (Index_KADKEY.Value.TryGetValue(KADKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KAD 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].[KAD]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KAD](
[KADKEY] varchar(10) NOT NULL,
[ADDRESS01] varchar(30) NULL,
[ADDRESS02] varchar(30) NULL,
[ADDRESS03] varchar(30) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KAD_Index_KADKEY] PRIMARY KEY CLUSTERED (
[KADKEY] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KADDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KADDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KAD"/> 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="KAD"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KAD> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_KADKEY = new List<string>();
foreach (var entity in Entities)
{
Index_KADKEY.Add(entity.KADKEY);
}
builder.AppendLine("DELETE [dbo].[KAD] WHERE");
// Index_KADKEY
builder.Append("[KADKEY] IN (");
for (int index = 0; index < Index_KADKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// KADKEY
var parameterKADKEY = $"@p{parameterIndex++}";
builder.Append(parameterKADKEY);
command.Parameters.Add(parameterKADKEY, SqlDbType.VarChar, 10).Value = Index_KADKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KAD data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KAD data set</returns>
public override EduHubDataSetDataReader<KAD> GetDataSetDataReader()
{
return new KADDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KAD data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KAD data set</returns>
public override EduHubDataSetDataReader<KAD> GetDataSetDataReader(List<KAD> Entities)
{
return new KADDataReader(new EduHubDataSetLoadedReader<KAD>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KADDataReader : EduHubDataSetDataReader<KAD>
{
public KADDataReader(IEduHubDataSetReader<KAD> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 7; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // KADKEY
return Current.KADKEY;
case 1: // ADDRESS01
return Current.ADDRESS01;
case 2: // ADDRESS02
return Current.ADDRESS02;
case 3: // ADDRESS03
return Current.ADDRESS03;
case 4: // LW_DATE
return Current.LW_DATE;
case 5: // LW_TIME
return Current.LW_TIME;
case 6: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // ADDRESS01
return Current.ADDRESS01 == null;
case 2: // ADDRESS02
return Current.ADDRESS02 == null;
case 3: // ADDRESS03
return Current.ADDRESS03 == null;
case 4: // LW_DATE
return Current.LW_DATE == null;
case 5: // LW_TIME
return Current.LW_TIME == null;
case 6: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // KADKEY
return "KADKEY";
case 1: // ADDRESS01
return "ADDRESS01";
case 2: // ADDRESS02
return "ADDRESS02";
case 3: // ADDRESS03
return "ADDRESS03";
case 4: // LW_DATE
return "LW_DATE";
case 5: // LW_TIME
return "LW_TIME";
case 6: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "KADKEY":
return 0;
case "ADDRESS01":
return 1;
case "ADDRESS02":
return 2;
case "ADDRESS03":
return 3;
case "LW_DATE":
return 4;
case "LW_TIME":
return 5;
case "LW_USER":
return 6;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
namespace FakeItEasy.Tests
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using NUnit.Framework;
using Guard = FakeItEasy.Guard;
[TestFixture]
public class RepeatedTests
{
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Used reflectively.")]
private object[] descriptionTestCases = TestCases.Create(
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.AtLeast.Once,
ExpectedDescription = "at least once"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.AtLeast.Twice,
ExpectedDescription = "at least twice"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.AtLeast.Times(3),
ExpectedDescription = "at least 3 times"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.AtLeast.Times(10),
ExpectedDescription = "at least 10 times"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.AtLeast.Times(10),
ExpectedDescription = "at least 10 times"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.NoMoreThan.Once,
ExpectedDescription = "no more than once"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.NoMoreThan.Twice,
ExpectedDescription = "no more than twice"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.NoMoreThan.Times(10),
ExpectedDescription = "no more than 10 times"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.Exactly.Once,
ExpectedDescription = "exactly once"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.Exactly.Twice,
ExpectedDescription = "exactly twice"
},
new RepeatDescriptionTestCase()
{
Repeat = () => Repeated.Exactly.Times(99),
ExpectedDescription = "exactly 99 times"
}).AsTestCaseSource();
[TestCase(1, 1, Result = true)]
[TestCase(1, 2, Result = false)]
public bool Like_should_return_instance_that_delegates_to_expression(int expected, int actual)
{
// Arrange
Expression<Func<int, bool>> repeatPredicate = repeat => repeat == expected;
// Act
var happened = Repeated.Like(repeatPredicate);
// Assert
return happened.Matches(actual);
}
[Test]
public void Like_should_return_instance_that_has_correct_description()
{
// Arrange
Expression<Func<int, bool>> repeatPredicate = repeat => repeat == 1;
// Act
var happened = Repeated.Like(repeatPredicate);
// Assert
Assert.That(happened.ToString(), Is.EqualTo("the number of times specified by the predicate 'repeat => (repeat == 1)'"));
}
[TestCase(1, Result = true)]
[TestCase(2, Result = false)]
public bool Exactly_once_should_only_match_one(int actualRepeat)
{
// Arrange
// Act
var repeated = Repeated.Exactly.Once;
// Assert
return repeated.Matches(actualRepeat);
}
[TestCase(2, Result = true)]
[TestCase(0, Result = false)]
public bool Exactly_twice_should_only_match_two(int actualRepeat)
{
// Arrange
// Act
var repeated = Repeated.Exactly.Twice;
// Assert
return repeated.Matches(actualRepeat);
}
[TestCase(0, 0, Result = true)]
[TestCase(0, 1, Result = false)]
public bool Exactly_number_of_times_should_match_as_expected(int actualRepeat, int expectedNumberOfTimes)
{
// Arrange
// Act
var repeated = Repeated.Exactly.Times(expectedNumberOfTimes);
// Assert
return repeated.Matches(actualRepeat);
}
[TestCase(1, Result = true)]
[TestCase(0, Result = false)]
[TestCase(2, Result = true)]
public bool At_least_once_should_match_one_or_higher(int actualRepeat)
{
// Arrange
// Act
var repeated = Repeated.AtLeast.Once;
// Assert
return repeated.Matches(actualRepeat);
}
[TestCase(1, Result = false)]
[TestCase(0, Result = false)]
[TestCase(2, Result = true)]
[TestCase(3, Result = true)]
public bool At_least_twice_should_only_match_two_or_higher(int actualRepeat)
{
// Arrange
// Act
var repeated = Repeated.AtLeast.Twice;
// Assert
return repeated.Matches(actualRepeat);
}
[TestCase(0, 0, Result = true)]
[TestCase(1, 0, Result = true)]
[TestCase(1, 1, Result = true)]
[TestCase(0, 1, Result = false)]
[TestCase(2, 1, Result = true)]
public bool At_least_number_of_times_should_match_as_expected(int actualRepeat, int expectedNumberOfTimes)
{
// Arrange
// Act
var repeated = Repeated.AtLeast.Times(expectedNumberOfTimes);
// Assert
return repeated.Matches(actualRepeat);
}
[TestCase(0, Result = true)]
[TestCase(1, Result = true)]
[TestCase(2, Result = false)]
public bool No_more_than_once_should_match_zero_and_one_only(int actualRepeat)
{
// Arrange
// Act
var repeated = Repeated.NoMoreThan.Once;
// Assert
return repeated.Matches(actualRepeat);
}
[TestCase(0, Result = true)]
[TestCase(1, Result = true)]
[TestCase(2, Result = true)]
[TestCase(3, Result = false)]
public bool No_more_than_twice_should_match_zero_one_and_two_only(int actualRepeat)
{
// Arrange
// Act
var repeated = Repeated.NoMoreThan.Twice;
// Assert
return repeated.Matches(actualRepeat);
}
[TestCase(0, 0, Result = true)]
[TestCase(1, 0, Result = false)]
[TestCase(1, 1, Result = true)]
[TestCase(0, 1, Result = true)]
[TestCase(2, 1, Result = false)]
public bool No_more_than_times_should_match_as_expected(int actualRepeat, int expectedNumberOfTimes)
{
// Arrange
// Act
var repeated = Repeated.NoMoreThan.Times(expectedNumberOfTimes);
// Assert
return repeated.Matches(actualRepeat);
}
[TestCase(0, Result = true)]
[TestCase(1, Result = false)]
public bool Never_should_match_zero_only(int actualRepeat)
{
// Arrange
// Act
// Assert
return Repeated.Never.Matches(actualRepeat);
}
[TestCaseSource("descriptionTestCases")]
public void Should_provide_expected_description(Func<Repeated> repeated, string expectedDescription)
{
Guard.AgainstNull(repeated, "repeated");
// Arrange
var repeatedInstance = repeated.Invoke();
// Act
var description = repeatedInstance.ToString();
// Assert
Assert.That(description, Is.EqualTo(expectedDescription));
}
private class RepeatDescriptionTestCase
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Used reflecively.")]
public Func<Repeated> Repeat { get; set; }
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Used reflecively.")]
public string ExpectedDescription { get; set; }
}
}
}
| |
using UnityEngine;
using System.Collections;
public enum PickupCharacterState
{
Idle = 0,
Walking = 1,
Trotting = 2,
Running = 3,
Jumping = 4,
}
[RequireComponent(typeof(CharacterController))]
public class PickupController : MonoBehaviour, IPunObservable
{
public AnimationClip idleAnimation;
public AnimationClip walkAnimation;
public AnimationClip runAnimation;
public AnimationClip jumpPoseAnimation;
public float walkMaxAnimationSpeed = 0.75f;
public float trotMaxAnimationSpeed = 1.0f;
public float runMaxAnimationSpeed = 1.0f;
public float jumpAnimationSpeed = 1.15f;
public float landAnimationSpeed = 1.0f;
private Animation _animation;
public PickupCharacterState _characterState;
// The speed when walking
public float walkSpeed = 2.0f;
// after trotAfterSeconds of walking we trot with trotSpeed
public float trotSpeed = 4.0f;
// when pressing "Fire3" button (cmd) we start running
public float runSpeed = 6.0f;
public float inAirControlAcceleration = 3.0f;
// How high do we jump when pressing jump and letting go immediately
public float jumpHeight = 0.5f;
// The gravity for the character
public float gravity = 20.0f;
// The gravity in controlled descent mode
public float speedSmoothing = 10.0f;
public float rotateSpeed = 500.0f;
public float trotAfterSeconds = 3.0f;
public bool canJump = false;
private float jumpRepeatTime = 0.05f;
private float jumpTimeout = 0.15f;
private float groundedTimeout = 0.25f;
// The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.
private float lockCameraTimer = 0.0f;
// The current move direction in x-z
private Vector3 moveDirection = Vector3.zero;
// The current vertical speed
private float verticalSpeed = 0.0f;
// The current x-z move speed
private float moveSpeed = 0.0f;
// The last collision flags returned from controller.Move
private CollisionFlags collisionFlags;
// Are we jumping? (Initiated with jump button and not grounded yet)
private bool jumping = false;
private bool jumpingReachedApex = false;
// Are we moving backwards (This locks the camera to not do a 180 degree spin)
private bool movingBack = false;
// Is the user pressing any keys?
private bool isMoving = false;
// When did the user start walking (Used for going into trot after a while)
private float walkTimeStart = 0.0f;
// Last time the jump button was clicked down
private float lastJumpButtonTime = -10.0f;
// Last time we performed a jump
private float lastJumpTime = -1.0f;
// the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
//private float lastJumpStartHeight = 0.0f;
private Vector3 inAirVelocity = Vector3.zero;
private float lastGroundedTime = 0.0f;
Vector3 velocity = Vector3.zero;
private Vector3 lastPos;
private Vector3 remotePosition;
public bool isControllable = false;
public bool DoRotate = true;
public float RemoteSmoothing = 5;
public bool AssignAsTagObject = true;
void Awake()
{
// PUN: automatically determine isControllable, if this GO has a PhotonView
PhotonView pv = gameObject.GetComponent<PhotonView>();
if (pv != null)
{
this.isControllable = pv.isMine;
// The pickup demo assigns this GameObject as the PhotonPlayer.TagObject. This way, we can access this character (controller, position, etc) easily
if (this.AssignAsTagObject)
{
pv.owner.TagObject = gameObject;
}
// please note: we change this setting on ANY PickupController if "DoRotate" is off. not only locally when it's "our" GameObject!
if (!this.DoRotate && pv.ObservedComponents != null)
{
for (int i = 0; i < pv.ObservedComponents.Count; ++i)
{
if (pv.ObservedComponents[i] is Transform)
{
pv.onSerializeTransformOption = OnSerializeTransform.OnlyPosition;
break;
}
}
}
}
this.moveDirection = transform.TransformDirection(Vector3.forward);
this._animation = GetComponent<Animation>();
if (!this._animation)
Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");
if (!this.idleAnimation)
{
this._animation = null;
Debug.Log("No idle animation found. Turning off animations.");
}
if (!this.walkAnimation)
{
this._animation = null;
Debug.Log("No walk animation found. Turning off animations.");
}
if (!this.runAnimation)
{
this._animation = null;
Debug.Log("No run animation found. Turning off animations.");
}
if (!this.jumpPoseAnimation && this.canJump)
{
this._animation = null;
Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations.");
}
}
void Update()
{
if (this.isControllable)
{
if (Input.GetButtonDown("Jump"))
{
this.lastJumpButtonTime = Time.time;
}
this.UpdateSmoothedMovementDirection();
// Apply gravity
// - extra power jump modifies gravity
// - controlledDescent mode modifies gravity
this.ApplyGravity();
// Apply jumping logic
this.ApplyJumping();
// Calculate actual motion
Vector3 movement = this.moveDirection *this.moveSpeed + new Vector3(0, this.verticalSpeed, 0) + this.inAirVelocity;
movement *= Time.deltaTime;
//Debug.Log(movement.x.ToString("0.000") + ":" + movement.z.ToString("0.000"));
// Move the controller
CharacterController controller = GetComponent<CharacterController>();
this.collisionFlags = controller.Move(movement);
}
// PUN: if a remote position is known, we smooth-move to it (being late(r) but smoother)
if (this.remotePosition != Vector3.zero)
{
transform.position = Vector3.Lerp(transform.position, this.remotePosition, Time.deltaTime * this.RemoteSmoothing);
}
this.velocity = (transform.position - this.lastPos)*25;
// ANIMATION sector
if (this._animation)
{
if (this._characterState == PickupCharacterState.Jumping)
{
if (!this.jumpingReachedApex)
{
this._animation[this.jumpPoseAnimation.name].speed = this.jumpAnimationSpeed;
this._animation[this.jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
this._animation.CrossFade(this.jumpPoseAnimation.name);
}
else
{
this._animation[this.jumpPoseAnimation.name].speed = -this.landAnimationSpeed;
this._animation[this.jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
this._animation.CrossFade(this.jumpPoseAnimation.name);
}
}
else
{
if (this._characterState == PickupCharacterState.Idle)
{
this._animation.CrossFade(this.idleAnimation.name);
}
else if (this._characterState == PickupCharacterState.Running)
{
this._animation[this.runAnimation.name].speed = this.runMaxAnimationSpeed;
if (this.isControllable)
{
this._animation[this.runAnimation.name].speed = Mathf.Clamp(this.velocity.magnitude, 0.0f, this.runMaxAnimationSpeed);
}
this._animation.CrossFade(this.runAnimation.name);
}
else if (this._characterState == PickupCharacterState.Trotting)
{
this._animation[this.walkAnimation.name].speed = this.trotMaxAnimationSpeed;
if (this.isControllable)
{
this._animation[this.walkAnimation.name].speed = Mathf.Clamp(this.velocity.magnitude, 0.0f, this.trotMaxAnimationSpeed);
}
this._animation.CrossFade(this.walkAnimation.name);
}
else if (this._characterState == PickupCharacterState.Walking)
{
this._animation[this.walkAnimation.name].speed = this.walkMaxAnimationSpeed;
if (this.isControllable)
{
this._animation[this.walkAnimation.name].speed = Mathf.Clamp(this.velocity.magnitude, 0.0f, this.walkMaxAnimationSpeed);
}
this._animation.CrossFade(this.walkAnimation.name);
}
if (this._characterState != PickupCharacterState.Running)
{
this._animation[this.runAnimation.name].time = 0.0f;
}
}
}
// ANIMATION sector
// Set rotation to the move direction
if (this.IsGrounded())
{
// a specialty of this controller: you can disable rotation!
if (this.DoRotate)
{
transform.rotation = Quaternion.LookRotation(this.moveDirection);
}
}
else
{
/* This causes choppy behaviour when colliding with SIDES
* Vector3 xzMove = velocity;
xzMove.y = 0;
if (xzMove.sqrMagnitude > 0.001f)
{
transform.rotation = Quaternion.LookRotation(xzMove);
}*/
}
// We are in jump mode but just became grounded
if (this.IsGrounded())
{
this.lastGroundedTime = Time.time;
this.inAirVelocity = Vector3.zero;
if (this.jumping)
{
this.jumping = false;
SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
}
}
this.lastPos = transform.position;
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.isWriting)
{
stream.SendNext(transform.position);
stream.SendNext((byte)this._characterState);
}
else
{
bool initialRemotePosition = (this.remotePosition == Vector3.zero);
this.remotePosition = (Vector3)stream.ReceiveNext();
this._characterState = (PickupCharacterState)((byte)stream.ReceiveNext());
if (initialRemotePosition)
{
// avoids lerping the character from "center" to the "current" position when this client joins
transform.position = this.remotePosition;
}
}
}
void UpdateSmoothedMovementDirection()
{
Transform cameraTransform = Camera.main.transform;
bool grounded = this.IsGrounded();
// Forward vector relative to the camera along the x-z plane
Vector3 forward = cameraTransform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
// Right vector relative to the camera
// Always orthogonal to the forward vector
Vector3 right = new Vector3(forward.z, 0, -forward.x);
float v = Input.GetAxisRaw("Vertical");
float h = Input.GetAxisRaw("Horizontal");
// Are we moving backwards or looking backwards
if (v < -0.2f)
this.movingBack = true;
else
this.movingBack = false;
bool wasMoving = this.isMoving;
this.isMoving = Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f;
// Target direction relative to the camera
Vector3 targetDirection = h * right + v * forward;
// Debug.Log("targetDirection " + targetDirection);
// Grounded controls
if (grounded)
{
// Lock camera for short period when transitioning moving & standing still
this.lockCameraTimer += Time.deltaTime;
if (this.isMoving != wasMoving)
this.lockCameraTimer = 0.0f;
// We store speed and direction seperately,
// so that when the character stands still we still have a valid forward direction
// moveDirection is always normalized, and we only update it if there is user input.
if (targetDirection != Vector3.zero)
{
// If we are really slow, just snap to the target direction
if (this.moveSpeed < this.walkSpeed * 0.9f && grounded)
{
this.moveDirection = targetDirection.normalized;
}
// Otherwise smoothly turn towards it
else
{
this.moveDirection = Vector3.RotateTowards(this.moveDirection, targetDirection, this.rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);
this.moveDirection = this.moveDirection.normalized;
}
}
// Smooth the speed based on the current target direction
float curSmooth = this.speedSmoothing * Time.deltaTime;
// Choose target speed
//* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
float targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0f);
this._characterState = PickupCharacterState.Idle;
// Pick speed modifier
if ((Input.GetKey(KeyCode.LeftShift) | Input.GetKey(KeyCode.RightShift)) && this.isMoving)
{
targetSpeed *= this.runSpeed;
this._characterState = PickupCharacterState.Running;
}
else if (Time.time - this.trotAfterSeconds > this.walkTimeStart)
{
targetSpeed *= this.trotSpeed;
this._characterState = PickupCharacterState.Trotting;
}
else if (this.isMoving)
{
targetSpeed *= this.walkSpeed;
this._characterState = PickupCharacterState.Walking;
}
this.moveSpeed = Mathf.Lerp(this.moveSpeed, targetSpeed, curSmooth);
// Reset walk time start when we slow down
if (this.moveSpeed < this.walkSpeed * 0.3f)
this.walkTimeStart = Time.time;
}
// In air controls
else
{
// Lock camera while in air
if (this.jumping)
this.lockCameraTimer = 0.0f;
if (this.isMoving)
this.inAirVelocity += targetDirection.normalized * Time.deltaTime *this.inAirControlAcceleration;
}
}
void ApplyJumping()
{
// Prevent jumping too fast after each other
if (this.lastJumpTime + this.jumpRepeatTime > Time.time)
return;
if (this.IsGrounded())
{
// Jump
// - Only when pressing the button down
// - With a timeout so you can press the button slightly before landing
if (this.canJump && Time.time < this.lastJumpButtonTime + this.jumpTimeout)
{
this.verticalSpeed = this.CalculateJumpVerticalSpeed(this.jumpHeight);
SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}
}
}
void ApplyGravity()
{
if (this.isControllable) // don't move player at all if not controllable.
{
// Apply gravity
//bool jumpButton = Input.GetButton("Jump");
// When we reach the apex of the jump we send out a message
if (this.jumping && !this.jumpingReachedApex && this.verticalSpeed <= 0.0f)
{
this.jumpingReachedApex = true;
SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
}
if (this.IsGrounded())
this.verticalSpeed = 0.0f;
else
this.verticalSpeed -= this.gravity * Time.deltaTime;
}
}
float CalculateJumpVerticalSpeed(float targetJumpHeight)
{
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2 * targetJumpHeight *this.gravity);
}
void DidJump()
{
this.jumping = true;
this.jumpingReachedApex = false;
this.lastJumpTime = Time.time;
//lastJumpStartHeight = transform.position.y;
this.lastJumpButtonTime = -10;
this._characterState = PickupCharacterState.Jumping;
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
// Debug.DrawRay(hit.point, hit.normal);
if (hit.moveDirection.y > 0.01f)
return;
}
public float GetSpeed()
{
return this.moveSpeed;
}
public bool IsJumping()
{
return this.jumping;
}
public bool IsGrounded()
{
return (this.collisionFlags & CollisionFlags.CollidedBelow) != 0;
}
public Vector3 GetDirection()
{
return this.moveDirection;
}
public bool IsMovingBackwards()
{
return this.movingBack;
}
public float GetLockCameraTimer()
{
return this.lockCameraTimer;
}
public bool IsMoving()
{
return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5f;
}
public bool HasJumpReachedApex()
{
return this.jumpingReachedApex;
}
public bool IsGroundedWithTimeout()
{
return this.lastGroundedTime + this.groundedTimeout > Time.time;
}
public void Reset()
{
gameObject.tag = "Player";
}
}
| |
namespace android.view
{
[global::MonoJavaBridge.JavaClass()]
public partial class Surface : java.lang.Object, android.os.Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Surface()
{
InitJNI();
}
protected Surface(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class OutOfResourcesException : java.lang.Exception
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OutOfResourcesException()
{
InitJNI();
}
protected OutOfResourcesException(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _OutOfResourcesException9031;
public OutOfResourcesException() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.Surface.OutOfResourcesException.staticClass, global::android.view.Surface.OutOfResourcesException._OutOfResourcesException9031);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _OutOfResourcesException9032;
public OutOfResourcesException(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.Surface.OutOfResourcesException.staticClass, global::android.view.Surface.OutOfResourcesException._OutOfResourcesException9032, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.Surface.OutOfResourcesException.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/Surface$OutOfResourcesException"));
global::android.view.Surface.OutOfResourcesException._OutOfResourcesException9031 = @__env.GetMethodIDNoThrow(global::android.view.Surface.OutOfResourcesException.staticClass, "<init>", "()V");
global::android.view.Surface.OutOfResourcesException._OutOfResourcesException9032 = @__env.GetMethodIDNoThrow(global::android.view.Surface.OutOfResourcesException.staticClass, "<init>", "(Ljava/lang/String;)V");
}
}
internal static global::MonoJavaBridge.MethodId _finalize9033;
protected override void finalize()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._finalize9033);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._finalize9033);
}
internal static global::MonoJavaBridge.MethodId _toString9034;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.view.Surface._toString9034)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._toString9034)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setSize9035;
public virtual void setSize(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._setSize9035, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._setSize9035, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _isValid9036;
public virtual bool isValid()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.Surface._isValid9036);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._isValid9036);
}
internal static global::MonoJavaBridge.MethodId _writeToParcel9037;
public virtual void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._writeToParcel9037, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._writeToParcel9037, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _describeContents9038;
public virtual int describeContents()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.Surface._describeContents9038);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._describeContents9038);
}
internal static global::MonoJavaBridge.MethodId _setFlags9039;
public virtual void setFlags(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._setFlags9039, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._setFlags9039, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _readFromParcel9040;
public virtual void readFromParcel(android.os.Parcel arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._readFromParcel9040, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._readFromParcel9040, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setAlpha9041;
public virtual void setAlpha(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._setAlpha9041, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._setAlpha9041, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setMatrix9042;
public virtual void setMatrix(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._setMatrix9042, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._setMatrix9042, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _show9043;
public virtual void show()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._show9043);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._show9043);
}
internal static global::MonoJavaBridge.MethodId _hide9044;
public virtual void hide()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._hide9044);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._hide9044);
}
internal static global::MonoJavaBridge.MethodId _setOrientation9045;
public static void setOrientation(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.view.Surface.staticClass, global::android.view.Surface._setOrientation9045, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _lockCanvas9046;
public virtual global::android.graphics.Canvas lockCanvas(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.view.Surface._lockCanvas9046, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Canvas;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._lockCanvas9046, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Canvas;
}
internal static global::MonoJavaBridge.MethodId _unlockCanvasAndPost9047;
public virtual void unlockCanvasAndPost(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._unlockCanvasAndPost9047, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._unlockCanvasAndPost9047, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _unlockCanvas9048;
public virtual void unlockCanvas(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._unlockCanvas9048, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._unlockCanvas9048, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setLayer9049;
public virtual void setLayer(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._setLayer9049, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._setLayer9049, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setPosition9050;
public virtual void setPosition(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._setPosition9050, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._setPosition9050, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setTransparentRegionHint9051;
public virtual void setTransparentRegionHint(android.graphics.Region arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._setTransparentRegionHint9051, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._setTransparentRegionHint9051, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _freeze9052;
public virtual void freeze()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._freeze9052);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._freeze9052);
}
internal static global::MonoJavaBridge.MethodId _unfreeze9053;
public virtual void unfreeze()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._unfreeze9053);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._unfreeze9053);
}
internal static global::MonoJavaBridge.MethodId _setFreezeTint9054;
public virtual void setFreezeTint(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.Surface._setFreezeTint9054, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.Surface.staticClass, global::android.view.Surface._setFreezeTint9054, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public static int HIDDEN
{
get
{
return 4;
}
}
public static int HARDWARE
{
get
{
return 16;
}
}
public static int GPU
{
get
{
return 40;
}
}
public static int SECURE
{
get
{
return 128;
}
}
public static int NON_PREMULTIPLIED
{
get
{
return 256;
}
}
public static int PUSH_BUFFERS
{
get
{
return 512;
}
}
public static int FX_SURFACE_NORMAL
{
get
{
return 0;
}
}
public static int FX_SURFACE_BLUR
{
get
{
return 65536;
}
}
public static int FX_SURFACE_DIM
{
get
{
return 131072;
}
}
public static int FX_SURFACE_MASK
{
get
{
return 983040;
}
}
public static int SURFACE_HIDDEN
{
get
{
return 1;
}
}
public static int SURFACE_FROZEN
{
get
{
return 2;
}
}
public static int SURACE_FROZEN
{
get
{
return 2;
}
}
public static int SURFACE_DITHER
{
get
{
return 4;
}
}
public static int SURFACE_BLUR_FREEZE
{
get
{
return 16;
}
}
public static int ROTATION_0
{
get
{
return 0;
}
}
public static int ROTATION_90
{
get
{
return 1;
}
}
public static int ROTATION_180
{
get
{
return 2;
}
}
public static int ROTATION_270
{
get
{
return 3;
}
}
internal static global::MonoJavaBridge.FieldId _CREATOR9055;
public static global::android.os.Parcelable_Creator CREATOR
{
get
{
return default(global::android.os.Parcelable_Creator);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.Surface.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/Surface"));
global::android.view.Surface._finalize9033 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "finalize", "()V");
global::android.view.Surface._toString9034 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "toString", "()Ljava/lang/String;");
global::android.view.Surface._setSize9035 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "setSize", "(II)V");
global::android.view.Surface._isValid9036 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "isValid", "()Z");
global::android.view.Surface._writeToParcel9037 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V");
global::android.view.Surface._describeContents9038 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "describeContents", "()I");
global::android.view.Surface._setFlags9039 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "setFlags", "(II)V");
global::android.view.Surface._readFromParcel9040 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V");
global::android.view.Surface._setAlpha9041 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "setAlpha", "(F)V");
global::android.view.Surface._setMatrix9042 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "setMatrix", "(FFFF)V");
global::android.view.Surface._show9043 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "show", "()V");
global::android.view.Surface._hide9044 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "hide", "()V");
global::android.view.Surface._setOrientation9045 = @__env.GetStaticMethodIDNoThrow(global::android.view.Surface.staticClass, "setOrientation", "(II)V");
global::android.view.Surface._lockCanvas9046 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "lockCanvas", "(Landroid/graphics/Rect;)Landroid/graphics/Canvas;");
global::android.view.Surface._unlockCanvasAndPost9047 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "unlockCanvasAndPost", "(Landroid/graphics/Canvas;)V");
global::android.view.Surface._unlockCanvas9048 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "unlockCanvas", "(Landroid/graphics/Canvas;)V");
global::android.view.Surface._setLayer9049 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "setLayer", "(I)V");
global::android.view.Surface._setPosition9050 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "setPosition", "(II)V");
global::android.view.Surface._setTransparentRegionHint9051 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "setTransparentRegionHint", "(Landroid/graphics/Region;)V");
global::android.view.Surface._freeze9052 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "freeze", "()V");
global::android.view.Surface._unfreeze9053 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "unfreeze", "()V");
global::android.view.Surface._setFreezeTint9054 = @__env.GetMethodIDNoThrow(global::android.view.Surface.staticClass, "setFreezeTint", "(I)V");
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using QuantConnect.Data;
using QuantConnect.Logging;
using QuantConnect.Util;
namespace QuantConnect.Brokerages
{
/// <summary>
/// Handles brokerage data subscriptions with multiple websocket connections, with optional symbol weighting
/// </summary>
public class BrokerageMultiWebSocketSubscriptionManager : EventBasedDataQueueHandlerSubscriptionManager, IDisposable
{
private readonly string _webSocketUrl;
private readonly int _maximumSymbolsPerWebSocket;
private readonly int _maximumWebSocketConnections;
private readonly Func<WebSocketClientWrapper> _webSocketFactory;
private readonly Func<IWebSocket, Symbol, bool> _subscribeFunc;
private readonly Func<IWebSocket, Symbol, bool> _unsubscribeFunc;
private readonly Action<WebSocketMessage> _messageHandler;
private readonly RateGate _connectionRateLimiter;
private readonly System.Timers.Timer _reconnectTimer;
private const int ConnectionTimeout = 30000;
private readonly object _locker = new();
private readonly List<BrokerageMultiWebSocketEntry> _webSocketEntries = new();
/// <summary>
/// Initializes a new instance of the <see cref="BrokerageMultiWebSocketSubscriptionManager"/> class
/// </summary>
/// <param name="webSocketUrl">The URL for websocket connections</param>
/// <param name="maximumSymbolsPerWebSocket">The maximum number of symbols per websocket connection</param>
/// <param name="maximumWebSocketConnections">The maximum number of websocket connections allowed (if zero, symbol weighting is disabled)</param>
/// <param name="symbolWeights">A dictionary for the symbol weights</param>
/// <param name="webSocketFactory">A function which returns a new websocket instance</param>
/// <param name="subscribeFunc">A function which subscribes a symbol</param>
/// <param name="unsubscribeFunc">A function which unsubscribes a symbol</param>
/// <param name="messageHandler">The websocket message handler</param>
/// <param name="webSocketConnectionDuration">The maximum duration of the websocket connection, TimeSpan.Zero for no duration limit</param>
/// <param name="connectionRateLimiter">The rate limiter for creating new websocket connections</param>
public BrokerageMultiWebSocketSubscriptionManager(
string webSocketUrl,
int maximumSymbolsPerWebSocket,
int maximumWebSocketConnections,
Dictionary<Symbol, int> symbolWeights,
Func<WebSocketClientWrapper> webSocketFactory,
Func<IWebSocket, Symbol, bool> subscribeFunc,
Func<IWebSocket, Symbol, bool> unsubscribeFunc,
Action<WebSocketMessage> messageHandler,
TimeSpan webSocketConnectionDuration,
RateGate connectionRateLimiter = null)
{
_webSocketUrl = webSocketUrl;
_maximumSymbolsPerWebSocket = maximumSymbolsPerWebSocket;
_maximumWebSocketConnections = maximumWebSocketConnections;
_webSocketFactory = webSocketFactory;
_subscribeFunc = subscribeFunc;
_unsubscribeFunc = unsubscribeFunc;
_messageHandler = messageHandler;
_connectionRateLimiter = connectionRateLimiter;
if (_maximumWebSocketConnections > 0)
{
// symbol weighting enabled, create all websocket instances
for (var i = 0; i < _maximumWebSocketConnections; i++)
{
var webSocket = _webSocketFactory();
webSocket.Open += OnOpen;
_webSocketEntries.Add(new BrokerageMultiWebSocketEntry(symbolWeights, webSocket));
}
}
// Some exchanges (e.g. Binance) require a daily restart for websocket connections
if (webSocketConnectionDuration != TimeSpan.Zero)
{
_reconnectTimer = new System.Timers.Timer
{
Interval = webSocketConnectionDuration.TotalMilliseconds
};
_reconnectTimer.Elapsed += (_, _) =>
{
Log.Trace("BrokerageMultiWebSocketSubscriptionManager(): Restarting websocket connections");
lock (_locker)
{
foreach (var entry in _webSocketEntries)
{
if (entry.WebSocket.IsOpen)
{
Task.Factory.StartNew(() =>
{
Log.Trace($"BrokerageMultiWebSocketSubscriptionManager(): Websocket restart - disconnect: ({entry.WebSocket.GetHashCode()})");
Disconnect(entry.WebSocket);
Log.Trace($"BrokerageMultiWebSocketSubscriptionManager(): Websocket restart - connect: ({entry.WebSocket.GetHashCode()})");
Connect(entry.WebSocket);
});
}
}
}
};
_reconnectTimer.Start();
Log.Trace($"BrokerageMultiWebSocketSubscriptionManager(): WebSocket connections will be restarted every: {webSocketConnectionDuration}");
}
}
/// <summary>
/// Subscribes to the symbols
/// </summary>
/// <param name="symbols">Symbols to subscribe</param>
/// <param name="tickType">Type of tick data</param>
protected override bool Subscribe(IEnumerable<Symbol> symbols, TickType tickType)
{
Log.Trace($"BrokerageMultiWebSocketSubscriptionManager.Subscribe(): {string.Join(",", symbols.Select(x => x.Value))}");
var success = true;
foreach (var symbol in symbols)
{
var webSocket = GetWebSocketForSymbol(symbol);
success &= _subscribeFunc(webSocket, symbol);
}
return success;
}
/// <summary>
/// Unsubscribes from the symbols
/// </summary>
/// <param name="symbols">Symbols to subscribe</param>
/// <param name="tickType">Type of tick data</param>
protected override bool Unsubscribe(IEnumerable<Symbol> symbols, TickType tickType)
{
Log.Trace($"BrokerageMultiWebSocketSubscriptionManager.Unsubscribe(): {string.Join(",", symbols.Select(x => x.Value))}");
var success = true;
foreach (var symbol in symbols)
{
var entry = GetWebSocketEntryBySymbol(symbol);
if (entry != null)
{
entry.RemoveSymbol(symbol);
success &= _unsubscribeFunc(entry.WebSocket, symbol);
}
}
return success;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_reconnectTimer?.Stop();
_reconnectTimer.DisposeSafely();
}
private BrokerageMultiWebSocketEntry GetWebSocketEntryBySymbol(Symbol symbol)
{
lock (_locker)
{
foreach (var entry in _webSocketEntries.Where(entry => entry.Contains(symbol)))
{
return entry;
}
}
return null;
}
/// <summary>
/// Adds a symbol to an existing or new websocket connection
/// </summary>
private IWebSocket GetWebSocketForSymbol(Symbol symbol)
{
BrokerageMultiWebSocketEntry entry;
lock (_locker)
{
if (_webSocketEntries.All(x => x.SymbolCount >= _maximumSymbolsPerWebSocket))
{
if (_maximumWebSocketConnections > 0)
{
throw new NotSupportedException($"Maximum symbol count reached for the current configuration [MaxSymbolsPerWebSocket={_maximumSymbolsPerWebSocket}, MaxWebSocketConnections:{_maximumWebSocketConnections}]");
}
// symbol limit reached on all, create new websocket instance
var webSocket = _webSocketFactory();
webSocket.Open += OnOpen;
_webSocketEntries.Add(new BrokerageMultiWebSocketEntry(webSocket));
}
// sort by weight ascending, taking into account the symbol limit per websocket
_webSocketEntries.Sort((x, y) =>
x.SymbolCount >= _maximumSymbolsPerWebSocket
? 1
: y.SymbolCount >= _maximumSymbolsPerWebSocket
? -1
: Math.Sign(x.TotalWeight - y.TotalWeight));
entry = _webSocketEntries.First();
}
if (!entry.WebSocket.IsOpen)
{
Connect(entry.WebSocket);
}
entry.AddSymbol(symbol);
Log.Trace($"BrokerageMultiWebSocketSubscriptionManager.GetWebSocketForSymbol(): added symbol: {symbol} to websocket: {entry.WebSocket.GetHashCode()} - Count: {entry.SymbolCount}");
return entry.WebSocket;
}
private void Connect(IWebSocket webSocket)
{
webSocket.Initialize(_webSocketUrl);
webSocket.Message += (s, e) => _messageHandler(e);
var connectedEvent = new ManualResetEvent(false);
EventHandler onOpenAction = (_, _) =>
{
connectedEvent.Set();
};
webSocket.Open += onOpenAction;
if (_connectionRateLimiter is { IsRateLimited: false })
{
_connectionRateLimiter.WaitToProceed();
}
try
{
webSocket.Connect();
if (!connectedEvent.WaitOne(ConnectionTimeout))
{
throw new TimeoutException($"BrokerageMultiWebSocketSubscriptionManager.Connect(): WebSocket connection timeout: {webSocket.GetHashCode()}");
}
}
finally
{
webSocket.Open -= onOpenAction;
connectedEvent.DisposeSafely();
}
}
private void Disconnect(IWebSocket webSocket)
{
webSocket.Close();
}
private void OnOpen(object sender, EventArgs e)
{
var webSocket = (IWebSocket)sender;
lock (_locker)
{
foreach (var entry in _webSocketEntries)
{
if (entry.WebSocket == webSocket && entry.Symbols.Count > 0)
{
Log.Trace($"BrokerageMultiWebSocketSubscriptionManager.Connect(): WebSocket opened: {webSocket.GetHashCode()} - Resubscribing existing symbols: {entry.Symbols.Count}");
Task.Factory.StartNew(() =>
{
foreach (var symbol in entry.Symbols)
{
_subscribeFunc(webSocket, symbol);
}
});
}
}
}
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.ComponentModel;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Basic Asserts on strings.
/// </summary>
// Abstract because we support syntax extension by inheriting and declaring new static members.
public abstract class StringAssert
{
#region Equals and ReferenceEquals
/// <summary>
/// DO NOT USE! Use StringAssert.AreEqualIgnoringCase(...) or Assert.AreEqual(...) instead.
/// The Equals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(object a, object b)
{
throw new InvalidOperationException("StringAssert.Equals should not be used. Use StringAssert.AreEqualIgnoringCase or Assert.AreEqual instead.");
}
/// <summary>
/// DO NOT USE!
/// The ReferenceEquals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new void ReferenceEquals(object a, object b)
{
throw new InvalidOperationException("StringAssert.ReferenceEquals should not be used.");
}
#endregion
#region Contains
/// <summary>
/// Asserts that a string is found within another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void Contains(string expected, string actual, string message, params object[] args)
{
Assert.That(actual, Does.Contain(expected), message, args);
}
/// <summary>
/// Asserts that a string is found within another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
static public void Contains(string expected, string actual)
{
Contains(expected, actual, string.Empty, null);
}
#endregion
#region DoesNotContain
/// <summary>
/// Asserts that a string is not found within another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void DoesNotContain(string expected, string actual, string message, params object[] args)
{
Assert.That(actual, Does.Not.Contain(expected), message, args );
}
/// <summary>
/// Asserts that a string is found within another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
static public void DoesNotContain(string expected, string actual)
{
DoesNotContain(expected, actual, string.Empty, null);
}
#endregion
#region StartsWith
/// <summary>
/// Asserts that a string starts with another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void StartsWith(string expected, string actual, string message, params object[] args)
{
Assert.That(actual, Does.StartWith(expected), message, args);
}
/// <summary>
/// Asserts that a string starts with another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
static public void StartsWith(string expected, string actual)
{
StartsWith(expected, actual, string.Empty, null);
}
#endregion
#region DoesNotStartWith
/// <summary>
/// Asserts that a string does not start with another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void DoesNotStartWith(string expected, string actual, string message, params object[] args)
{
Assert.That(actual, Does.Not.StartWith(expected), message, args);
}
/// <summary>
/// Asserts that a string does not start with another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
static public void DoesNotStartWith(string expected, string actual)
{
DoesNotStartWith(expected, actual, string.Empty, null);
}
#endregion
#region EndsWith
/// <summary>
/// Asserts that a string ends with another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void EndsWith(string expected, string actual, string message, params object[] args)
{
Assert.That(actual, Does.EndWith(expected), message, args);
}
/// <summary>
/// Asserts that a string ends with another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
static public void EndsWith(string expected, string actual)
{
EndsWith(expected, actual, string.Empty, null);
}
#endregion
#region DoesNotEndWith
/// <summary>
/// Asserts that a string does not end with another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void DoesNotEndWith(string expected, string actual, string message, params object[] args)
{
Assert.That(actual, Does.Not.EndWith(expected), message, args);
}
/// <summary>
/// Asserts that a string does not end with another string.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The string to be examined</param>
static public void DoesNotEndWith(string expected, string actual)
{
DoesNotEndWith(expected, actual, string.Empty, null);
}
#endregion
#region AreEqualIgnoringCase
/// <summary>
/// Asserts that two strings are equal, without regard to case.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The actual string</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void AreEqualIgnoringCase(string expected, string actual, string message, params object[] args)
{
Assert.That(actual, Is.EqualTo(expected).IgnoreCase, message, args);
}
/// <summary>
/// Asserts that two strings are equal, without regard to case.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The actual string</param>
static public void AreEqualIgnoringCase(string expected, string actual)
{
AreEqualIgnoringCase(expected, actual, string.Empty, null);
}
#endregion
#region AreNotEqualIgnoringCase
/// <summary>
/// Asserts that two strings are not equal, without regard to case.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The actual string</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void AreNotEqualIgnoringCase(string expected, string actual, string message, params object[] args)
{
Assert.That(actual, Is.Not.EqualTo(expected).IgnoreCase, message, args);
}
/// <summary>
/// Asserts that two strings are not equal, without regard to case.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The actual string</param>
static public void AreNotEqualIgnoringCase(string expected, string actual)
{
AreNotEqualIgnoringCase(expected, actual, string.Empty, null);
}
#endregion
#region IsMatch
/// <summary>
/// Asserts that a string matches an expected regular expression pattern.
/// </summary>
/// <param name="pattern">The regex pattern to be matched</param>
/// <param name="actual">The actual string</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void IsMatch(string pattern, string actual, string message, params object[] args)
{
Assert.That(actual, Does.Match(pattern), message, args);
}
/// <summary>
/// Asserts that a string matches an expected regular expression pattern.
/// </summary>
/// <param name="pattern">The regex pattern to be matched</param>
/// <param name="actual">The actual string</param>
static public void IsMatch(string pattern, string actual)
{
IsMatch(pattern, actual, string.Empty, null);
}
#endregion
#region DoesNotMatch
/// <summary>
/// Asserts that a string does not match an expected regular expression pattern.
/// </summary>
/// <param name="pattern">The regex pattern to be used</param>
/// <param name="actual">The actual string</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Arguments used in formatting the message</param>
static public void DoesNotMatch(string pattern, string actual, string message, params object[] args)
{
Assert.That(actual, Does.Not.Match(pattern), message, args);
}
/// <summary>
/// Asserts that a string does not match an expected regular expression pattern.
/// </summary>
/// <param name="pattern">The regex pattern to be used</param>
/// <param name="actual">The actual string</param>
static public void DoesNotMatch(string pattern, string actual)
{
DoesNotMatch(pattern, actual, string.Empty, null);
}
#endregion
}
}
| |
using System;
using System.Reflection;
using System.Drawing;
using System.Drawing.Design;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Runtime.Remoting.Messaging;
using System.Diagnostics;
using System.Workflow.Activities.Common;
namespace System.Workflow.Activities
{
[SRDescription(SR.WebServiceResponseActivityDescription)]
[SRCategory(SR.Standard)]
[ToolboxBitmap(typeof(WebServiceOutputActivity), "Resources.WebServiceOut.png")]
[Designer(typeof(WebServiceResponseDesigner), typeof(IDesigner))]
[ActivityValidator(typeof(WebServiceResponseValidator))]
[DefaultEvent("SendingOutput")]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class WebServiceOutputActivity : Activity, IPropertyValueProvider, IDynamicPropertyTypeProvider
{
//metadata properties
public static readonly DependencyProperty InputActivityNameProperty = DependencyProperty.Register("InputActivityName", typeof(string), typeof(WebServiceOutputActivity), new PropertyMetadata("", DependencyPropertyOptions.Metadata));
//instance properties
public static readonly DependencyProperty ParameterBindingsProperty = DependencyProperty.Register("ParameterBindings", typeof(WorkflowParameterBindingCollection), typeof(WebServiceOutputActivity), new PropertyMetadata(DependencyPropertyOptions.Metadata | DependencyPropertyOptions.ReadOnly, new Attribute[] { new BrowsableAttribute(false), new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content) }));
//event
public static readonly DependencyProperty SendingOutputEvent = DependencyProperty.Register("SendingOutput", typeof(EventHandler), typeof(WebServiceOutputActivity));
#region Constructors
public WebServiceOutputActivity()
{
//
base.SetReadOnlyPropertyValue(ParameterBindingsProperty, new WorkflowParameterBindingCollection(this));
}
public WebServiceOutputActivity(string name)
: base(name)
{
//
base.SetReadOnlyPropertyValue(ParameterBindingsProperty, new WorkflowParameterBindingCollection(this));
}
#endregion
[SRCategory(SR.Activity)]
[SRDescription(SR.ReceiveActivityNameDescription)]
[TypeConverter(typeof(PropertyValueProviderTypeConverter))]
[RefreshProperties(RefreshProperties.All)]
[MergablePropertyAttribute(false)]
[DefaultValue("")]
public string InputActivityName
{
get
{
return base.GetValue(InputActivityNameProperty) as string;
}
set
{
base.SetValue(InputActivityNameProperty, value);
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Browsable(false)]
public WorkflowParameterBindingCollection ParameterBindings
{
get
{
return base.GetValue(ParameterBindingsProperty) as WorkflowParameterBindingCollection;
}
}
[SRDescription(SR.OnBeforeResponseDescr)]
[SRCategory(SR.Handlers)]
[MergableProperty(false)]
public event EventHandler SendingOutput
{
add
{
base.AddHandler(SendingOutputEvent, value);
}
remove
{
base.RemoveHandler(SendingOutputEvent, value);
}
}
ICollection IPropertyValueProvider.GetPropertyValues(ITypeDescriptorContext context)
{
StringCollection names = new StringCollection();
if (context.PropertyDescriptor.Name == "InputActivityName")
{
foreach (Activity activity in WebServiceActivityHelpers.GetPreceedingActivities(this))
{
if (activity is WebServiceInputActivity)
{
names.Add(activity.QualifiedName);
}
}
}
return names;
}
protected override void Initialize(IServiceProvider provider)
{
if (this.Parent == null)
throw new InvalidOperationException(SR.GetString(SR.Error_MustHaveParent));
base.Initialize(provider);
}
#region Execute
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
WorkflowQueuingService queueService = executionContext.GetService<WorkflowQueuingService>();
// fire event
this.RaiseEvent(WebServiceOutputActivity.SendingOutputEvent, this, EventArgs.Empty);
WebServiceInputActivity webservicereceive = this.GetActivityByName(this.InputActivityName) as WebServiceInputActivity;
if (webservicereceive == null)
{
Activity parent = this.Parent;
while (parent != null)
{
//typically if defined inside a custom activity
string qualifiedName = parent.QualifiedName + "." + this.InputActivityName;
webservicereceive = this.GetActivityByName(qualifiedName) as WebServiceInputActivity;
if (webservicereceive != null)
break;
parent = this.Parent;
}
}
if (webservicereceive == null)
throw new InvalidOperationException(SR.GetString(SR.Error_CannotResolveWebServiceInput, this.QualifiedName, this.InputActivityName));
IComparable queueId = new EventQueueName(webservicereceive.InterfaceType, webservicereceive.MethodName, webservicereceive.QualifiedName);
MethodInfo mInfo = webservicereceive.InterfaceType.GetMethod(webservicereceive.MethodName);
if (!queueService.Exists(queueId))
{
// determine if no response is required,
// compiler did not catch it, do the runtime check and return
if (mInfo.ReturnType == typeof(void))
{
return ActivityExecutionStatus.Closed;
}
bool isresponseRequired = false;
foreach (ParameterInfo formalParameter in mInfo.GetParameters())
{
if (formalParameter.ParameterType.IsByRef || (formalParameter.IsIn && formalParameter.IsOut))
{
isresponseRequired = true;
}
}
if (isresponseRequired)
{
return ActivityExecutionStatus.Closed;
}
}
if (!queueService.Exists(queueId))
throw new InvalidOperationException(SR.GetString(SR.Error_WebServiceInputNotProcessed, webservicereceive.QualifiedName));
IMethodResponseMessage responseMessage = null;
WorkflowQueue queue = queueService.GetWorkflowQueue(queueId);
if (queue.Count != 0)
responseMessage = queue.Dequeue() as IMethodResponseMessage;
IMethodMessage message = responseMessage as IMethodMessage;
WorkflowParameterBindingCollection parameterBindings = this.ParameterBindings;
ArrayList outArgs = new ArrayList();
// populate result
if (this.ParameterBindings.Contains("(ReturnValue)"))
{
WorkflowParameterBinding retBind = this.ParameterBindings["(ReturnValue)"];
if (retBind != null)
{
outArgs.Add(retBind.Value);
}
}
foreach (ParameterInfo formalParameter in mInfo.GetParameters())
{
// update out and byref values
if (formalParameter.ParameterType.IsByRef || (formalParameter.IsIn && formalParameter.IsOut))
{
WorkflowParameterBinding binding = parameterBindings[formalParameter.Name];
outArgs.Add(binding.Value);
}
}
// reset the waiting thread
responseMessage.SendResponse(outArgs);
return ActivityExecutionStatus.Closed;
}
#endregion
#region IDynamicPropertyTypeProvider
Type IDynamicPropertyTypeProvider.GetPropertyType(IServiceProvider serviceProvider, string propertyName)
{
if (propertyName == null)
throw new ArgumentNullException("propertyName");
Dictionary<string, object> parameters = new Dictionary<string, object>();
this.GetParameterPropertyDescriptors(parameters);
if (parameters.ContainsKey(propertyName))
{
ParameterInfoBasedPropertyDescriptor descriptor = parameters[propertyName] as ParameterInfoBasedPropertyDescriptor;
if (descriptor != null)
return descriptor.ParameterType;
}
return null;
}
AccessTypes IDynamicPropertyTypeProvider.GetAccessType(IServiceProvider serviceProvider, string propertyName)
{
if (propertyName == null)
throw new ArgumentNullException("propertyName");
return AccessTypes.Read;
}
internal void GetParameterPropertyDescriptors(IDictionary properties)
{
if (((IComponent)this).Site == null)
return;
ITypeProvider typeProvider = (ITypeProvider)((IComponent)this).Site.GetService(typeof(ITypeProvider));
if (typeProvider == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
if (this.InputActivityName != null && !String.IsNullOrEmpty(this.InputActivityName.Trim()))
{
WebServiceInputActivity webServiceReceive = Helpers.ParseActivity(Helpers.GetRootActivity(this), this.InputActivityName) as WebServiceInputActivity;
if (webServiceReceive != null)
{
Type type = null;
if (webServiceReceive.InterfaceType != null)
type = typeProvider.GetType(webServiceReceive.InterfaceType.AssemblyQualifiedName);
if (type != null)
{
MethodInfo method = Helpers.GetInterfaceMethod(type, webServiceReceive.MethodName);
if (method != null && WebServiceActivityHelpers.ValidateParameterTypes(method).Count == 0)
{
List<ParameterInfo> inputParameters, outParameters;
WebServiceActivityHelpers.GetParameterInfo(method, out inputParameters, out outParameters);
foreach (ParameterInfo paramInfo in outParameters)
{
PropertyDescriptor prop = null;
if (paramInfo.Position == -1)
prop = new ParameterInfoBasedPropertyDescriptor(typeof(WebServiceOutputActivity), paramInfo, false, DesignOnlyAttribute.Yes);
else
prop = new ParameterInfoBasedPropertyDescriptor(typeof(WebServiceOutputActivity), paramInfo, true, DesignOnlyAttribute.Yes);
if (prop != null)
properties[prop.Name] = prop;
}
}
}
}
}
}
#endregion
}
internal sealed class WebServiceResponseValidator : ActivityValidator
{
public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
{
ValidationErrorCollection validationErrors = base.Validate(manager, obj);
WebServiceOutputActivity webServiceResponse = obj as WebServiceOutputActivity;
if (webServiceResponse == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(WebServiceOutputActivity).FullName), "obj");
if (Helpers.IsActivityLocked(webServiceResponse))
{
return validationErrors;
}
WebServiceInputActivity webServiceReceive = null;
if (String.IsNullOrEmpty(webServiceResponse.InputActivityName))
validationErrors.Add(ValidationError.GetNotSetValidationError("InputActivityName"));
else
{
ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));
if (typeProvider == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
bool foundMatchingReceive = false;
foreach (Activity activity in WebServiceActivityHelpers.GetPreceedingActivities(webServiceResponse))
{
if ((activity is WebServiceOutputActivity && String.Compare(((WebServiceOutputActivity)activity).InputActivityName, webServiceResponse.InputActivityName, StringComparison.Ordinal) == 0) ||
(activity is WebServiceFaultActivity && String.Compare(((WebServiceFaultActivity)activity).InputActivityName, webServiceResponse.InputActivityName, StringComparison.Ordinal) == 0))
{
if (activity is WebServiceOutputActivity)
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_DuplicateWebServiceResponseFound, activity.QualifiedName, webServiceResponse.InputActivityName), ErrorNumbers.Error_DuplicateWebServiceResponseFound));
else
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_DuplicateWebServiceFaultFound, activity.QualifiedName, webServiceResponse.InputActivityName), ErrorNumbers.Error_DuplicateWebServiceFaultFound));
return validationErrors;
}
}
foreach (Activity activity in WebServiceActivityHelpers.GetPreceedingActivities(webServiceResponse))
{
if (String.Compare(activity.QualifiedName, webServiceResponse.InputActivityName, StringComparison.Ordinal) == 0)
{
if (activity is WebServiceInputActivity)
{
webServiceReceive = activity as WebServiceInputActivity;
foundMatchingReceive = true;
}
else
{
foundMatchingReceive = false;
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotValid, webServiceResponse.InputActivityName), ErrorNumbers.Error_WebServiceReceiveNotValid));
return validationErrors;
}
break;
}
}
if (!foundMatchingReceive)
{
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotFound, webServiceResponse.InputActivityName), ErrorNumbers.Error_WebServiceReceiveNotFound));
return validationErrors;
}
else
{
Type interfaceType = null;
if (webServiceReceive.InterfaceType != null)
interfaceType = typeProvider.GetType(webServiceReceive.InterfaceType.AssemblyQualifiedName);
if (interfaceType == null)
{
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotConfigured, webServiceReceive.Name), ErrorNumbers.Error_WebServiceReceiveNotConfigured));
}
else
{
// Validate method
if (String.IsNullOrEmpty(webServiceReceive.MethodName))
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotConfigured, webServiceReceive.Name), ErrorNumbers.Error_WebServiceReceiveNotConfigured));
else
{
MethodInfo methodInfo = Helpers.GetInterfaceMethod(interfaceType, webServiceReceive.MethodName);
if (methodInfo == null)
{
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotConfigured, webServiceReceive.Name), ErrorNumbers.Error_WebServiceReceiveNotConfigured));
}
else
{
ValidationErrorCollection parameterTypeErrors = WebServiceActivityHelpers.ValidateParameterTypes(methodInfo);
if (parameterTypeErrors.Count > 0)
{
foreach (ValidationError parameterTypeError in parameterTypeErrors)
{
parameterTypeError.PropertyName = "InputActivityName";
}
validationErrors.AddRange(parameterTypeErrors);
}
else
{
List<ParameterInfo> inputParameters, outParameters;
WebServiceActivityHelpers.GetParameterInfo(methodInfo, out inputParameters, out outParameters);
if (outParameters.Count == 0)
{
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceResponseNotNeeded), ErrorNumbers.Error_WebServiceResponseNotNeeded));
}
else
{
// Check to see if all output parameters have a valid bindings.
foreach (ParameterInfo paramInfo in outParameters)
{
string paramName = paramInfo.Name;
Type paramType = paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType;
if (paramInfo.Position == -1)
paramName = "(ReturnValue)";
object paramValue = null;
if (webServiceResponse.ParameterBindings.Contains(paramName))
{
if (webServiceResponse.ParameterBindings[paramName].IsBindingSet(WorkflowParameterBinding.ValueProperty))
paramValue = webServiceResponse.ParameterBindings[paramName].GetBinding(WorkflowParameterBinding.ValueProperty);
else
paramValue = webServiceResponse.ParameterBindings[paramName].GetValue(WorkflowParameterBinding.ValueProperty);
}
if (!paramType.IsPublic || !paramType.IsSerializable)
{
ValidationError validationError = new ValidationError(SR.GetString(SR.Error_TypeNotPublicSerializable, paramName, paramType.FullName), ErrorNumbers.Error_TypeNotPublicSerializable);
validationError.PropertyName = (String.Compare(paramName, "(ReturnValue)", StringComparison.Ordinal) == 0) ? paramName : ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(webServiceReceive.GetType(), paramName);
validationErrors.Add(validationError);
}
else if (!webServiceResponse.ParameterBindings.Contains(paramName) || paramValue == null)
{
ValidationError validationError = ValidationError.GetNotSetValidationError(paramName);
validationError.PropertyName = (String.Compare(paramName, "(ReturnValue)", StringComparison.Ordinal) == 0) ? paramName : ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(webServiceReceive.GetType(), paramName);
validationErrors.Add(validationError);
}
else
{
AccessTypes access = AccessTypes.Read;
if (paramInfo.IsOut || paramInfo.IsRetval || paramInfo.Position == -1)
access = AccessTypes.Write;
ValidationErrorCollection variableErrors = ValidationHelpers.ValidateProperty(manager, webServiceResponse, paramValue,
new PropertyValidationContext(webServiceResponse.ParameterBindings[paramName], null, paramName), new BindValidationContext(paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType, access));
foreach (ValidationError variableError in variableErrors)
{
if (String.Compare(paramName, "(ReturnValue)", StringComparison.Ordinal) != 0)
variableError.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(webServiceReceive.GetType(), paramName);
}
validationErrors.AddRange(variableErrors);
}
}
if (webServiceResponse.ParameterBindings.Count > outParameters.Count)
validationErrors.Add(new ValidationError(SR.GetString(SR.Warning_AdditionalBindingsFound), ErrorNumbers.Warning_AdditionalBindingsFound, true));
}
}
}
}
}
}
}
return validationErrors;
}
}
internal static class WebServiceActivityHelpers
{
private static IEnumerable GetContainedActivities(CompositeActivity activity)
{
if (!activity.Enabled)
yield break;
foreach (Activity containedActivity in activity.Activities)
{
if (containedActivity is CompositeActivity && !Helpers.IsCustomActivity((CompositeActivity)containedActivity))
{
foreach (Activity nestedActivity in WebServiceActivityHelpers.GetContainedActivities((CompositeActivity)containedActivity))
{
if (nestedActivity.Enabled)
yield return nestedActivity;
}
}
else
{
if (containedActivity.Enabled)
yield return containedActivity;
}
}
yield break;
}
internal static IEnumerable GetPreceedingActivities(Activity startActivity)
{
return GetPreceedingActivities(startActivity, false);
}
internal static IEnumerable GetPreceedingActivities(Activity startActivity, bool crossOverLoop)
{
Activity currentActivity = null;
Stack<Activity> activityStack = new Stack<Activity>();
activityStack.Push(startActivity);
while ((currentActivity = activityStack.Pop()) != null)
{
if (currentActivity is CompositeActivity && Helpers.IsCustomActivity((CompositeActivity)currentActivity))
break;
if (currentActivity.Parent != null)
{
foreach (Activity siblingActivity in currentActivity.Parent.Activities)
{
//
if (siblingActivity == currentActivity && ((currentActivity.Parent is ParallelActivity && !Helpers.IsFrameworkActivity(currentActivity)) || (currentActivity.Parent is StateActivity && !Helpers.IsFrameworkActivity(currentActivity))))
continue;
//
if (currentActivity.Parent is IfElseActivity && !Helpers.IsFrameworkActivity(currentActivity))
continue;
//For Listen Case.
if (currentActivity.Parent is ListenActivity && !Helpers.IsFrameworkActivity(currentActivity))
continue;
// State Machine logic:
// If startActivity was in the InitialState, then
// there are no preceeding activities.
// Otherwise, we just return the parent state as
// the preceeding activity.
StateActivity currentState = currentActivity.Parent as StateActivity;
if (currentState != null)
{
StateActivity enclosingState = StateMachineHelpers.FindEnclosingState(startActivity);
//If we are at Initial State there is no preceeding above us.
if (StateMachineHelpers.IsInitialState(enclosingState))
yield break;
else
yield return currentState;
}
if (siblingActivity == currentActivity)
break;
if (siblingActivity.Enabled)
{
if (siblingActivity is CompositeActivity && !Helpers.IsCustomActivity((CompositeActivity)siblingActivity) && (crossOverLoop || !IsLoopActivity(siblingActivity)))
{
foreach (Activity containedActivity in WebServiceActivityHelpers.GetContainedActivities((CompositeActivity)siblingActivity))
yield return containedActivity;
}
else
{
yield return siblingActivity;
}
}
}
}
if (!crossOverLoop && IsLoopActivity(currentActivity.Parent))
break;
else
activityStack.Push(currentActivity.Parent);
}
yield break;
}
internal static bool IsLoopActivity(Activity activity)
{
//
if (activity is WhileActivity || activity is ReplicatorActivity || activity is ConditionedActivityGroup)
return true;
return false;
}
internal static bool IsInsideLoop(Activity webServiceActivity, Activity searchBoundary)
{
IEnumerable<String> searchBoundaryPath = GetActivityPath(searchBoundary);
IEnumerable<String> currentActivityPath = GetActivityPath(webServiceActivity);
String leastCommonParent = FindLeastCommonParent(searchBoundaryPath, currentActivityPath);
Activity currentActivity = webServiceActivity;
while (currentActivity.Parent != null && currentActivity.Parent.QualifiedName != leastCommonParent)
{
if (IsLoopActivity(currentActivity))
return true;
currentActivity = currentActivity.Parent;
}
return false;
}
static IEnumerable<String> GetActivityPath(Activity activity)
{
if (activity != null)
{
foreach (String path in GetActivityPath(activity.Parent))
yield return path;
yield return activity.QualifiedName;
}
}
static String FindLeastCommonParent(IEnumerable<String> source, IEnumerable<String> dest)
{
IEnumerator srcEnum = source.GetEnumerator();
IEnumerator destEnum = dest.GetEnumerator();
String leastCommonParent = null;
while (srcEnum.MoveNext() && destEnum.MoveNext())
{
if (srcEnum.Current.Equals(destEnum.Current))
leastCommonParent = (String)srcEnum.Current;
else
return leastCommonParent;
}
return leastCommonParent;
}
internal static IEnumerable GetSucceedingActivities(Activity startActivity)
{
Activity currentActivity = null;
Stack<Activity> activityStack = new Stack<Activity>();
activityStack.Push(startActivity);
while ((currentActivity = activityStack.Pop()) != null)
{
if (currentActivity is CompositeActivity && Helpers.IsCustomActivity((CompositeActivity)currentActivity))
break;
if (currentActivity.Parent != null)
{
bool pastCurrentActivity = false;
foreach (Activity siblingActivity in currentActivity.Parent.Activities)
{
if (siblingActivity == currentActivity)
{
pastCurrentActivity = true;
continue;
}
if (!pastCurrentActivity)
continue;
if (siblingActivity.Enabled)
{
if (siblingActivity is CompositeActivity && !Helpers.IsCustomActivity((CompositeActivity)siblingActivity))
{
foreach (Activity containedActivity in WebServiceActivityHelpers.GetContainedActivities((CompositeActivity)siblingActivity))
yield return containedActivity;
}
else
{
yield return siblingActivity;
}
}
}
}
activityStack.Push(currentActivity.Parent);
}
yield break;
}
internal static void GetParameterInfo(MethodInfo methodInfo, out List<ParameterInfo> inParameters, out List<ParameterInfo> outParameters)
{
inParameters = new List<ParameterInfo>(); outParameters = new List<ParameterInfo>();
foreach (ParameterInfo paramInfo in methodInfo.GetParameters())
{
if (paramInfo.IsOut || paramInfo.IsRetval || paramInfo.ParameterType.IsByRef)
outParameters.Add(paramInfo);
if (!paramInfo.IsOut && !paramInfo.IsRetval)
inParameters.Add(paramInfo);
}
if (methodInfo.ReturnType != typeof(void))
outParameters.Add(methodInfo.ReturnParameter);
return;
}
internal static ValidationErrorCollection ValidateParameterTypes(MethodInfo methodInfo)
{
ValidationErrorCollection validationErrors = new ValidationErrorCollection();
if (methodInfo == null)
return validationErrors;
foreach (ParameterInfo paramInfo in methodInfo.GetParameters())
{
if (paramInfo.ParameterType == null)
{
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ParameterTypeNotFound, methodInfo.Name, paramInfo.Name), ErrorNumbers.Error_ParameterTypeNotFound));
}
}
if (methodInfo.ReturnType != typeof(void) && methodInfo.ReturnParameter.ParameterType == null)
{
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ReturnTypeNotFound, methodInfo.Name), ErrorNumbers.Error_ReturnTypeNotFound));
}
return validationErrors;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using DocumentDBRestAPIClient.Areas.HelpPage.ModelDescriptions;
using DocumentDBRestAPIClient.Areas.HelpPage.Models;
namespace DocumentDBRestAPIClient.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 media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), 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 description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <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)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.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}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Aurora.Utils;
using Gma.System.MouseKeyHook.WinApi;
using Microsoft.Win32.SafeHandles;
using SharpDX.RawInput;
namespace Aurora
{
/// <summary>
/// Class for intercepting input events
/// </summary>
internal sealed class InputInterceptor : IDisposable
{
private readonly MessagePumpThread thread = new MessagePumpThread();
private readonly HookProcedure hookProcedure;
public event EventHandler<InputEventData> Input;
public InputInterceptor()
{
try
{
// Store delegate to prevent it's been garbage collected
hookProcedure = LowLevelHookProc;
thread.Start(MessagePumpInit);
}
catch
{
Dispose();
throw;
}
}
private void MessagePumpInit()
{
using (new ThreadPriorityChanger(ThreadPriority.AboveNormal,
ThreadPriorityChanger.ThreadPriority.THREAD_PRIORITY_TIME_CRITICAL))
using (var lowLevelHookHandle = HookNativeMethods.SetWindowsHookEx(HookIds.WH_KEYBOARD_LL, hookProcedure,
Process.GetCurrentProcess().MainModule.BaseAddress, 0))
{
if (lowLevelHookHandle.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
thread.EnterMessageLoop();
}
}
private IntPtr LowLevelHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
var passThrough = nCode != 0;
if (passThrough)
{
return HookNativeMethods.CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
var callbackData = new InputEventData
{
Message = (int)wParam,
Data = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct))
};
//Debug.WriteLine(
// $@"LowLevelInput {(Keys)callbackData.Data.VirtualKeyCode} {callbackData.Data.ScanCode} {callbackData.Data.Flags} {
// KeyUtils.GetDeviceKey(
// (Keys)callbackData.Data.VirtualKeyCode, callbackData.Data.ScanCode,
// ((ScanCodeFlags)callbackData.Data.Flags).HasFlag(ScanCodeFlags.E0))
// }", "InputEvents");
Input?.Invoke(this, callbackData);
if (callbackData.Intercepted)
{
return new IntPtr(-1);
}
return HookNativeMethods.CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
public sealed class InputEventData
{
public KeyboardHookStruct Data { get; set; }
public int Message { get; set; }
public bool Intercepted { get; set; }
public bool KeyUp => Message == Messages.WM_KEYUP || Message == Messages.WM_SYSKEYUP;
public bool KeyDown => Message == Messages.WM_KEYDOWN || Message == Messages.WM_SYSKEYDOWN;
}
private bool disposed;
public void Dispose()
{
if (!disposed)
{
disposed = true;
thread.Dispose();
}
}
private static class HookNativeMethods
{
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="idHook">This parameter is ignored.</param>
/// <param name="nCode">[in] Specifies the hook code passed to the current hook procedure.</param>
/// <param name="wParam">[in] Specifies the wParam value passed to the current hook procedure.</param>
/// <param name="lParam">[in] Specifies the lParam value passed to the current hook procedure.</param>
/// <returns>This value is returned by the next hook procedure in the chain.</returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr CallNextHookEx(
IntPtr idHook,
int nCode,
IntPtr wParam,
IntPtr lParam);
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events
/// are associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">
/// [in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values.
/// </param>
/// <param name="lpfn">
/// [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a
/// thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link
/// library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
/// </param>
/// <param name="hMod">
/// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
/// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
/// the current process and if the hook procedure is within the code associated with the current process.
/// </param>
/// <param name="dwThreadId">
/// [in] Specifies the identifier of the thread with which the hook procedure is to be associated.
/// If this parameter is zero, the hook procedure is associated with all existing threads running in the
/// same desktop as the calling thread.
/// </param>
/// <returns>
/// If the function succeeds, the return value is the handle to the hook procedure.
/// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
internal static extern HookProcedureHandle SetWindowsHookEx(
int idHook,
HookProcedure lpfn,
IntPtr hMod,
int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx
/// function.
/// </summary>
/// <param name="idHook">
/// [in] Handle to the hook to be removed. This parameter is a hook handle obtained by a previous call to
/// SetWindowsHookEx.
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
internal static extern int UnhookWindowsHookEx(IntPtr idHook);
}
private static class HookIds
{
/// <summary>
/// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
/// </summary>
internal const int WH_MOUSE = 7;
/// <summary>
/// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook
/// procedure.
/// </summary>
internal const int WH_KEYBOARD = 2;
/// <summary>
/// Windows NT/2000/XP/Vista/7: Installs a hook procedure that monitors low-level mouse input events.
/// </summary>
internal const int WH_MOUSE_LL = 14;
/// <summary>
/// Windows NT/2000/XP/Vista/7: Installs a hook procedure that monitors low-level keyboard input events.
/// </summary>
internal const int WH_KEYBOARD_LL = 13;
}
/// <summary>
/// The KeyboardHookStruct structure contains information about a low-level keyboard input event.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
internal struct KeyboardHookStruct
{
/// <summary>
/// Specifies a virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int VirtualKeyCode;
/// <summary>
/// Specifies a hardware scan code for the key.
/// </summary>
public int ScanCode;
/// <summary>
/// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
/// </summary>
public int Flags;
/// <summary>
/// Specifies the Time stamp for this message.
/// </summary>
public int Time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int ExtraInfo;
}
private sealed class HookProcedureHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private static bool _closing;
static HookProcedureHandle()
{
Application.ApplicationExit += (sender, e) => { _closing = true; };
}
public HookProcedureHandle()
: base(true)
{
}
protected override bool ReleaseHandle()
{
//NOTE Calling Unhook during processexit causes delay
if (_closing) return true;
return HookNativeMethods.UnhookWindowsHookEx(handle) != 0;
}
}
private static class Messages
{
//values from Winuser.h in Microsoft SDK.
/// <summary>
/// The WM_MOUSEMOVE message is posted to a window when the cursor moves.
/// </summary>
public const int WM_MOUSEMOVE = 0x200;
/// <summary>
/// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
/// </summary>
public const int WM_LBUTTONDOWN = 0x201;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
public const int WM_RBUTTONDOWN = 0x204;
/// <summary>
/// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
/// </summary>
public const int WM_MBUTTONDOWN = 0x207;
/// <summary>
/// The WM_LBUTTONUP message is posted when the user releases the left mouse button
/// </summary>
public const int WM_LBUTTONUP = 0x202;
/// <summary>
/// The WM_RBUTTONUP message is posted when the user releases the right mouse button
/// </summary>
public const int WM_RBUTTONUP = 0x205;
/// <summary>
/// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
/// </summary>
public const int WM_MBUTTONUP = 0x208;
/// <summary>
/// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button
/// </summary>
public const int WM_LBUTTONDBLCLK = 0x203;
/// <summary>
/// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button
/// </summary>
public const int WM_RBUTTONDBLCLK = 0x206;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
public const int WM_MBUTTONDBLCLK = 0x209;
/// <summary>
/// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel.
/// </summary>
public const int WM_MOUSEWHEEL = 0x020A;
/// <summary>
/// The WM_XBUTTONDOWN message is posted when the user presses the first or second X mouse
/// button.
/// </summary>
public const int WM_XBUTTONDOWN = 0x20B;
/// <summary>
/// The WM_XBUTTONUP message is posted when the user releases the first or second X mouse
/// button.
/// </summary>
public const int WM_XBUTTONUP = 0x20C;
/// <summary>
/// The WM_XBUTTONDBLCLK message is posted when the user double-clicks the first or second
/// X mouse button.
/// </summary>
/// <remarks>Only windows that have the CS_DBLCLKS style can receive WM_XBUTTONDBLCLK messages.</remarks>
public const int WM_XBUTTONDBLCLK = 0x20D;
/// <summary>
/// The WM_MOUSEHWHEEL message Sent to the active window when the mouse's horizontal scroll
/// wheel is tilted or rotated.
/// </summary>
public const int WM_MOUSEHWHEEL = 0x20E;
/// <summary>
/// The WM_KEYDOWN message is posted to the window with the keyboard focus when a non-system
/// key is pressed. A non-system key is a key that is pressed when the ALT key is not pressed.
/// </summary>
public const int WM_KEYDOWN = 0x100;
/// <summary>
/// The WM_KEYUP message is posted to the window with the keyboard focus when a non-system
/// key is released. A non-system key is a key that is pressed when the ALT key is not pressed,
/// or a keyboard key that is pressed when a window has the keyboard focus.
/// </summary>
public const int WM_KEYUP = 0x101;
/// <summary>
/// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
/// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
/// presses another key. It also occurs when no window currently has the keyboard focus;
/// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
/// receives the message can distinguish between these two contexts by checking the context
/// code in the lParam parameter.
/// </summary>
public const int WM_SYSKEYDOWN = 0x104;
/// <summary>
/// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
/// releases a key that was pressed while the ALT key was held down. It also occurs when no
/// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent
/// to the active window. The window that receives the message can distinguish between
/// these two contexts by checking the context code in the lParam parameter.
/// </summary>
public const int WM_SYSKEYUP = 0x105;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Diagnostics;
using System.Reflection;
using System.Runtime;
using System.Security;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.Workflow.Runtime;
class WorkflowOperationInvoker : IOperationInvoker
{
static object[] emptyObjectArray = new object[0];
bool canCreateInstance;
DispatchRuntime dispatchRuntime;
int inParameterCount;
bool isOneWay;
OperationDescription operationDescription;
ServiceAuthorizationManager serviceAuthorizationManager;
string staticQueueName;
MethodInfo syncMethod;
WorkflowInstanceLifetimeManagerExtension workflowInstanceLifeTimeManager;
WorkflowRuntime workflowRuntime;
public WorkflowOperationInvoker(OperationDescription operationDescription, WorkflowOperationBehavior workflowOperationBehavior,
WorkflowRuntime workflowRuntime, DispatchRuntime dispatchRuntime)
{
if (operationDescription == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operationDescription");
}
if (workflowRuntime == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workflowRuntime");
}
if (workflowOperationBehavior == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workflowOperationBehavior");
}
this.isOneWay = operationDescription.IsOneWay;
if (operationDescription.BeginMethod != null)
{
this.syncMethod = operationDescription.BeginMethod;
inParameterCount = GetFlowedInParameterCount(operationDescription.BeginMethod.GetParameters()) - 2;
}
else
{
this.syncMethod = operationDescription.SyncMethod;
inParameterCount = GetFlowedInParameterCount(operationDescription.SyncMethod.GetParameters());
}
this.operationDescription = operationDescription;
this.workflowRuntime = workflowRuntime;
this.canCreateInstance = workflowOperationBehavior.CanCreateInstance;
this.serviceAuthorizationManager = workflowOperationBehavior.ServiceAuthorizationManager;
this.dispatchRuntime = dispatchRuntime;
staticQueueName = QueueNameHelper.Create(this.syncMethod.DeclaringType, operationDescription.Name);
}
public bool CanCreateInstance
{
get { return this.canCreateInstance; }
}
public DispatchRuntime DispatchRuntime
{
get { return this.dispatchRuntime; }
}
public WorkflowInstanceLifetimeManagerExtension InstanceLifetimeManager
{
get
{
if (this.workflowInstanceLifeTimeManager == null)
{
this.workflowInstanceLifeTimeManager = this.dispatchRuntime.ChannelDispatcher.Host.Extensions.Find<WorkflowInstanceLifetimeManagerExtension>();
}
return this.workflowInstanceLifeTimeManager;
}
}
public bool IsOneWay
{
get { return this.isOneWay; }
}
public bool IsSynchronous
{
get { return false; }
}
public string StaticQueueName
{
get { return this.staticQueueName; }
}
public object[] AllocateInputs()
{
if (inParameterCount == 0)
{
return emptyObjectArray;
}
return new object[inParameterCount];
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
long beginTime = 0;
if (PerformanceCounters.PerformanceCountersEnabled)
{
PerformanceCounters.MethodCalled(this.operationDescription.Name);
try
{
if (UnsafeNativeMethods.QueryPerformanceCounter(out beginTime) == 0)
{
beginTime = -1;
}
}
catch (SecurityException exception)
{
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityException(SR.GetString("PartialTrustPerformanceCountersNotEnabled"), exception));
}
}
Authorize();
WorkflowDurableInstance durableInstance = (WorkflowDurableInstance) instance;
Fx.Assert(durableInstance.CurrentOperationInvocation == null,
"At the time WorkflowOperationInvoker.InvokeBegin is called, the WorkflowDurableInstance.CurrentOperationInvocation is expected to be null given the ConcurrencyMode.Single.");
durableInstance.CurrentOperationInvocation = new WorkflowOperationAsyncResult(
this,
durableInstance,
inputs,
callback,
state,
beginTime);
return durableInstance.CurrentOperationInvocation;
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
bool methodThrewException = false;
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
}
WorkflowDurableInstance durableInstance = (WorkflowDurableInstance) instance;
WorkflowOperationAsyncResult asyncResult = (WorkflowOperationAsyncResult) result;
Fx.Assert(durableInstance.CurrentOperationInvocation != null,
"At the time WorkflowOperationInvoker.InvokeEnd is called, the WorkflowDurableInstance.CurrentOperationInvocation is expected to be present.");
try
{
return WorkflowOperationAsyncResult.End(asyncResult, out outputs);
}
catch (FaultException)
{
methodThrewException = true;
if (PerformanceCounters.PerformanceCountersEnabled)
{
PerformanceCounters.MethodReturnedFault(this.operationDescription.Name);
}
throw;
}
catch (Exception e)
{
methodThrewException = true;
if (Fx.IsFatal(e))
{
throw;
}
if (PerformanceCounters.PerformanceCountersEnabled)
{
PerformanceCounters.MethodReturnedError(this.operationDescription.Name);
}
throw;
}
finally
{
durableInstance.CurrentOperationInvocation = null;
if (!methodThrewException)
{
if (PerformanceCounters.PerformanceCountersEnabled)
{
long currentTime = 0;
long duration = 0;
if ((asyncResult.BeginTime >= 0) && (UnsafeNativeMethods.QueryPerformanceCounter(out currentTime) != 0))
{
duration = currentTime - asyncResult.BeginTime;
}
PerformanceCounters.MethodReturnedSuccess(this.operationDescription.Name, duration);
}
}
}
}
static int GetFlowedInParameterCount(System.Reflection.ParameterInfo[] parameterInfos)
{
int inputCount = 0;
foreach (System.Reflection.ParameterInfo parameterInfo in parameterInfos)
{
if (parameterInfo.IsOut)
{
if (parameterInfo.IsIn)
{
++inputCount;
}
}
else
{
++inputCount;
}
}
return inputCount;
}
void Authorize()
{
Fx.Assert(OperationContext.Current != null, "Not in service dispatch thread");
if (this.serviceAuthorizationManager != null)
{
if (!this.serviceAuthorizationManager.CheckAccess(OperationContext.Current))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
}
}
}
}
}
| |
/*
* 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.Impl.Messaging
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Collections;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Portable;
using Apache.Ignite.Core.Impl.Resource;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Messaging;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Messaging functionality.
/// </summary>
internal class Messaging : PlatformTarget, IMessaging
{
/// <summary>
/// Opcodes.
/// </summary>
private enum Op
{
LocalListen = 1,
RemoteListen = 2,
Send = 3,
SendMulti = 4,
SendOrdered = 5,
StopLocalListen = 6,
StopRemoteListen = 7
}
/** Map from user (func+topic) -> id, needed for unsubscription. */
private readonly MultiValueDictionary<KeyValuePair<object, object>, long> _funcMap =
new MultiValueDictionary<KeyValuePair<object, object>, long>();
/** Grid */
private readonly Ignite _ignite;
/// <summary>
/// Initializes a new instance of the <see cref="Messaging" /> class.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="prj">Cluster group.</param>
public Messaging(IUnmanagedTarget target, PortableMarshaller marsh, IClusterGroup prj)
: base(target, marsh)
{
Debug.Assert(prj != null);
ClusterGroup = prj;
_ignite = (Ignite) prj.Ignite;
}
/** <inheritdoc /> */
public IClusterGroup ClusterGroup { get; private set; }
/** <inheritdoc /> */
public void Send(object message, object topic = null)
{
IgniteArgumentCheck.NotNull(message, "message");
DoOutOp((int) Op.Send, topic, message);
}
/** <inheritdoc /> */
public void Send(IEnumerable messages, object topic = null)
{
IgniteArgumentCheck.NotNull(messages, "messages");
DoOutOp((int) Op.SendMulti, writer =>
{
writer.Write(topic);
WriteEnumerable(writer, messages.OfType<object>());
});
}
/** <inheritdoc /> */
public void SendOrdered(object message, object topic = null, TimeSpan? timeout = null)
{
IgniteArgumentCheck.NotNull(message, "message");
DoOutOp((int) Op.SendOrdered, writer =>
{
writer.Write(topic);
writer.Write(message);
writer.WriteLong((long)(timeout == null ? 0 : timeout.Value.TotalMilliseconds));
});
}
/** <inheritdoc /> */
public void LocalListen<T>(IMessageFilter<T> filter, object topic = null)
{
IgniteArgumentCheck.NotNull(filter, "filter");
ResourceProcessor.Inject(filter, _ignite);
lock (_funcMap)
{
var key = GetKey(filter, topic);
MessageFilterHolder filter0 = MessageFilterHolder.CreateLocal(_ignite, filter);
var filterHnd = _ignite.HandleRegistry.Allocate(filter0);
filter0.DestroyAction = () =>
{
lock (_funcMap)
{
_funcMap.Remove(key, filterHnd);
}
};
try
{
DoOutOp((int) Op.LocalListen, writer =>
{
writer.WriteLong(filterHnd);
writer.Write(topic);
});
}
catch (Exception)
{
_ignite.HandleRegistry.Release(filterHnd);
throw;
}
_funcMap.Add(key, filterHnd);
}
}
/** <inheritdoc /> */
public void StopLocalListen<T>(IMessageFilter<T> filter, object topic = null)
{
IgniteArgumentCheck.NotNull(filter, "filter");
long filterHnd;
bool removed;
lock (_funcMap)
{
removed = _funcMap.TryRemove(GetKey(filter, topic), out filterHnd);
}
if (removed)
{
DoOutOp((int) Op.StopLocalListen, writer =>
{
writer.WriteLong(filterHnd);
writer.Write(topic);
});
}
}
/** <inheritdoc /> */
public Guid RemoteListen<T>(IMessageFilter<T> filter, object topic = null)
{
IgniteArgumentCheck.NotNull(filter, "filter");
var filter0 = MessageFilterHolder.CreateLocal(_ignite, filter);
var filterHnd = _ignite.HandleRegistry.AllocateSafe(filter0);
try
{
Guid id = Guid.Empty;
DoOutInOp((int) Op.RemoteListen, writer =>
{
writer.Write(filter0);
writer.WriteLong(filterHnd);
writer.Write(topic);
},
input =>
{
var id0 = Marshaller.StartUnmarshal(input).RawReader().ReadGuid();
Debug.Assert(IsAsync || id0.HasValue);
if (id0.HasValue)
id = id0.Value;
});
return id;
}
catch (Exception)
{
_ignite.HandleRegistry.Release(filterHnd);
throw;
}
}
/** <inheritdoc /> */
public void StopRemoteListen(Guid opId)
{
DoOutOp((int) Op.StopRemoteListen, writer =>
{
writer.WriteGuid(opId);
});
}
/** <inheritdoc /> */
public virtual IMessaging WithAsync()
{
return new MessagingAsync(UU.MessagingWithASync(Target), Marshaller, ClusterGroup);
}
/** <inheritdoc /> */
public virtual bool IsAsync
{
get { return false; }
}
/** <inheritdoc /> */
public virtual IFuture GetFuture()
{
throw IgniteUtils.GetAsyncModeDisabledException();
}
/** <inheritdoc /> */
public virtual IFuture<TResult> GetFuture<TResult>()
{
throw IgniteUtils.GetAsyncModeDisabledException();
}
/// <summary>
/// Gets the key for user-provided filter and topic.
/// </summary>
/// <param name="filter">Filter.</param>
/// <param name="topic">Topic.</param>
/// <returns>Compound dictionary key.</returns>
private static KeyValuePair<object, object> GetKey(object filter, object topic)
{
return new KeyValuePair<object, object>(filter, topic);
}
}
}
| |
// Copyright (C) 2015-2017 Luca Piccioni
//
// 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.
#pragma warning disable 618, 649
//, 1734
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using Khronos;
// ReSharper disable InheritdocConsiderUsage
// ReSharper disable SwitchStatementMissingSomeCases
// ReSharper disable RedundantIfElseBlock
namespace OpenGL
{
/// <summary>
/// Modern OpenGL bindings.
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
public partial class Gl : KhronosApi
{
#region Constructors
/// <summary>
/// Static constructor.
/// </summary>
static Gl()
{
#if !NETSTANDARD1_1
// Optional initialization
string envGlStaticInit = Environment.GetEnvironmentVariable("OPENGL_NET_GL_STATIC_INIT");
if (envGlStaticInit != null && envGlStaticInit == "NO")
return;
#endif
try {
Initialize();
} catch (NotSupportedException) {
// Fail-safe
}
}
/// <summary>
/// Initialize OpenGL namespace static environment. This method shall be called before any other classes methods.
/// </summary>
public static void Initialize()
{
if (_Initialized)
return; // Already initialized
_Initialized = true;
#if !NETSTANDARD1_1
// Optional initialization
string envGlInit = Environment.GetEnvironmentVariable("OPENGL_NET_INIT");
if (envGlInit != null && envGlInit == "NO")
return;
#endif
// Environment options
LogComment("OpenGL.Net is initializing");
// Loader function OS API GL API
// ------------------------------------------------------
// Supported platform: Windows
// wglGetProcAddress WGL GL
// wglGetProcAddress WGL GLES2+ (with WGL_create_context_es(2)?_profile_EXT)
// eglGetProcAddress EGL(Angle) GLES2+
// ------------------------------------------------------
// Supported platform: Linux
// glXGetProcAddress GLX GL
// glXGetProcAddress GLX GLES2+ (with GLX_create_context_es(2)?_profile_EXT)
// eglGetProcAddress EGL GLES2+
// ------------------------------------------------------
// Supported platform: Android
// eglGetProcAddress EGL GL
// eglGetProcAddress EGL GLES2+
try {
#if !MONODROID
// Determine whether use EGL as device context backend
if (Egl.IsAvailable) {
// Note: on Linux without GLX
if (Platform.CurrentPlatformId == Platform.Id.Linux && Glx.IsAvailable == false)
Egl.IsRequired = true;
#if !NETSTANDARD1_1
// Explict initialization
string envPlatform = Environment.GetEnvironmentVariable("OPENGL_NET_PLATFORM");
if (envPlatform != null && envPlatform == "EGL")
Egl.IsRequired = true;
#endif
}
#endif
// Create native window for getting preliminary information on desktop systems
// This instance will be used for creating contexts without explictly specify a window
NativeWindow = DeviceContext.CreateHiddenWindow();
// Create device context
using (DeviceContext windowDevice = DeviceContext.Create()) {
// Create basic OpenGL context
IntPtr renderContext = windowDevice.CreateSimpleContext();
if (renderContext == IntPtr.Zero)
throw new NotImplementedException("unable to create a simple context");
// Make contect current
if (windowDevice.MakeCurrent(renderContext) == false)
throw new InvalidOperationException("unable to make current", windowDevice.GetPlatformException());
#if !MONODROID
// Reload platform function pointers, if required
if (Egl.IsRequired == false && Platform.CurrentPlatformId == Platform.Id.WindowsNT)
Wgl.BindAPI();
#endif
// Query OpenGL informations
string glVersion = GetString(StringName.Version);
_CurrentVersion = KhronosVersion.Parse(glVersion);
// Query OpenGL extensions (current OpenGL implementation, CurrentCaps)
_CurrentExtensions = new Extensions();
_CurrentExtensions.Query();
// Query platform extensions
windowDevice.QueryPlatformExtensions();
// Query OpenGL limits
_CurrentLimits = Limits.Query(CurrentVersion, _CurrentExtensions);
// Obtain current OpenGL Shading Language version
string glslVersion = null;
switch (_CurrentVersion.Api) {
case KhronosVersion.ApiGl:
if (_CurrentVersion >= Version_200 || _CurrentExtensions.ShadingLanguage100_ARB)
glslVersion = GetString(StringName.ShadingLanguageVersion);
break;
case KhronosVersion.ApiGles2:
glslVersion = GetString(StringName.ShadingLanguageVersion);
break;
}
if (glslVersion != null)
_CurrentShadingVersion = GlslVersion.Parse(glslVersion, _CurrentVersion.Api);
// Vendor/Render information
_Vendor = GetString(StringName.Vendor);
_Renderer = GetString(StringName.Renderer);
if (EnvDebug || EnvExperimental) {
Debug.Assert(CurrentVersion != null && CurrentExtensions != null);
CheckExtensionCommands<Gl>(CurrentVersion, CurrentExtensions, EnvExperimental);
}
// Before deletion, make uncurrent
windowDevice.MakeCurrent(IntPtr.Zero);
// Detroy context
if (windowDevice.DeleteContext(renderContext) == false)
throw new InvalidOperationException("unable to delete OpenGL context");
}
LogComment("OpenGL.Net has been initialized");
} catch (Exception excepton) {
InitializationException = excepton;
LogComment($"Unable to initialize OpenGL.Net: {InitializationException}");
}
}
/// <summary>
/// Flag indicating whether <see cref="Gl"/> has been initialized.
/// </summary>
private static bool _Initialized;
/// <summary>
/// Eventual exception raised during Gl initialization.
/// </summary>
internal static Exception InitializationException;
/// <summary>
/// The native window used for initializing the OpenGL.Net state.
/// </summary>
internal static INativeWindow NativeWindow;
#endregion
#region Versions, Extensions and Limits
/// <summary>
/// OpenGL version currently implemented.
/// </summary>
/// <remarks>
/// Higher OpenGL versions versions cannot be requested to be implemented.
/// </remarks>
public static KhronosVersion CurrentVersion => _CurrentVersion;
/// <summary>
/// OpenGL version currently implemented.
/// </summary>
/// <remarks>
/// Higher OpenGL versions versions cannot be requested to be implemented.
/// </remarks>
private static KhronosVersion _CurrentVersion;
/// <summary>
/// OpenGL Shading Language version currently implemented.
/// </summary>
/// <remarks>
/// Higher OpenGL Shading Language versions cannot be requested to be implemented.
/// </remarks>
public static GlslVersion CurrentShadingVersion => _CurrentShadingVersion;
/// <summary>
/// OpenGL Shading Language version currently implemented.
/// </summary>
/// <remarks>
/// Higher OpenGL Shading Language versions cannot be requested to be implemented.
/// </remarks>
private static GlslVersion _CurrentShadingVersion;
/// <summary>
/// Get the OpenGL vendor.
/// </summary>
public static string CurrentVendor => _Vendor;
/// <summary>
/// OpenGL vendor.
/// </summary>
private static string _Vendor;
/// <summary>
/// Get the OpenGL renderer.
/// </summary>
public static string CurrentRenderer => _Renderer;
/// <summary>
/// OpenGL renderer.
/// </summary>
private static string _Renderer;
/// <summary>
/// OpenGL extension support.
/// </summary>
public static Extensions CurrentExtensions => _CurrentExtensions;
/// <summary>
/// OpenGL extension support.
/// </summary>
private static Extensions _CurrentExtensions;
/// <summary>
/// OpenGL limits.
/// </summary>
public static Limits CurrentLimits => _CurrentLimits;
/// <summary>
/// OpenGL limits.
/// </summary>
private static Limits _CurrentLimits;
#endregion
#region Versions, Extensions and Limits Stacking
/// <summary>
/// Push current extensions.
/// </summary>
public static void PushExtensions()
{
// Enqueue the original state onto the stack...
_StackExtensions.Push(_CurrentExtensions);
// ...and copy the current one
_CurrentExtensions = _CurrentExtensions.Clone();
}
/// <summary>
/// Pop current extensions.
/// </summary>
public static void PopExtensions()
{
if (_StackExtensions.Count == 0)
throw new InvalidOperationException("extensions stack underflow");
_CurrentExtensions = _StackExtensions.Pop();
}
/// <summary>
/// Stack of <see cref="Extensions"/> to emulate specific environments.
/// </summary>
private static readonly Stack<Extensions> _StackExtensions = new Stack<Extensions>();
#endregion
#region Experimental Extensions
/// <summary>
/// Check whether commands implemented by the current driver have a corresponding extension not enabled by driver.
/// </summary>
public static void EnableExperimentalExtensions()
{
CheckExtensionCommands<Gl>(CurrentVersion, CurrentExtensions, true);
}
/// <summary>
/// Check whether commands implemented by the current driver have a corresponding extension not enabled by driver.
/// </summary>
public static void EnableExperimentalExtensions(KhronosVersion version, Extensions extensions)
{
CheckExtensionCommands<Gl>(version, extensions, true);
}
#endregion
#region API Binding
/// <summary>
/// Get or set the delegate used for loading function pointers for this API.
/// </summary>
public GetAddressDelegate GetFunctionPointerDelegate
{
get { return _GetAddressDelegate; }
set { _GetAddressDelegate = value ?? GetProcAddressGLOS; }
}
/// <summary>
/// Delegate used for loading function pointers for this API.
/// </summary>
private static GetAddressDelegate _GetAddressDelegate = GetProcAddressGLOS;
/// <summary>
/// Bind the OpenGL delegates for the API corresponding to the current OpenGL context.
/// </summary>
public static void BindAPI()
{
BindAPI(QueryContextVersionCore(), CurrentExtensions);
}
/// <summary>
/// Bind the OpenGL delegates to a specific API.
/// </summary>
/// <param name="version">
/// A <see cref="KhronosVersion"/> that specifies the API to bind.
/// </param>
/// <param name="extensions">
/// A <see cref="Khronos.KhronosApi.ExtensionsCollection"/> that specifies the extensions supported. It can be null.
/// </param>
public static void BindAPI(KhronosVersion version, ExtensionsCollection extensions)
{
if (version == null)
throw new ArgumentNullException(nameof(version));
BindAPI<Gl>(GetPlatformLibrary(version), _GetAddressDelegate, version, extensions);
}
/// <summary>
/// Query the version of the current OpenGL context.
/// </summary>
/// <returns>
/// It returns the <see cref="KhronosVersion"/> specifying the actual version of the context current on this thread.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Exception thrown if no GL context is current on the calling thread.
/// </exception>
public static KhronosVersion QueryContextVersion()
{
// Parse version string (effective for detecting Desktop and ES contextes)
KhronosVersion glversion = KhronosVersion.Parse(GetString(StringName.Version));
// Context profile
if (glversion.Api == KhronosVersion.ApiGl && glversion >= Version_320) {
string glProfile;
int ctxProfile;
Get(CONTEXT_PROFILE_MASK, out ctxProfile);
if ((ctxProfile & CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0)
glProfile = KhronosVersion.ProfileCompatibility;
else if ((ctxProfile & CONTEXT_CORE_PROFILE_BIT) != 0)
glProfile = KhronosVersion.ProfileCore;
else
glProfile = KhronosVersion.ProfileCompatibility;
return new KhronosVersion(glversion, glProfile);
} else
return new KhronosVersion(glversion, KhronosVersion.ProfileCompatibility);
}
/// <summary>
/// Query the version of the current OpenGL context.
/// </summary>
/// <returns>
/// It returns the <see cref="KhronosVersion"/> specifying the actual version of the context current on this thread.
/// </returns>
private static KhronosVersion QueryContextVersionCore()
{
// Load minimal Gl functions for querying information
if (Egl.IsRequired == false) {
BindAPIFunction(Version_100, null, "glGetError");
BindAPIFunction(Version_100, null, "glGetString");
BindAPIFunction(Version_100, null, "glGetIntegerv");
} else {
// ???
BindAPIFunction(Version_320_ES, null, "glGetError");
BindAPIFunction(Version_320_ES, null, "glGetString");
BindAPIFunction(Version_320_ES, null, "glGetIntegerv");
}
return QueryContextVersion();
}
/// <summary>
/// Bind a single OpenGL delegates to a specific API.
/// </summary>
/// <param name="version">
/// A <see cref="KhronosVersion"/> that specifies the API to bind.
/// </param>
/// <param name="extensions">
/// A <see cref="Khronos.KhronosApi.ExtensionsCollection"/> that specifies the extensions supported. It can be null.
/// </param>
/// <param name="functionName">
/// A <see cref="String"/> that specifies the name of the function to bind.
/// </param>
internal static void BindAPIFunction(KhronosVersion version, ExtensionsCollection extensions, string functionName)
{
BindAPIFunction<Gl>(GetPlatformLibrary(version), functionName, _GetAddressDelegate, version, extensions);
}
/// <summary>
/// Get the library name used for loading OpenGL functions.
/// </summary>
/// <param name="version">
/// A <see cref="KhronosVersion"/> that specifies the API to bind.
/// </param>
/// <returns>
/// It returns a <see cref="String"/> that specifies the library name to be used.
/// </returns>
private static string GetPlatformLibrary(KhronosVersion version)
{
switch (version.Api) {
case KhronosVersion.ApiGl:
case KhronosVersion.ApiGlsc2:
switch (Platform.CurrentPlatformId) {
case Platform.Id.Linux:
return "libGL.so.1";
case Platform.Id.MacOS:
return "/usr/X11/lib/libGL.1.dylib";
default:
// EGL ignore library name
return Library;
}
case KhronosVersion.ApiGles1:
switch (Platform.CurrentPlatformId) {
case Platform.Id.Linux:
return "libGLESv2.so";
default:
return Egl.IsRequired ? LibraryEs : Library;
}
case KhronosVersion.ApiGles2:
switch (Platform.CurrentPlatformId) {
case Platform.Id.Linux:
return "libGLESv2.so";
default:
return Egl.IsRequired ? LibraryEs2 : Library;
}
default:
throw new NotSupportedException($"binding API for OpenGL {version} not supported");
}
}
/// <summary>
/// Default import library.
/// </summary>
internal const string Library = "opengl32.dll";
/// <summary>
/// Default import library.
/// </summary>
internal const string LibraryEs = "libGLESv1_CM.dll";
/// <summary>
/// Default import library.
/// </summary>
internal const string LibraryEs2 = "libGLESv2.dll";
#endregion
#region Error Handling
/// <summary>
/// OpenGL error checking.
/// </summary>
public static void CheckErrors()
{
ErrorCode error = GetError();
if (error != ErrorCode.NoError)
throw new GlException(error);
}
/// <summary>
/// Flush GL errors queue.
/// </summary>
private static void ClearErrors()
{
while (GetError() != ErrorCode.NoError)
// ReSharper disable once EmptyEmbeddedStatement
;
}
/// <summary>
/// OpenGL error checking.
/// </summary>
/// <param name="returnValue">
/// A <see cref="Object"/> that specifies the function returned value, if any.
/// </param>
[Conditional("GL_DEBUG")]
// ReSharper disable once UnusedParameter.Local
private static void DebugCheckErrors(object returnValue)
{
CheckErrors();
}
#endregion
#region Command Logging
/// <summary>
/// Load an API command call.
/// </summary>
/// <param name="name">
/// A <see cref="String"/> that specifies the name of the API command.
/// </param>
/// <param name="returnValue">
/// A <see cref="Object"/> that specifies the returned value, if any.
/// </param>
/// <param name="args">
/// A <see cref="T:Object[]"/> that specifies the API command arguments, if any.
/// </param>
[Conditional("GL_DEBUG")]
protected new static void LogCommand(string name, object returnValue, params object[] args)
{
if (_LogContext == null)
_LogContext = new KhronosLogContext(typeof(Gl));
RaiseLog(new KhronosLogEventArgs(_LogContext, name, args, returnValue));
}
/// <summary>
/// Context for logging enumerant names instead of numerical values.
/// </summary>
private static KhronosLogContext _LogContext;
#endregion
#region Hand-crafted Bindings
/// <summary>
/// Specify a callback to receive debugging messages from the GL.
/// </summary>
/// <param name="source">
/// A <see cref="DebugSource"/> that specify the source of the message.
/// </param>
/// <param name="type">
/// A <see cref="DebugType"/> that specify the type of the message.
/// </param>
/// <param name="id">
/// A <see cref="UInt32"/> that specify the identifier of the message.
/// </param>
/// <param name="severity">
/// A <see cref="DebugSeverity"/> that specify the severity of the message.
/// </param>
/// <param name="length">
/// The length of the message.
/// </param>
/// <param name="message">
/// A <see cref="IntPtr"/> that specify a pointer to a null-terminated ASCII C string, representing the content of the message.
/// </param>
/// <param name="userParam">
/// A <see cref="IntPtr"/> that specify the user-specified parameter.
/// </param>
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate void DebugProc(DebugSource source, DebugType type, uint id, DebugSeverity severity, int length, IntPtr message, IntPtr userParam);
/// <summary>
///
/// </summary>
/// <returns></returns>
public delegate IntPtr VulkanProc();
/// <summary>
/// specify values to record in transform feedback buffers
/// </summary>
/// <param name="program">
/// The name of the target program object.
/// </param>
/// <param name="varyings">
/// An array of zero-terminated strings specifying the names of the varying variables to use for
/// transform feedback.
/// </param>
/// <param name="bufferMode">
/// Identifies the mode used to capture the varying variables when transform feedback is active. <paramref
/// name="bufferMode"/> must be Gl.INTERLEAVED_ATTRIBS or Gl.SEPARATE_ATTRIBS.
/// </param>
/// <remarks>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Gl.INVALID_VALUE is generated if <paramref name="program"/> is not the name of a program object.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Gl.INVALID_VALUE is generated if <paramref name="bufferMode"/> is Gl.SEPARATE_ATTRIBS and the length of <paramref name="varyings"/> is
/// greater than the implementation-dependent limit Gl.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS.
/// </exception>
/// <seealso cref="Gl.BeginTransformFeedback"/>
/// <seealso cref="Gl.EndTransformFeedback"/>
/// <seealso cref="Gl.GetTransformFeedbackVarying"/>
[RequiredByFeature("GL_VERSION_3_0")]
[RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")]
[RequiredByFeature("GL_EXT_transform_feedback")]
public static void TransformFeedbackVaryings(uint program, IntPtr[] varyings, int bufferMode)
{
unsafe
{
fixed (IntPtr* p_varyings = varyings)
{
Debug.Assert(Delegates.pglTransformFeedbackVaryings_Unmanaged != null, "pglTransformFeedbackVaryings not implemented");
Delegates.pglTransformFeedbackVaryings_Unmanaged(program, varyings.Length, p_varyings, bufferMode);
LogCommand("glTransformFeedbackVaryings", null, program, varyings.Length, varyings, bufferMode);
}
}
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[SuppressUnmanagedCodeSecurity]
internal delegate void glTransformFeedbackVaryings_Unmanaged(uint program, int count, IntPtr* varyings, int bufferMode);
[RequiredByFeature("GL_VERSION_3_0", EntryPoint = "glTransformFeedbackVaryings")]
[RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2", EntryPoint = "glTransformFeedbackVaryings")]
[RequiredByFeature("GL_EXT_transform_feedback", EntryPoint = "glTransformFeedbackVaryingsEXT")]
[ThreadStatic]
internal static glTransformFeedbackVaryings_Unmanaged pglTransformFeedbackVaryings_Unmanaged;
}
#endregion
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// 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 program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the BeamSearch.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Gann Bierner and Thomas Morton
//
// 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 program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections;
using Microsoft.Extensions.Caching.Memory;
namespace OpenNLP.Tools.Util
{
/// <summary>
/// Performs k-best search over sequence. This is besed on the description in
/// Ratnaparkhi (1998), PhD diss, Univ. of Pennsylvania.
/// </summary>
public class BeamSearch
{
private const int ZeroLog = -100000;
private static readonly object[] EmptyAdditionalContext = new object[0];
internal SharpEntropy.IMaximumEntropyModel Model;
internal IBeamSearchContextGenerator ContextGenerator;
internal int Size;
private readonly MemoryCache contextsCache;
// Constructors -----------------
/// <summary>Creates new search object</summary>
/// <param name="size">The size of the beam (k)</param>
/// <param name="contextGenerator">the context generator for the model</param>
/// <param name="model">the model for assigning probabilities to the sequence outcomes</param>
public BeamSearch(int size, IBeamSearchContextGenerator contextGenerator,
SharpEntropy.IMaximumEntropyModel model) :
this(size, contextGenerator, model, 0){}
/// <summary>Creates new search object</summary>
/// <param name="size">The size of the beam (k)</param>
/// <param name="contextGenerator">the context generator for the model</param>
/// <param name="model">the model for assigning probabilities to the sequence outcomes</param>
/// <param name="cacheSizeInMegaBytes">size of the cache to use for performance</param>
public BeamSearch(int size, IBeamSearchContextGenerator contextGenerator,
SharpEntropy.IMaximumEntropyModel model, int cacheSizeInMegaBytes)
{
Size = size;
ContextGenerator = contextGenerator;
Model = model;
if (cacheSizeInMegaBytes > 0)
{
contextsCache = new MemoryCache(new MemoryCacheOptions()
{
CompactOnMemoryPressure = true,
});
}
}
// Methods ------------------------
/// <summary>
/// Returns the best sequence of outcomes based on model for this object.
/// </summary>
/// <param name="numSequences">The maximum number of sequences to be returned</param>
/// <param name="sequence">The input sequence</param>
/// <param name="additionalContext">
/// An object[] of additional context.
/// This is passed to the context generator blindly with the assumption that the context are appropiate.
/// </param>
/// <returns>An array of the top ranked sequences of outcomes</returns>
public Sequence[] BestSequences(int numSequences, string[] sequence, object[] additionalContext)
{
return BestSequences(numSequences, sequence, additionalContext, ZeroLog);
}
/// <summary>
/// Returns the best sequence of outcomes based on model for this object.</summary>
/// <param name="numSequences">The maximum number of sequences to be returned</param>
/// <param name="sequence">The input sequence</param>
/// <param name="additionalContext">
/// An object[] of additional context. This is passed to the context generator blindly with the assumption that the context are appropiate.
/// </param>
/// <param name="minSequenceScore">A lower bound on the score of a returned sequence</param>
/// <returns>An array of the top ranked sequences of outcomes</returns>
public virtual Sequence[] BestSequences(int numSequences, string[] sequence, object[] additionalContext,
double minSequenceScore)
{
int sequenceCount = sequence.Length;
var previousHeap = new ListHeap<Sequence>(Size);
var nextHeap = new ListHeap<Sequence>(Size);
var probabilities = new double[Model.OutcomeCount];//not used at the moment
previousHeap.Add(new Sequence());
if (additionalContext == null)
{
additionalContext = EmptyAdditionalContext;
}
for (int currentSequence = 0; currentSequence < sequenceCount; currentSequence++)
{
int sz = Math.Min(Size, previousHeap.Size);
int sc = 0;
for (; previousHeap.Size > 0 && sc < sz; sc++)
{
Sequence topSequence = previousHeap.Extract();
string[] outcomes = topSequence.Outcomes.ToArray();
string[] contexts = ContextGenerator.GetContext(currentSequence, sequence, outcomes,
additionalContext);
double[] scores;
if (contextsCache != null)
{
var contextKey = string.Join("|", contexts);
if (!contextsCache.TryGetValue(contextKey, out scores)){
scores = Model.Evaluate(contexts, probabilities);
contextsCache.Set(contextKey, scores);
}
}
else
{
scores = Model.Evaluate(contexts, probabilities);
}
var tempScores = new double[scores.Length];
Array.Copy(scores, tempScores, scores.Length);
Array.Sort(tempScores);
double minimum = tempScores[Math.Max(0, scores.Length - Size)];
for (int currentScore = 0; currentScore < scores.Length; currentScore++)
{
if (scores[currentScore] < minimum)
{
continue; //only advance first "size" outcomes
}
string outcomeName = Model.GetOutcomeName(currentScore);
if (ValidSequence(currentSequence, sequence, outcomes, outcomeName))
{
var newSequence = new Sequence(topSequence, outcomeName, scores[currentScore]);
if (newSequence.Score > minSequenceScore)
{
nextHeap.Add(newSequence);
}
}
}
if (nextHeap.Size == 0)
{
//if no advanced sequences, advance all valid
for (int currentScore = 0; currentScore < scores.Length; currentScore++)
{
string outcomeName = Model.GetOutcomeName(currentScore);
if (ValidSequence(currentSequence, sequence, outcomes, outcomeName))
{
var newSequence = new Sequence(topSequence, outcomeName, scores[currentScore]);
if (newSequence.Score > minSequenceScore)
{
nextHeap.Add(newSequence);
}
}
}
}
//nextHeap.Sort();
}
// make prev = next; and re-init next (we reuse existing prev set once we clear it)
previousHeap.Clear();
ListHeap<Sequence> tempHeap = previousHeap;
previousHeap = nextHeap;
nextHeap = tempHeap;
}
int topSequenceCount = Math.Min(numSequences, previousHeap.Size);
var topSequences = new Sequence[topSequenceCount];
int sequenceIndex = 0;
for (; sequenceIndex < topSequenceCount; sequenceIndex++)
{
topSequences[sequenceIndex] = (Sequence) previousHeap.Extract();
}
return topSequences;
}
/// <summary>
/// Returns the best sequence of outcomes based on model for this object.
/// </summary>
/// <param name="sequence">The input sequence</param>
/// <param name="additionalContext">
/// An object[] of additional context.
/// This is passed to the context generator blindly with the assumption that the context are appropiate.
/// </param>
/// <returns>The top ranked sequence of outcomes</returns>
public Sequence BestSequence(string[] sequence, object[] additionalContext)
{
return BestSequences(1, sequence, additionalContext, ZeroLog)[0];
}
/// <summary>
/// Determines whether a particular continuation of a sequence is valid.
/// This is used to restrict invalid sequences such as thoses used in start/continue tag-based chunking
/// or could be used to implement tag dictionary restrictions.
/// </summary>
/// <param name="index">The index in the input sequence for which the new outcome is being proposed</param>
/// <param name="inputSequence">The input sequnce</param>
/// <param name="outcomesSequence">The outcomes so far in this sequence</param>
/// <param name="outcome">The next proposed outcome for the outcomes sequence</param>
/// <returns>true if the sequence would still be valid with the new outcome, false otherwise</returns>
protected internal virtual bool ValidSequence(int index, ArrayList inputSequence, Sequence outcomesSequence,
string outcome)
{
return true;
}
/// <summary>
/// Determines whether a particular continuation of a sequence is valid.
/// This is used to restrict invalid sequences such as thoses used in start/continure tag-based chunking
/// or could be used to implement tag dictionary restrictions.
/// </summary>
/// <param name="index">The index in the input sequence for which the new outcome is being proposed</param>
/// <param name="inputSequence">The input sequnce</param>
/// <param name="outcomesSequence">The outcomes so far in this sequence</param>
/// <param name="outcome">The next proposed outcome for the outcomes sequence</param>
/// <returns>true if the sequence would still be valid with the new outcome, false otherwise</returns>
protected internal virtual bool ValidSequence(int index, object[] inputSequence, string[] outcomesSequence,
string outcome)
{
return true;
}
}
}
| |
using System;
#if V1
using IList_ServiceAttribute = System.Collections.IList;
using IList_ServiceAttributeId = System.Collections.IList;
using IEnumerable_ServiceAttribute = System.Collections.IEnumerable;
using IEnumerator_ServiceAttribute = System.Collections.IEnumerator;
#else
using IList_ServiceAttribute = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceAttribute>;
using IList_ServiceAttributeId = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceAttributeId>;
using IEnumerable_ServiceAttribute = System.Collections.Generic.IEnumerable<InTheHand.Net.Bluetooth.ServiceAttribute>;
using IEnumerator_ServiceAttribute = System.Collections.Generic.IEnumerator<InTheHand.Net.Bluetooth.ServiceAttribute>;
#endif
using System.Text;
using System.Diagnostics.CodeAnalysis;
namespace InTheHand.Net.Bluetooth
{
/// <summary>
/// Holds an SDP service record.
/// </summary>
/// -
/// <remarks>
/// <para>A Service Record is the top-level container in the Service Discovery
/// protocol/database. It contains a list of Service Attributes each identified
/// by a numerical identifier (its <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>),
/// and with its data held in a <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> has methods to access the
/// various types of data it contains.
/// </para>
/// <para>The content of the record for a particular service class is defined in the
/// profile’s specification along with the IDs it uses. The IDs for the
/// common standard services have beed defined here, as e.g.
/// <see cref="T:InTheHand.Net.Bluetooth.AttributeIds.ObexAttributeId"/>,
/// <see cref="T:InTheHand.Net.Bluetooth.AttributeIds.BasicPrintingProfileAttributeId"/>,
/// etc. The Service Discovery profile itself defines IDs, some that can be used
/// in any record <see cref="T:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId"/>,
/// and others
/// <see cref="T:InTheHand.Net.Bluetooth.AttributeIds.ServiceDiscoveryServerAttributeId"/>,
/// and <see cref="T:InTheHand.Net.Bluetooth.AttributeIds.BrowseGroupDescriptorAttributeId"/>.
/// </para>
/// <para>Note that except for the attributes in the “Universal” category
/// the IDs are <i>not</i> unique, for instance the ID is 0x0200 for both
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.ServiceDiscoveryServerAttributeId.VersionNumberList"/>
/// and <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.BrowseGroupDescriptorAttributeId.GroupId"/>
/// from <see cref="T:InTheHand.Net.Bluetooth.AttributeIds.ServiceDiscoveryServerAttributeId"/>
/// and <see cref="T:InTheHand.Net.Bluetooth.AttributeIds.BrowseGroupDescriptorAttributeId"/>
/// respectively.
/// </para>
/// <para><see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> provides the normal
/// collection-type methods properties e.g.
/// <see cref="P:InTheHand.Net.Bluetooth.ServiceRecord.Count"/>,
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.Contains(InTheHand.Net.Bluetooth.ServiceAttributeId)"/>,
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetAttributeById(InTheHand.Net.Bluetooth.ServiceAttributeId)"/>,
/// <see cref="P:InTheHand.Net.Bluetooth.ServiceRecord.Item(System.Int32)"/>
/// and <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetEnumerator"/>. So, to
/// access a particular attribute’s content get the
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/> using one of those methods
/// and then read the data from the <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.
/// See the example below.
/// </para>
///
/// <para> 
/// </para>
///
/// <para>The SDP specification defines the content of <c>TextString</c> element
/// type very loosely and they are thus very difficult to handle when reading
/// from a record.
/// The encoding of the string content is
/// not set in the specification, and thus implementors are free to use any
/// encoding they fancy, for instance ASCII, UTF-8,
/// UTF-16, Windows-1252, etc — all of which have been seen in record
/// from real devices. It would have been much more sensible to mandate UTF-8
/// as the other part of the Bluetooth protocol suite do e.g. the PIN is always
/// stored as a UTF-8 encoded string.
/// </para>
/// <para>Not only that but some of the attributes defined in the SDP specification
/// can be included in more than one ‘natural language’ version,
/// and the definition of the language and the string’s encoding
/// is not included in the element, but is
/// instead defined in a separate element and the ID of the string attribute
/// modified. Yikes!
/// </para>
/// <para> This makes it near impossible to decode the bytes in
/// a string element at parse time and create the string object then. Therefore
/// the parser creates an element containing the raw bytes from the string which
/// hopefully the user will know how to decode, passing the required encoding
/// information to one of methods on the element i.e.
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsString(InTheHand.Net.Bluetooth.LanguageBaseItem)"/>,
/// which takes a multi-language-base item from the same record (see e.g.
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetPrimaryLanguageBaseItem"/>),
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsString(System.Text.Encoding)"/>
/// which takes a .NET <see cref="T:System.Text.Encoding"/> object,
/// or <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.GetValueAsStringUtf8"/>,
/// or <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetMultiLanguageStringAttributeById(InTheHand.Net.Bluetooth.ServiceAttributeId,InTheHand.Net.Bluetooth.LanguageBaseItem)"/>
/// on the record which again takes a multi-language-base item.
/// </para>
///
/// <para> 
/// </para>
///
/// <para>A Service Record can be created from the source byte array by using the
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.CreateServiceRecordFromBytes(System.Byte[])"/>
/// method or the
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceRecordParser.Parse(System.Byte[],System.Int32,System.Int32)"/>
/// on <see cref="T:InTheHand.Net.Bluetooth.ServiceRecordParser"/>. A record
/// can also be created from a list of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>
/// passed to the constructor
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.#ctor(System.Collections.Generic.IList{InTheHand.Net.Bluetooth.ServiceAttribute})"/>.
/// </para>
///
/// <para> 
/// </para>
///
/// <para>From the SDP specification:
/// </para>
/// <list type="bullet">
/// <item><term>2.2 ServiceRecord </term><description>“…
/// a list of service attributes.”</description></item>
/// <item><term>2.3 ServiceAttribute</term><description>“…
/// two components: an attribute id and an attribute value.”</description></item>
/// <item><term>2.4 Attribute ID</term><description>“…
/// a 16-bit unsigned integer”,
/// “…represented as a data element.”</description></item>
/// <item><term>2.5 Attribute Value</term><description>“…
/// a variable length field whose meaning is determined by the attribute ID…”,
/// “…represented by a data element.”</description></item>
/// <item><term>3.1 Data Element</term><description>“…
/// a typed data representation.
/// It consists of two fields: a header field and a data field.
/// The header field, in turn, is composed of two parts: a type descriptor and a size descriptor.
/// ”</description></item>
/// <item><term>3.2 Data Element Type Descriptor </term><description>“…
/// a 5-bit type descriptor.”</description></item>
/// <item><term>3.3 Data Element Size Descriptor </term><description>“…
/// The data element size descriptor is represented as a
/// 3-bit size index followed by 0, 8, 16, or 32 bits.”</description></item>
/// </list>
/// </remarks>
/// -
/// <example>
/// <code lang="C#">
/// ServiceRecord record = ...
/// ServiceAttribute attr = record.GetAttributeById(UniversalAttributeId.ServiceRecordHandle);
/// ServiceElement element = attr.Value;
/// if(element.ElementType != ElementType.UInt32) {
/// throw new FooException("Invalid record content for ServiceRecordHandle");
/// }
/// UInt32 handle = (UInt32)element.Value;
/// </code>
/// or
/// <code lang="VB.NET">
/// Dim bppRecord As ServiceRecord = ...
/// Dim attr As ServiceAttribute = bppRecord.GetAttributeById(BasicPrintingProfileAttributeId.PrinterName)
/// Dim element As ServiceElement = attr.Value;
/// ' Spec say it is in UTF-8
/// Dim printerName As String = element.GetValueAsStringUtf8()
/// </code>
/// </example>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
#endif
public sealed class ServiceRecord : IEnumerable_ServiceAttribute
{
//--------------------------------------------------------------
private IList_ServiceAttribute m_attributes;
private byte[] m_srcBytes;
//--------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> class
/// containing no <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>s.
/// </summary>
public ServiceRecord()
{
m_attributes =
#if V1
new System.Collections.ArrayList();
#else
new System.Collections.Generic.List<ServiceAttribute>();
#endif
}
/// <overloads>
/// Initializes a new instance of the
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> class.
/// </overloads>
/// ----
/// <summary>
/// Initializes a new instance of the
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> class
/// with the specified set of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>s.
/// </summary>
/// -
/// <param name="attributesList">The list of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>
/// to add to the record,
/// as an <see cref="T:System.Collections.Generic.IList`1"/>
/// of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>.
/// </param>
public ServiceRecord(IList_ServiceAttribute attributesList)
{
if (attributesList == null) {
throw new ArgumentNullException("attributesList");
}
#if V1
foreach (Object item in attributesList) {
if (!(item is ServiceAttribute)) {
throw new ArgumentException(ErrorMsgListContainsNotAttribute);
}
}
#endif
m_attributes = attributesList;
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> class
/// with the specified set of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>s.
/// </summary>
/// -
/// <param name="attributesList">The list of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>
/// to add to the record,
/// as an array of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>.
/// </param>
public ServiceRecord(params ServiceAttribute[] attributesList)
: this((IList_ServiceAttribute)attributesList)
{ }
//--------------------------------------------------------------
/// <summary>
/// Create a <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> by parsing
/// the given array of <see cref="T:System.Byte"/>.
/// </summary>
/// -
/// <remarks>This uses the <see cref="T:InTheHand.Net.Bluetooth.ServiceRecordParser"/>
/// with its default settings.
/// See <see cref="M:InTheHand.Net.Bluetooth.ServiceRecordParser.Parse(System.Byte[],System.Int32,System.Int32)"/>
/// for more information. In particular for the errors that can result, two
/// of which are listed here.
/// </remarks>
/// -
/// <param name="recordBytes">A byte array containing the encoded Service Record.
/// </param>
/// -
/// <returns>The new <see cref="ServiceRecord"/> parsed from the byte array.
/// </returns>
/// -
/// <exception cref="T:System.Net.ProtocolViolationException">
/// The record contains invalid content.
/// </exception>
/// <exception cref="T:System.NotImplementedException">
/// The record contains an element type not supported by the parser.
/// </exception>
/// -
/// <seealso cref="M:InTheHand.Net.Bluetooth.ServiceRecordParser.Parse(System.Byte[],System.Int32,System.Int32)"/>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "bytes")]
public static ServiceRecord CreateServiceRecordFromBytes(byte[] recordBytes)
{
if (recordBytes == null) {
throw new ArgumentNullException("recordBytes");
}
ServiceRecord parsedRecord = new ServiceRecordParser().Parse(recordBytes);
//// ...and copy the result to 'this'.
//this.m_attributes = tmpRecord.m_attributes;
//this.m_srcBytes = tmpRecord.m_srcBytes;
//System.Diagnostics.Debug.Assert(this.m_srcBytes == recordBytes);
return parsedRecord;
}
//--------------------------------------------------------------
/// <summary>
/// Gets the count of attributes in the record.
/// </summary>
public Int32 Count
{
[System.Diagnostics.DebuggerStepThroughAttribute]
get { return m_attributes.Count; }
}
//[Obsolete("obsolete", true)]
//internal ServiceAttribute[] HackGetAllAttributes()
//{
// ServiceAttribute[] arr = new ServiceAttribute[Count];
// m_attributes.CopyTo(arr, 0);
// return arr;
//}
//--------------------------------------------------------------
//[CLSCompliant(false)] // use ServiceAttributeId version
//public void Add(ushort id, ServiceElement value)
//{
// Add(unchecked((ServiceAttributeId)id), value);
//}
//TODO public void Add(ServiceAttributeId id, ServiceElement value)
//{
// m_attributes.Add(new ServiceAttribute(id, value));
//}
//--------------------------------------------------------------
/// <summary>
/// Gets the attribute at the specified index.
/// </summary>
/// -
/// <param name="index">The zero-based index of the attribute to get.</param>
/// -
/// <returns>A <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/> holding
/// the attribute at the specified index.</returns>
/// -
/// <exception cref="T:System.Exception">
/// <para>index is less than 0.</para>
/// <para>-or-</para>
/// <para>index is equal to or greater than Count. </para>
/// </exception>
public ServiceAttribute this[Int32 index]
{
get { return GetAttributeByIndex(index); }
}
/// <summary>
/// Gets the attribute at the specified index.
/// </summary>
/// -
/// <param name="index">The zero-based index of the attribute to get.</param>
/// -
/// <returns>A <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/> holding
/// the attribute at the specified index.
/// Is never <see langword="null"/>.
/// </returns>
/// -
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <para>index is less than 0.</para>
/// <para>-or-</para>
/// <para>index is equal to or greater than Count. </para>
/// </exception>
public ServiceAttribute GetAttributeByIndex(Int32 index)
{
// The following will itself check the index to throw ArgumentOutOfRangeException.
ServiceAttribute attr = (ServiceAttribute)m_attributes[index]; // cast for non-Generics build.
System.Diagnostics.Debug.Assert(attr != null);
return attr;
}
//--------------------------------------------------------------
/// <overloads>
/// Determines whether a service attribute with the specified ID,
/// and optional natural language, is in the List.
/// </overloads>
/// -
/// <summary>
/// Determines whether a service attribute with the specified ID is in the List.
/// </summary>
/// -
/// <param name="id">The id of the service attribute to locate, as a
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.</param>
/// -
/// <returns>true if item is found in the record; otherwise, false. </returns>
public bool Contains(ServiceAttributeId id)
{
ServiceAttribute tmp;
return TryGetAttributeById(id, out tmp);
}
/// <overloads>
/// Returns the attribute with the given ID.
/// </overloads>
/// -
/// <summary>
/// Returns the attribute with the given ID.
/// </summary>
/// -
/// <param name="id">The Attribute Id as a <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.</param>
/// -
/// <returns>A <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/> holding
/// the attribute with the specified ID.
/// Is never <see langword="null"/>.
/// </returns>
/// -
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// There is no attribute with the given Id in the record.
/// Throws <see cref="T:System.ArgumentException"/> in NETCFv1
/// </exception>
public ServiceAttribute GetAttributeById(ServiceAttributeId id)
{
ServiceAttribute attribute;
bool found = TryGetAttributeById(id, out attribute);
if (!found) {
#if V1
throw new ArgumentException(ErrorMsgNoAttributeWithId);
#else
throw new System.Collections.Generic.KeyNotFoundException(ErrorMsgNoAttributeWithId);
#endif
}
System.Diagnostics.Debug.Assert(attribute != null);
return attribute;
}
//NODO No-(((TryGetAttributeById public? Also one with language param.)))
private bool TryGetAttributeById(ServiceAttributeId id, out ServiceAttribute attribute)
{
foreach (ServiceAttribute curAttr in m_attributes) {
if (curAttr.Id == id) {
attribute = curAttr;
System.Diagnostics.Debug.Assert(attribute != null);
return true;
}
}//for
attribute = null;
return false;
}
//--------------------------------------------------------------
/// <summary>
/// Get a list of the numerical IDs of the Attributes in the record
/// as an <see cref="T:System.Collections.Generic.IList`1"/>
/// of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.
/// </summary>
/// -
/// <remarks>
/// This method will likely be only rarely used: instead
/// one would generally want either to read a specific attribute using
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetAttributeById(InTheHand.Net.Bluetooth.ServiceAttributeId)"/>,
/// or read every attribute by using
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>'s
/// <c>IEnumerable</c> ability e.g.
/// <code lang="VB.NET">
/// For Each curAttr As ServiceAttribute In record
/// If curAttr.Id = UniversalAttributeId.ProtocolDescriptorList Then
/// ...
/// Next
/// </code>
/// <para>Note, for NETCFv1 this returns an instance of the non-Generic list
/// <see cref="T:System.Collections.IList"/>.
/// </para>
/// </remarks>
/// -
/// (Provide a pure example since NDocs makes big mess of displaying Generic types).
/// <example>
/// In C#:
/// <code lang="C#">
/// IList<ServiceAttributeId> ids = record.GetAttributeIds();
/// </code>
/// In VB.NET:
/// <code lang="VB.NET">
/// Dim ids As IList(Of ServiceAttributeId) = record.GetAttributeIds()
/// </code>
/// Or without Generics in .NET 1.1 (NETCFv1) in VB.NET:
/// <code lang="VB.NET">
/// Dim ids As IList = record.GetAttributeIds()
/// </code>
/// </example>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
#endif
public IList_ServiceAttributeId AttributeIds
{
get
{
ServiceAttributeId[] ids = new ServiceAttributeId[Count];
int i = 0;
foreach (ServiceAttribute curAttr in m_attributes) {
ids[i] = curAttr.Id;
++i;
}//for
return ids;
}
}
//--------------------------------------------------------------
/// <summary>
/// Determines whether a TextString service attribute with the specified ID
/// and natural language
/// is in the List.
/// </summary>
/// -
/// <param name="id">The id of the service attribute to locate, as a
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.</param>
/// <param name="language">
/// Which multi-language version of the string attribute to locate.
/// </param>
/// -
/// <returns>true if item is found in the record; otherwise, false. </returns>
public bool Contains(ServiceAttributeId id, LanguageBaseItem language)
{
if (language == null) { throw new ArgumentNullException("language"); }
ServiceAttributeId actualId = CreateLanguageBasedAttributeId(id, language.AttributeIdBase);
ServiceAttribute tmp;
bool found = TryGetAttributeById(actualId, out tmp);
return found && (tmp.Value.ElementType == ElementType.TextString);
}
/// <summary>
/// Returns the attribute with the given ID and natural language.
/// </summary>
/// -
/// <param name="id">The id of the service attribute to locate, as a
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.</param>
/// <param name="language">
/// Which multi-language version of the string attribute to locate.
/// </param>
/// -
/// <returns>A <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/> holding
/// the attribute with the specified ID and language.
/// Is never <see langword="null"/>.
/// </returns>
/// -
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// There is no attribute with the given Id with the given language base in the record.
/// </exception>
public ServiceAttribute GetAttributeById(ServiceAttributeId id, LanguageBaseItem language)
{
if (language == null) { throw new ArgumentNullException("language"); }
ServiceAttributeId actualId = CreateLanguageBasedAttributeId(id, language.AttributeIdBase);
ServiceAttribute attr = GetAttributeById(actualId);
System.Diagnostics.Debug.Assert(attr != null);
return attr;
}
/// <summary>
/// Create the attribute id resulting for adding the language base attribute id.
/// </summary>
/// -
/// <returns>The result <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.</returns>
/// -
/// <exception cref="T:System.OverflowException">
/// <paramref name="baseId"/> added to the <paramref name="id"/>
/// would create an id that cannot be represented as an Attribute Id.
/// </exception>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public static ServiceAttributeId CreateLanguageBasedAttributeId(ServiceAttributeId id, ServiceAttributeId baseId)
{
System.Diagnostics.Debug.Assert(typeof(short) == Enum.GetUnderlyingType(typeof(ServiceAttributeId)));
short offset = (short)baseId;
ServiceAttributeId actualId = id + offset;
// If either had the MSB set, then the result must also!
if ((actualId < 0) ^ ((id < 0) || (baseId < 0))) {
throw new OverflowException();
}
return actualId;
}
/// <summary>
/// Gets a <see cref="T:System.String"/> containing the value of the
/// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>
/// service attribute with the specified ID,
/// using the specified natural language.
/// </summary>
/// -
/// <remarks>
/// <para>As noted in the documentation on this class, string are defined in
/// an odd manner, and the multi-language strings defined in the base SDP
/// specification are defined in a very very odd manner. The natural language and the
/// string’s encoding are not included in the element, but instead are
/// defined in a separate element, and the ID of the string attribute is
/// modified. This pair is present for each natural language.
/// </para>
/// <para>This method is provided to simplify accessing those strings, given
/// the Language attribute it should use it to find and decode the string.
/// If the primary Language attribute is to be used, then use the
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetPrimaryMultiLanguageStringAttributeById(InTheHand.Net.Bluetooth.ServiceAttributeId)"/>
/// method that takes only the id parameter.
/// </para>
/// </remarks>
/// -
/// <param name="id">The id of the service attribute to locate, as a
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.</param>
/// <param name="language">
/// Which multi-language version of the string attribute to locate.
/// </param>
/// -
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// There is no attribute with the given Id in the record.
/// Throws <see cref="T:System.ArgumentException"/> in NETCFv1
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// The service element is not of type
/// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>.
/// </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">
/// If the value in the service element is not a valid string in the encoding
/// specified in the given <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>.
/// </exception>
/// -
/// <example>
/// C#:
/// <code lang="C#">
/// LanguageBaseItem primaryLang = record.GetPrimaryLanguageBaseItem();
/// if (primaryLang == null) {
/// Console.WriteLine("Primary multi-language not present, would have to guess the string's encoding.");
/// return;
/// }
/// try {
/// String sn = record.GetMultiLanguageStringAttributeById(UniversalAttributeId.ServiceName, primaryLang);
/// Console.WriteLine("ServiceName: " + sn);
/// } catch (KeyNotFoundException) {
/// Console.WriteLine("The record has no ServiceName Attribute.");
/// }
/// </code>
/// </example>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")]
#endif
public String GetMultiLanguageStringAttributeById(ServiceAttributeId id, LanguageBaseItem language)
{
if (language == null) { throw new ArgumentNullException("language"); }
ServiceAttributeId actualId = CreateLanguageBasedAttributeId(id, language.AttributeIdBase);
ServiceAttribute attr = GetAttributeById(actualId);
ServiceElement element = attr.Value;
// (No need to check that element is of type TextString, that's handled inside the following).
String str = element.GetValueAsString(language);
return str;
}
/// <summary>
/// Gets a <see cref="T:System.String"/> containing the value of the
/// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>
/// service attribute with the specified ID,
/// using the primary natural language.
/// </summary>
/// -
/// <remarks>
/// <para>As noted in the documentation on this class, string are defined in
/// an odd manner, and the multi-language strings defined in the base SDP
/// specification are defined in a very very odd manner. The natural language and the
/// string’s encoding are not included in the element, but instead are
/// defined in a separate element, and the ID of the string attribute is
/// modified. This pair is present for each natural language.
/// </para>
/// <para>This method is provided to simplify accessing those strings, it will
/// find the primary Language attribute and use it to find and decode the string.
/// And if there is no primary Language attribute, which is the case in many
/// of the records one sees on mobile phones, it will attempt the operation
/// assuming the string is encoded in UTF-8 (or ASCII).
/// </para>
/// </remarks>
/// -
/// <param name="id">The id of the service attribute to locate, as a
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.</param>
/// -
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// There is no attribute with the given Id in the record.
/// Throws <see cref="T:System.ArgumentException"/> in NETCFv1
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// The service element is not of type
/// <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.TextString"/>.
/// </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">
/// If the value in the service element is not a valid string in the encoding
/// specified in the given <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>.
/// </exception>
/// -
/// <example>
/// C#:
/// <code lang="C#">
/// try {
/// String sn = record.GetMultiLanguageStringAttributeById(UniversalAttributeId.ServiceName);
/// Console.WriteLine("ServiceName: " + sn);
/// } catch (KeyNotFoundException) {
/// Console.WriteLine("The record has no ServiceName Attribute.");
/// }
/// </code>
/// </example>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")]
#endif
public String GetPrimaryMultiLanguageStringAttributeById(ServiceAttributeId id)
{
LanguageBaseItem lang = this.GetPrimaryLanguageBaseItem();
if (lang == null) {
lang = LanguageBaseItem.CreateEnglishUtf8PrimaryLanguageItem();
}
return GetMultiLanguageStringAttributeById(id, lang);
}
//--------------------------------------------------------------
/// <summary>
/// Gets the list of LanguageBaseAttributeId items in the service record.
/// </summary>
/// -
/// <remarks>
/// See also <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetPrimaryLanguageBaseItem"/>.
/// </remarks>
/// -
/// <returns>
/// An array of <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>.
/// An array of length zero is returned if the service record contains no such attribute.
/// </returns>
/// -
/// <seealso cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetPrimaryLanguageBaseItem"/>
public LanguageBaseItem[] GetLanguageBaseList()
{
if (!Contains(InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.LanguageBaseAttributeIdList)) {
return new LanguageBaseItem[0];
}
ServiceAttribute attr = GetAttributeById(InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.LanguageBaseAttributeIdList);
if (attr.Value.ElementType != ElementType.ElementSequence) {
return new LanguageBaseItem[0];
}
LanguageBaseItem[] langList;
try {
langList = LanguageBaseItem.ParseListFromElementSequence(attr.Value);
} catch (System.Net.ProtocolViolationException) {
return new LanguageBaseItem[0];
}
return langList;
}
/// <summary>
/// Gets the primary LanguageBaseAttributeId item in the service record.
/// </summary>
/// -
/// <remarks>
/// For instance, can be used with methods
/// <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetMultiLanguageStringAttributeById(InTheHand.Net.Bluetooth.ServiceAttributeId,InTheHand.Net.Bluetooth.LanguageBaseItem)"/>,
/// and <see cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetAttributeById(InTheHand.Net.Bluetooth.ServiceAttributeId,InTheHand.Net.Bluetooth.LanguageBaseItem)"/>
/// etc. See example code in the first.
/// </remarks>
/// -
/// <returns>
/// A <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>, or null
/// if the service record contains no such attribute, or
/// no primary language item (one with Base Id 0x0100) is included.
/// </returns>
/// -
/// <seealso cref="M:InTheHand.Net.Bluetooth.ServiceRecord.GetLanguageBaseList"/>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
#endif
public LanguageBaseItem GetPrimaryLanguageBaseItem()
{
LanguageBaseItem[] list = GetLanguageBaseList();
System.Diagnostics.Debug.Assert(list != null);
const ServiceAttributeId PrimaryBaseId = (ServiceAttributeId)0x0100;
foreach (LanguageBaseItem item in list) {
if (item.AttributeIdBase == PrimaryBaseId) { return item; }
}//for
return null;
}
//--------------------------------------------------------------
#region IEnumerable<ServiceAttribute> Members
#if ! V1
/// <summary>
/// Gets an enumerator that can be used to navigate through the record's
/// list of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>s.
/// </summary>
/// -
/// <returns>An <see cref="T:System.Collections.Generic.IEnumerator`1"/>
/// of type <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>.
/// </returns>
/// -
/// <example>
/// In C#:
/// <code lang="C#">
/// foreach (ServiceAttribute curAttr in record) {
/// if (curAttr.Id == UniversalAttributeId.ProtocolDescriptorList) {
/// ...
/// }
/// </code>
/// In Visual Basic:
/// <code lang="VB.NET">
/// For Each curAttr As ServiceAttribute In record
/// If curAttr.Id = UniversalAttributeId.ProtocolDescriptorList Then
/// ...
/// Next
/// </code>
/// </example>
public IEnumerator_ServiceAttribute GetEnumerator()
{
return new ServiceRecordEnumerator(this);
}
#endif
#endregion
#region IEnumerable Members
/// <summary>
/// Gets an enumerator that can be used to navigate through the record's
/// list of <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>s.
/// </summary>
#if V1
// This is the only GetEnumerator method.
public System.Collections.IEnumerator GetEnumerator()
#else
// EIMI, to not conflict with the Generics version.
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
#endif
{
return new ServiceRecordEnumerator(this);
}
#endregion
sealed internal class ServiceRecordEnumerator : IEnumerator_ServiceAttribute
{
ServiceRecord m_record;
int m_currentIndex = -1;
internal ServiceRecordEnumerator(ServiceRecord record)
{
m_record = record;
}
#region IEnumerator<ServiceAttribute> Members
public ServiceAttribute Current //x
{
get
{
if (m_record == null) { throw new ObjectDisposedException(this.GetType().Name); }
if (m_currentIndex < 0) { throw new InvalidOperationException(); }
if (m_currentIndex >= m_record.Count) { throw new InvalidOperationException(); }
return m_record[m_currentIndex];
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
m_record = null;
}
#endregion
#region IEnumerator Members
object System.Collections.IEnumerator.Current
{
// Just call the strongly-type version.
get { return Current; }
}
public bool MoveNext()//x
{
if (m_record == null) { throw new ObjectDisposedException(this.GetType().Name); }
++m_currentIndex;
System.Diagnostics.Debug.Assert(m_currentIndex >= 0);
if (m_currentIndex >= 0 && m_currentIndex < m_record.Count) {
return true;
} else {
m_currentIndex = m_record.Count;
return false;
}
}
public void Reset()//x
{
if (m_record == null) { throw new ObjectDisposedException(this.GetType().Name); }
m_currentIndex = -1;
}
#endregion
}//2class
//--------------------------------------------------------------
internal void SetSourceBytes(byte[] recordBytes)
{
System.Diagnostics.Debug.Assert(recordBytes != null);
m_srcBytes = (byte[])recordBytes.Clone();
}
/// <summary>
/// Get the raw byte array from which the record was parsed.
/// </summary>
/// -
/// <remarks>
/// <para>A <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> can be created either by manually building new
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>s holding new
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>s, or it can be created
/// by <see cref="T:InTheHand.Net.Bluetooth.ServiceRecordParser"/> parsing an array
/// of bytes read from another machine by e.g.
/// <see cref="M:InTheHand.Net.Sockets.BluetoothDeviceInfo.GetServiceRecords(System.Guid)"/>.
/// In that case this method returns that source byte array.
/// </para>
/// <para>To creates a Service Record byte array from the contained
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/>s use
/// <see cref="ToByteArray"/> or <see cref="T:InTheHand.Net.Bluetooth.ServiceRecordCreator"/>.
/// </para>
/// </remarks>
/// -
/// <value>
/// An array of <see cref="T:System.Byte"/>, or <see langword="null"/> if
/// the record was not created by parsing a raw record.
/// </value>
/// -
/// <seealso cref="ToByteArray"/>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
#endif
public byte[] SourceBytes
{
get
{
return m_srcBytes;
}
}
/// <summary>
/// Return the byte array representing the service record.
/// </summary>
/// -
/// <remarks>The byte array content is created dynamically from the
/// <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> instance using
/// the <see cref="T:InTheHand.Net.Bluetooth.ServiceRecordCreator"/> class.
/// </remarks>
/// -
/// <returns>The result as an array of <see cref="T:System.Byte"/>.
/// </returns>
/// -
/// <seealso cref="SourceBytes"/>
public byte[] ToByteArray()
{
byte[] createdFromParsedRecord = new ServiceRecordCreator().CreateServiceRecord(this);
return createdFromParsedRecord;
}
//--------------------------------------------------------------
//internal static void Arrays_Equal(byte[] x, byte[] y) // as NETCFv1 not Generic <T>
//{
// if (x.Length != y.Length) {
// throw new InvalidOperationException("diff lengs!!!");
// }
// for (int i = 0; i < x.Length; ++i) {
// if (!x[i].Equals(y[i])) {
// throw new InvalidOperationException(String.Format(System.Globalization.CultureInfo.InvariantCulture,
// "diff at {0}, x: 0x{1:X2}, y: 0x{2:X2} !!!", i, x[i], y[i]));
// }
// }
//}
//--------------------------------------------------------------
/// <exclude/>
public const String ErrorMsgNotSeq = "LanguageBaseList attribute not of type ElementSequence.";
/// <exclude/>
public const string ErrorMsgNoAttributeWithId
= "No Service Attribute with that ID.";
/// <exclude/>
public const string ErrorMsgListContainsNotAttribute
= "The list contains a element which is not a ServiceAttribute.";
}//class
}
| |
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace MooGet {
/// <summary>Represents a Moofile file which specifies NuGet package dependencies for a project or solution</summary>
public partial class Moofile {
string _text;
public Moofile() {}
public Moofile(string moofilePath) {
Path = moofilePath;
Text = Util.ReadFile(moofilePath);
}
public string Path { get; set; }
public Dictionary<string, string> Configuration { get; set; }
public List<Dependency> GlobalDependencies { get; set; }
public List<Group> Groups { get; set; }
public Group this[string name] {
get { return Groups.FirstOrDefault(g => g.Name == name); }
}
public string Text {
get { return _text; }
set {
_text = value;
Parse();
}
}
public string FullPath {
get { return System.IO.Path.GetFullPath(Path); }
}
public string Directory {
get { return System.IO.Path.GetDirectoryName(FullPath); }
}
public List<string> RelativeDirectories {
get { return new List<string>(System.IO.Directory.GetDirectories(Directory)); }
}
public List<string> RelativeDirectoryNames {
get { return RelativeDirectories.Select(dir => System.IO.Path.GetFileName(dir)).ToList(); }
}
// TODO this should be as simple as getting all Configuration where IsDirectory is true. Refactor Configuration to Configurations ... a List<Configuration>
/// <summary>Returns all Configuration items that have the same name as a directory in the Moofile's directory</summary>
public Dictionary<string, string> DirectoryConfigurations {
get { return Configuration.Where(config => RelativeDirectoryNames.Contains(config.Key)).ToDictionary(x => x.Key, x => x.Value); }
}
public string[] GetFiles(string dirname, string matcher) {
var fullDirname = System.IO.Path.Combine(Directory, dirname);
return System.IO.Directory.GetFiles(fullDirname, matcher, SearchOption.AllDirectories);
}
public List<Dependency> DependenciesFor(string key) {
var dependencies = new List<Dependency>();
GlobalDependencies.ForEach(d => dependencies.Add(d));
var group = Groups.FirstOrDefault(g => g.Name == key);
if (group != null)
group.Dependencies.ForEach(d => dependencies.Add(d));
return dependencies;
}
public object Build() {
var response = new StringBuilder();
foreach (var dirConfig in DirectoryConfigurations) {
var dirname = dirConfig.Key;
var arguments = dirConfig.Value.Trim().Replace("\n", " ").Trim();
var csharpFiles = GetFiles(dirname, "*.cs");
var command = string.Format("gmcs {0} {1}", arguments, string.Join(" ", csharpFiles));
string outputDir = null;
var output = Regex.Match(command, @"[-\/]out:([^\s]+)");
if (output != null) {
var outFile = output.Groups[1].ToString().Replace("\\", "/"); // switch the other way on Windows?
command = command.Replace(output.ToString(), "/out:" + outFile);
outputDir = System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(outFile));
System.IO.Directory.CreateDirectory(outputDir);
}
var dllReferences = DependenciesFor(dirConfig.Key).
Where(d => d.Text.ToLower().EndsWith(".dll")).
Select(d => System.IO.Path.GetFullPath(d.Text)).ToList();
// NOTE ... i think you should have to run 'moo install' to support .nupkg references ...
var nupkgReferences = DependenciesFor(dirConfig.Key).
Where(d => d.Text.ToLower().EndsWith(".nupkg")).
Select(d => new Nupkg(System.IO.Path.GetFullPath(d.Text))).ToList();
var localPackageReferences = new List<IPackage>();
foreach (var nupkg in nupkgReferences) {
var package = Moo.Dir.Push(nupkg) as IPackage;
response.Line("Installed {0}", package);
localPackageReferences.Add(package);
}
// add -r references for dlls
dllReferences.ForEach(dll => command += " -r:" + dll);
// add -r references for LocalPackage libraries
foreach (var package in localPackageReferences)
foreach (var dll in (package as MooDirPackage).Libraries)
command += " -r:" + System.IO.Path.GetFullPath(dll);
response.Line(command);
response.Line(Util.RunCommand(command, Directory).Trim());
// Copy dlls to output directory
dllReferences.ForEach(dll => {
var copyTo = System.IO.Path.Combine(outputDir, System.IO.Path.GetFileName(dll));
response.Line("cp {0} {1}", dll, copyTo);
File.Copy(dll, copyTo);
});
foreach (var package in localPackageReferences)
foreach (var dll in (package as MooDirPackage).Libraries) {
var dllPath = System.IO.Path.GetFullPath(dll);
var copyTo = System.IO.Path.Combine(outputDir, System.IO.Path.GetFileName(dllPath));
response.Line("cp {0} {1}", dllPath, copyTo);
File.Copy(dllPath, copyTo);
}
}
return response;
}
public string Inspect() {
var response = new StringBuilder();
if (Configuration.Any())
response.Line("[Configuration]");
foreach (var config in Configuration)
response.Indent("{0}: {1}", config.Key, config.Value.Trim().Replace("\n", " "));
if (GlobalDependencies.Any())
response.Line("[Global Dependencies]");
foreach (var dep in GlobalDependencies)
response.Indent(dep.Text.Trim());
foreach (var group in Groups) {
response.Line("[{0}]", group.Name);
foreach (var dep in group.Dependencies)
response.Indent(dep.Text.Trim());
}
return response.ToString();
}
// TODO extract method or extract class. this is one big procedural thing ... is there a nice way to clean this up. let's atLEAST refactor each for loop into a method with a sole purpose
void Parse() {
Groups = new List<Group>();
GlobalDependencies = new List<Dependency>();
Configuration = new Dictionary<string, string>();
var lines = Text.Trim().Split('\n');
var sections = new Dictionary<string, List<string>>(); // track indentations
sections["global"] = new List<string>();
string currentGroup = null;
for (int i = 0; i < lines.Length; i++) {
var line = lines[i];
var nextLine = ((i+1) >= lines.Length) ? null : lines[i + 1];
// ignore empty lines
if (line.Trim().Length == 0)
continue;
// ignore comments
if (line.StartsWith("#") || line.StartsWith("//"))
continue;
if (LineIndented(line))
sections[currentGroup].Add(line.Trim());
else if (LineIndented(nextLine)) {
currentGroup = line.Trim();
sections[currentGroup] = new List<string>();
} else
sections["global"].Add(line);
}
// before adding sections as Configuration, Dependencies, or GlobalDependencies
// find everything key with a comma and split it up so src, spec: foo turns into src: foo and spec: foo
foreach (var section in new Dictionary<string, List<string>>(sections)) {
// For sections that have commas, we split up the section name and we take all of the dependencies
// and add them to ALL of the groups specified
if (section.Key.Contains(",")) {
if (section.Key.Contains(":")) {
foreach (var part in section.Key.Split(',')) {
var key = part.Replace(":", "").Trim();
if (! Configuration.ContainsKey(key)) Configuration[key] = "";
foreach (var value in section.Value)
Configuration[key] += "\n" + value;
}
sections.Remove(section.Key);
} else {
foreach (var part in section.Key.Split(',')) {
var key = part.Trim();
var group = Groups.FirstOrDefault(g => g.Name == key);
if (group == null) {
group = new Group(key);
Groups.Add(group);
}
foreach (var value in section.Value)
group.Dependencies.Add(new Dependency(value){ Moofile = this });
}
sections.Remove(section.Key); // we processed this into groups ourselves
}
}
// For the global section we look at all of the global values and, if they have a comma and a colon,
// we add the configuration information to the configuration for all of the comma separated values
if (section.Key == "global") {
foreach (var item in section.Value) {
if (item.Contains(",")) {
// Configuration
if (item.Contains(":")) {
// if there is a :, we only split this up if the , is BEFORE the first :
// That's because the comma is part of the VALUE of this configuration
var colonIndex = item.IndexOf(":");
var commaIndex = item.IndexOf(",");
if (colonIndex > -1 && commaIndex > colonIndex) continue;
// Everything after the colon is the value
var value = item.Substring(colonIndex + 1);
// take all of the parts before the colon and set their configuration values
foreach (var part in item.Substring(0, colonIndex).Split(',')) {
var key = part.Trim();
if (! Configuration.ContainsKey(key)) Configuration[key] = "";
Configuration[key] += "\n" + value;
}
} else {
Console.WriteLine("Global section has commas but no colon. I don't understand: {0}", item);
}
}
}
}
}
// Process sections and import them into GlobalDependencies, Groups, and Configuration
foreach (var section in sections) {
if (section.Key == "global") {
foreach (var dependencyText in section.Value) {
if (dependencyText.Contains(":"))
AddToConfigurationFromString(Configuration, dependencyText);
else
GlobalDependencies.Add(new Dependency(dependencyText){ Moofile = this });
}
} else {
if (section.Key.Contains(":")) {
Configuration.Add(section.Key.Replace(":", ""), string.Join("\n", section.Value.ToArray()));
} else {
var group = Groups.FirstOrDefault(g => g.Name == section.Key);
if (group == null) {
group = new Group(section.Key);
Groups.Add(group);
}
foreach (var dependencyText in section.Value)
group.Dependencies.Add(new Dependency(dependencyText){ Moofile = this });
}
}
}
}
// takes foo: bar and sets config["foo"] += "\n" + "bar"
static void AddToConfigurationFromString(Dictionary<string, string> config, string text) {
var parts = new List<string>(text.Split(':'));
var key = parts.First();
parts.RemoveAt(0);
var value = string.Join(":", parts.ToArray());
if (! config.ContainsKey(key)) config[key] = "";
config[key] += "\n" + value;
}
static bool LineIndented(string line) {
if (line == null) return false;
return line.StartsWith(" ") || line.StartsWith("\t");
}
}
}
| |
//
// SailboatComputer - CompassSensor.cs
//
// Created 01 - 2013
//
// Alex Wetmore
using System;
using System.IO;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using trig = System.Math;
namespace SailboatComputer
{
/// <summary>
/// This is an I2C sensor to read heading using the LSM303DLHC chip.
/// I got this working by looking at the the application notes found here:
/// http://www.pololu.com/file/download/LSM303DLH-compass-app-note.pdf?file_id=0J434
/// and the sample Arduino code from these sources:
/// https://github.com/pololu/LSM303 (most useful)
/// https://github.com/adafruit/Adafruit_LSM303 (copied constants)
/// Basic usage:
/// I2CDevice m_i2c = new I2CDevice(null);
/// CompassSensor sensor = new CompassSensor(m_i2c);
/// double roll;
/// double pitch;
/// double heading;
/// heading = sensor.ReadAngleAndHeading(out roll, out pitch);
/// Use CompassSensor.Calibrate() to get calibration parameters and save
/// them into the m_magMin and m_magMax vectors in this class.
/// </summary>
public class CompassSensor
{
private const int TransactionTimeout = 500; // ms
private const int ClockRateKHz = 100;
private const byte AccelAddress = 0x19;
private const byte MagAddress = 0x1e;
private readonly I2CDevice.Configuration m_accelConfig;
private readonly I2CDevice m_i2c;
private readonly I2CDevice.Configuration m_magConfig;
private readonly Int16[] m_recentHeadings = new Int16[5];
private int m_recentHeadingIndex;
private vector m_magMax = new vector(629, 594, 719);
private vector m_magMin = new vector(-666, -713, -565);
/// <summary>
/// Initialize the CompassSensor
/// </summary>
/// <param name="i2c">single I2CDevice being used on the Netduino</param>
public CompassSensor(I2CDevice i2c)
{
this.m_accelConfig = new I2CDevice.Configuration(AccelAddress, ClockRateKHz);
this.m_magConfig = new I2CDevice.Configuration(MagAddress, ClockRateKHz);
this.m_i2c = i2c;
WriteRegister(this.m_accelConfig, (byte) AccelRegisters.LSM303_REGISTER_ACCEL_CTRL_REG1_A, 0x27);
WriteRegister(this.m_accelConfig, (byte) AccelRegisters.LSM303_REGISTER_ACCEL_CTRL_REG4_A, 0x40 | 0x80 | 0x08);
WriteRegister(this.m_magConfig, (byte) MagRegisters.LSM303_REGISTER_MAG_CRA_REG_M, 0x14);
WriteRegister(this.m_magConfig, (byte) MagRegisters.LSM303_REGISTER_MAG_MR_REG_M, 0x00);
}
/// <summary>
/// Read the heading and angle data from the device.
/// These formulas come from:
/// http://www.pololu.com/file/download/LSM303DLH-compass-app-note.pdf?file_id=0J434
/// </summary>
/// <param name="roll">The device's roll measured in degrees</param>
/// <param name="pitch">The device's pitch measured in degrees</param>
/// <returns>
/// The compass heading rounded to the nearest integer. Zero is
/// aligned with the X-> on the top of the Adafruit board.
/// </returns>
public Int16 ReadHeading(out double roll, out double pitch)
{
intvector accRaw = ReadRawAcc();
// compute roll and pitch, results are in radians
pitch = trig.Asin((double) accRaw.x / 1024);
roll = trig.Asin(((double) accRaw.y / 1024) / System.Math.Cos(pitch));
intvector magRaw = ReadRawMag();
vector mag;
// normalize mag output using calibration results.
// This corresponds to M1 in the application notes
mag.x = ((magRaw.x - this.m_magMin.x) / (this.m_magMax.x - this.m_magMin.x) * 2 - 1.0);
mag.y = ((magRaw.y - this.m_magMin.y) / (this.m_magMax.y - this.m_magMin.y) * 2 - 1.0);
mag.z = ((magRaw.z - this.m_magMin.z) / (this.m_magMax.z - this.m_magMin.z) * 2 - 1.0);
// tilt compenstation. magtilt corresponds to M2 in the
// application notes. These are from equation 12 in the
// app notes
vector magtilt;
double cospitch = trig.Cos(pitch);
double sinpitch = trig.Sin(pitch);
double cosroll = trig.Cos(roll);
double sinroll = trig.Sin(roll);
magtilt.x = mag.x * cospitch + mag.z * sinpitch;
magtilt.y = mag.x * sinroll * sinpitch + mag.y * cosroll - mag.z * sinroll * cospitch;
magtilt.z = -mag.x * cosroll * sinpitch + mag.y * sinroll + mag.z * cosroll * cospitch;
// compute heading. This is equation 13 in the app notes
Int16 heading;
double rawheading = trig.Atan(magtilt.y / magtilt.x) * 180 / trig.PI;
if (magtilt.x == 0 && magtilt.y < 0)
{
heading = 90;
}
else if (magtilt.y == 0 && magtilt.y >= 0)
{
heading = 270;
}
else if (magtilt.x < 0)
{
heading = (Int16) (rawheading + 180);
}
else if (magtilt.x > 0 && magtilt.y < 0)
{
heading = (Int16) (rawheading + 360);
}
else
{
heading = (Int16) rawheading;
}
// convert pitch and roll to degrees
pitch *= (180 / trig.PI);
roll *= (180 / trig.PI);
this.m_recentHeadings[this.m_recentHeadingIndex] = heading;
this.m_recentHeadingIndex = (this.m_recentHeadingIndex + 1) % this.m_recentHeadings.Length;
// double the most recent value as a weighting
int dampenedHeading = heading;
for (int i = 0; i < this.m_recentHeadings.Length; i++)
{
dampenedHeading += this.m_recentHeadings[i];
}
dampenedHeading /= (this.m_recentHeadings.Length + 1);
//return (Int16) dampenedHeading;
return heading;
}
/// <summary>
/// Calibration function. Run this on your device and spin the device
/// in all possible orientations. When done note the most recent
/// output in the Debug console.
/// </summary>
public void Calibrate()
{
intvector min;
intvector max;
intvector oldmin;
intvector oldmax;
intvector raw;
min.x = Int16.MaxValue;
min.y = Int16.MaxValue;
min.z = Int16.MaxValue;
max.x = Int16.MinValue;
max.y = Int16.MinValue;
max.z = Int16.MinValue;
while (true)
{
oldmin = min;
oldmax = max;
raw = ReadRawMag();
min.x = (Int16) System.Math.Min(min.x, raw.x);
min.y = (Int16) System.Math.Min(min.y, raw.y);
min.z = (Int16) System.Math.Min(min.z, raw.z);
max.x = (Int16) System.Math.Max(max.x, raw.x);
max.y = (Int16) System.Math.Max(max.y, raw.y);
max.z = (Int16) System.Math.Max(max.z, raw.z);
if (!(Object.Equals(min, oldmin)) || !(Object.Equals(max, oldmax)))
{
Debug.Print("new values");
Debug.Print("x: min=" + min.x + " max=" + max.x);
Debug.Print("y: min=" + min.y + " max=" + max.y);
Debug.Print("z: min=" + min.z + " max=" + max.z);
Debug.Print("");
}
}
}
/// <summary>
/// Read raw values from the accelerometer. We shift the values down
/// to 12 bits to reduce noise (the chip values aren't accurate to 16
/// bits).
/// </summary>
/// <returns>An int vector with the raw values</returns>
private intvector ReadRawAcc()
{
byte[] data = new byte[6];
intvector acc;
// assert the MSB of the address to get the accelerometer
// to do slave-transmit subaddress updating.
ReadRegister(this.m_accelConfig, ((byte) AccelRegisters.LSM303_REGISTER_ACCEL_OUT_X_L_A) | 0x80, data);
acc.x = (Int16) (((data[0] << 8) + data[1]));
acc.y = (Int16) (((data[2] << 8) + data[3]));
acc.z = (Int16) (((data[4] << 8) + data[5]));
acc.x = (Int16) (acc.x >> 4);
acc.y = (Int16) (acc.y >> 4);
acc.z = (Int16) (acc.z >> 4);
return acc;
}
/// <summary>
/// Read raw values from the mag sensor.
/// </summary>
/// <returns>An int vector with the raw values</returns>
private intvector ReadRawMag()
{
byte[] data = new byte[6];
intvector mag;
ReadRegister(this.m_magConfig, ((byte) MagRegisters.LSM303_REGISTER_MAG_OUT_X_H_M), data);
mag.x = (Int16) ((data[0] << 8) + data[1]);
mag.z = (Int16) ((data[2] << 8) + data[3]);
mag.y = (Int16) ((data[4] << 8) + data[5]);
return mag;
}
/// <summary>
/// Read array of bytes at specific register from the I2C slave device.
/// </summary>
/// <param name="config">I2C slave device configuration.</param>
/// <param name="register">The register to read bytes from.</param>
/// <param name="readBuffer">The array of bytes that will contain the data read from the device.</param>
/// <param name="transactionTimeout">The amount of time the system will wait before resuming execution of the transaction.</param>
public void ReadRegister(I2CDevice.Configuration config, byte register, byte[] readBuffer)
{
byte[] writeBuffer = {register};
// create an i2c write transaction to be sent to the device.
I2CDevice.I2CTransaction[] transactions = new I2CDevice.I2CTransaction[]
{
I2CDevice.CreateWriteTransaction(writeBuffer),
I2CDevice.CreateReadTransaction(readBuffer)
};
// the i2c data is sent here to the device.
int transferred;
lock (this.m_i2c)
{
this.m_i2c.Config = config;
transferred = this.m_i2c.Execute(transactions, TransactionTimeout);
}
// make sure the data was sent.
if (transferred != writeBuffer.Length + readBuffer.Length)
{
throw new IOException("Read Failed: " + transferred + "!=" + (writeBuffer.Length + readBuffer.Length));
}
}
/// <summary>
/// Write a byte value to a specific register on the I2C slave device.
/// </summary>
/// <param name="config">I2C slave device configuration.</param>
/// <param name="register">The register to send bytes to.</param>
/// <param name="value">The byte that will be sent to the device.</param>
/// <param name="transactionTimeout">The amount of time the system will wait before resuming execution of the transaction.</param>
public void WriteRegister(I2CDevice.Configuration config, byte register, byte value)
{
byte[] writeBuffer = {register, value};
// create an i2c write transaction to be sent to the device.
I2CDevice.I2CTransaction[] transactions = new I2CDevice.I2CTransaction[] {I2CDevice.CreateWriteTransaction(writeBuffer)};
// the i2c data is sent here to the device.
int transferred;
lock (this.m_i2c)
{
this.m_i2c.Config = config;
transferred = this.m_i2c.Execute(transactions, TransactionTimeout);
}
// make sure the data was sent.
if (transferred != writeBuffer.Length)
{
throw new IOException("Write Failed: " + transferred + "!=" + writeBuffer.Length);
}
}
private enum AccelRegisters : byte
{
// DEFAULT TYPE
LSM303_REGISTER_ACCEL_CTRL_REG1_A = 0x20, // 00000111 rw
LSM303_REGISTER_ACCEL_CTRL_REG2_A = 0x21, // 00000000 rw
LSM303_REGISTER_ACCEL_CTRL_REG3_A = 0x22, // 00000000 rw
LSM303_REGISTER_ACCEL_CTRL_REG4_A = 0x23, // 00000000 rw
LSM303_REGISTER_ACCEL_CTRL_REG5_A = 0x24, // 00000000 rw
LSM303_REGISTER_ACCEL_CTRL_REG6_A = 0x25, // 00000000 rw
LSM303_REGISTER_ACCEL_REFERENCE_A = 0x26, // 00000000 r
LSM303_REGISTER_ACCEL_STATUS_REG_A = 0x27, // 00000000 r
LSM303_REGISTER_ACCEL_OUT_X_L_A = 0x28,
LSM303_REGISTER_ACCEL_OUT_X_H_A = 0x29,
LSM303_REGISTER_ACCEL_OUT_Y_L_A = 0x2A,
LSM303_REGISTER_ACCEL_OUT_Y_H_A = 0x2B,
LSM303_REGISTER_ACCEL_OUT_Z_L_A = 0x2C,
LSM303_REGISTER_ACCEL_OUT_Z_H_A = 0x2D,
LSM303_REGISTER_ACCEL_FIFO_CTRL_REG_A = 0x2E,
LSM303_REGISTER_ACCEL_FIFO_SRC_REG_A = 0x2F,
LSM303_REGISTER_ACCEL_INT1_CFG_A = 0x30,
LSM303_REGISTER_ACCEL_INT1_SOURCE_A = 0x31,
LSM303_REGISTER_ACCEL_INT1_THS_A = 0x32,
LSM303_REGISTER_ACCEL_INT1_DURATION_A = 0x33,
LSM303_REGISTER_ACCEL_INT2_CFG_A = 0x34,
LSM303_REGISTER_ACCEL_INT2_SOURCE_A = 0x35,
LSM303_REGISTER_ACCEL_INT2_THS_A = 0x36,
LSM303_REGISTER_ACCEL_INT2_DURATION_A = 0x37,
LSM303_REGISTER_ACCEL_CLICK_CFG_A = 0x38,
LSM303_REGISTER_ACCEL_CLICK_SRC_A = 0x39,
LSM303_REGISTER_ACCEL_CLICK_THS_A = 0x3A,
LSM303_REGISTER_ACCEL_TIME_LIMIT_A = 0x3B,
LSM303_REGISTER_ACCEL_TIME_LATENCY_A = 0x3C,
LSM303_REGISTER_ACCEL_TIME_WINDOW_A = 0x3D
};
private enum MagRegisters : byte
{
LSM303_REGISTER_MAG_CRA_REG_M = 0x00,
LSM303_REGISTER_MAG_CRB_REG_M = 0x01,
LSM303_REGISTER_MAG_MR_REG_M = 0x02,
LSM303_REGISTER_MAG_OUT_X_H_M = 0x03,
LSM303_REGISTER_MAG_OUT_X_L_M = 0x04,
LSM303_REGISTER_MAG_OUT_Z_H_M = 0x05,
LSM303_REGISTER_MAG_OUT_Z_L_M = 0x06,
LSM303_REGISTER_MAG_OUT_Y_H_M = 0x07,
LSM303_REGISTER_MAG_OUT_Y_L_M = 0x08,
LSM303_REGISTER_MAG_SR_REG_Mg = 0x09,
LSM303_REGISTER_MAG_IRA_REG_M = 0x0A,
LSM303_REGISTER_MAG_IRB_REG_M = 0x0B,
LSM303_REGISTER_MAG_IRC_REG_M = 0x0C,
LSM303_REGISTER_MAG_TEMP_OUT_H_M = 0x31,
LSM303_REGISTER_MAG_TEMP_OUT_L_M = 0x32
}
public struct intvector
{
public Int16 x;
public Int16 y;
public Int16 z;
};
public struct vector
{
public double x;
public double y;
public double z;
public vector(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
};
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !NETSTANDARD1_3 && !NETSTANDARD1_5
namespace NLog
{
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Xml;
using NLog.Internal;
/// <summary>
/// TraceListener which routes all messages through NLog.
/// </summary>
public class NLogTraceListener : TraceListener
{
private LogFactory _logFactory;
private LogLevel _defaultLogLevel = LogLevel.Debug;
private bool _attributesLoaded;
private bool _autoLoggerName;
private LogLevel _forceLogLevel;
private bool _disableFlush;
/// <summary>
/// Initializes a new instance of the <see cref="NLogTraceListener"/> class.
/// </summary>
public NLogTraceListener()
{
}
/// <summary>
/// Gets or sets the log factory to use when outputting messages (null - use LogManager).
/// </summary>
public LogFactory LogFactory
{
get
{
InitAttributes();
return _logFactory;
}
set
{
_logFactory = value;
_attributesLoaded = true;
}
}
/// <summary>
/// Gets or sets the default log level.
/// </summary>
public LogLevel DefaultLogLevel
{
get
{
InitAttributes();
return _defaultLogLevel;
}
set
{
_defaultLogLevel = value;
_attributesLoaded = true;
}
}
/// <summary>
/// Gets or sets the log which should be always used regardless of source level.
/// </summary>
public LogLevel ForceLogLevel
{
get
{
InitAttributes();
return _forceLogLevel;
}
set
{
_forceLogLevel = value;
_attributesLoaded = true;
}
}
/// <summary>
/// Gets or sets a value indicating whether flush calls from trace sources should be ignored.
/// </summary>
public bool DisableFlush
{
get
{
InitAttributes();
return _disableFlush;
}
set
{
_disableFlush = value;
_attributesLoaded = true;
}
}
/// <summary>
/// Gets a value indicating whether the trace listener is thread safe.
/// </summary>
/// <value></value>
/// <returns>true if the trace listener is thread safe; otherwise, false. The default is false.</returns>
public override bool IsThreadSafe => true;
/// <summary>
/// Gets or sets a value indicating whether to use auto logger name detected from the stack trace.
/// </summary>
public bool AutoLoggerName
{
get
{
InitAttributes();
return _autoLoggerName;
}
set
{
_autoLoggerName = value;
_attributesLoaded = true;
}
}
/// <summary>
/// When overridden in a derived class, writes the specified message to the listener you create in the derived class.
/// </summary>
/// <param name="message">A message to write.</param>
public override void Write(string message)
{
ProcessLogEventInfo(DefaultLogLevel, null, message, null, null, TraceEventType.Resume, null);
}
/// <summary>
/// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator.
/// </summary>
/// <param name="message">A message to write.</param>
public override void WriteLine(string message)
{
ProcessLogEventInfo(DefaultLogLevel, null, message, null, null, TraceEventType.Resume, null);
}
/// <summary>
/// When overridden in a derived class, closes the output stream so it no longer receives tracing or debugging output.
/// </summary>
public override void Close()
{
//nothing to do in this case, but maybe in derived.
}
/// <summary>
/// Emits an error message.
/// </summary>
/// <param name="message">A message to emit.</param>
public override void Fail(string message)
{
ProcessLogEventInfo(LogLevel.Error, null, message, null, null, TraceEventType.Error, null);
}
/// <summary>
/// Emits an error message and a detailed error message.
/// </summary>
/// <param name="message">A message to emit.</param>
/// <param name="detailMessage">A detailed message to emit.</param>
public override void Fail(string message, string detailMessage)
{
ProcessLogEventInfo(LogLevel.Error, null, string.Concat(message, " ", detailMessage), null, null, TraceEventType.Error, null);
}
/// <summary>
/// Flushes the output (if <see cref="DisableFlush"/> is not <c>true</c>) buffer with the default timeout of 15 seconds.
/// </summary>
public override void Flush()
{
if (!DisableFlush)
{
if (LogFactory != null)
{
LogFactory.Flush();
}
else
{
LogManager.Flush();
}
}
}
/// <summary>
/// Writes trace information, a data object and event information to the listener specific output.
/// </summary>
/// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param>
/// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param>
/// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param>
/// <param name="id">A numeric identifier for the event.</param>
/// <param name="data">The trace data to emit.</param>
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
{
TraceData(eventCache, source, eventType, id, new object[] { data });
}
/// <summary>
/// Writes trace information, an array of data objects and event information to the listener specific output.
/// </summary>
/// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param>
/// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param>
/// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param>
/// <param name="id">A numeric identifier for the event.</param>
/// <param name="data">An array of objects to emit as data.</param>
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, string.Empty, null, null, data))
return;
string message = string.Empty;
if (data?.Length > 0)
{
if (data.Length == 1)
{
message = "{0}";
}
else
{
var sb = new StringBuilder(data.Length * 5 - 2);
for (int i = 0; i < data.Length; ++i)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append('{');
sb.AppendInvariant(i);
sb.Append('}');
}
message = sb.ToString();
}
}
ProcessLogEventInfo(TranslateLogLevel(eventType), source, message, data, id, eventType, null);
}
/// <summary>
/// Writes trace and event information to the listener specific output.
/// </summary>
/// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param>
/// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param>
/// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param>
/// <param name="id">A numeric identifier for the event.</param>
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, string.Empty, null, null, null))
return;
ProcessLogEventInfo(TranslateLogLevel(eventType), source, string.Empty, null, id, eventType, null);
}
/// <summary>
/// Writes trace information, a formatted array of objects and event information to the listener specific output.
/// </summary>
/// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param>
/// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param>
/// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param>
/// <param name="id">A numeric identifier for the event.</param>
/// <param name="format">A format string that contains zero or more format items, which correspond to objects in the <paramref name="args"/> array.</param>
/// <param name="args">An object array containing zero or more objects to format.</param>
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null))
return;
ProcessLogEventInfo(TranslateLogLevel(eventType), source, format, args, id, eventType, null);
}
/// <summary>
/// Writes trace information, a message, and event information to the listener specific output.
/// </summary>
/// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param>
/// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param>
/// <param name="eventType">One of the <see cref="System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param>
/// <param name="id">A numeric identifier for the event.</param>
/// <param name="message">A message to write.</param>
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
return;
ProcessLogEventInfo(TranslateLogLevel(eventType), source, message, null, id, eventType, null);
}
/// <summary>
/// Writes trace information, a message, a related activity identity and event information to the listener specific output.
/// </summary>
/// <param name="eventCache">A <see cref="System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param>
/// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param>
/// <param name="id">A numeric identifier for the event.</param>
/// <param name="message">A message to write.</param>
/// <param name="relatedActivityId">A <see cref="System.Guid"/> object identifying a related activity.</param>
public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, TraceEventType.Transfer, id, message, null, null, null))
return;
ProcessLogEventInfo(LogLevel.Debug, source, message, null, id, TraceEventType.Transfer, relatedActivityId);
}
/// <summary>
/// Gets the custom attributes supported by the trace listener.
/// </summary>
/// <returns>
/// A string array naming the custom attributes supported by the trace listener, or null if there are no custom attributes.
/// </returns>
protected override string[] GetSupportedAttributes()
{
return new[] { "defaultLogLevel", "autoLoggerName", "forceLogLevel", "disableFlush" };
}
/// <summary>
/// Translates the event type to level from <see cref="TraceEventType"/>.
/// </summary>
/// <param name="eventType">Type of the event.</param>
/// <returns>Translated log level.</returns>
private static LogLevel TranslateLogLevel(TraceEventType eventType)
{
switch (eventType)
{
case TraceEventType.Verbose:
return LogLevel.Trace;
case TraceEventType.Information:
return LogLevel.Info;
case TraceEventType.Warning:
return LogLevel.Warn;
case TraceEventType.Error:
return LogLevel.Error;
case TraceEventType.Critical:
return LogLevel.Fatal;
default:
return LogLevel.Debug;
}
}
/// <summary>
/// Process the log event
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">The name of the logger.</param>
/// <param name="message">The log message.</param>
/// <param name="arguments">The log parameters.</param>
/// <param name="eventId">The event id.</param>
/// <param name="eventType">The event type.</param>
/// <param name="relatedActivityId">The related activity id.</param>
/// </summary>
protected virtual void ProcessLogEventInfo(LogLevel logLevel, string loggerName, [Localizable(false)] string message, object[] arguments, int? eventId, TraceEventType? eventType, Guid? relatedActivityId)
{
StackTrace stackTrace = AutoLoggerName ? new StackTrace() : null;
var logger = GetLogger(loggerName, stackTrace, out int userFrameIndex);
logLevel = _forceLogLevel ?? logLevel;
if (!logger.IsEnabled(logLevel))
{
return; // We are done
}
var ev = new LogEventInfo();
ev.LoggerName = logger.Name;
ev.Level = logLevel;
if (eventType.HasValue)
{
ev.Properties.Add("EventType", eventType.Value);
}
if (relatedActivityId.HasValue)
{
ev.Properties.Add("RelatedActivityID", relatedActivityId.Value);
}
ev.Message = message;
ev.Parameters = arguments;
ev.Level = _forceLogLevel ?? logLevel;
if (eventId.HasValue)
{
ev.Properties.Add("EventID", eventId.Value);
}
if (stackTrace != null && userFrameIndex >= 0)
{
ev.SetStackTrace(stackTrace, userFrameIndex);
}
logger.Log(ev);
}
private Logger GetLogger(string loggerName, StackTrace stackTrace, out int userFrameIndex)
{
loggerName = (loggerName ?? Name) ?? string.Empty;
userFrameIndex = -1;
if (stackTrace != null)
{
for (int i = 0; i < stackTrace.FrameCount; ++i)
{
var frame = stackTrace.GetFrame(i);
loggerName = StackTraceUsageUtils.LookupClassNameFromStackFrame(frame);
if (!string.IsNullOrEmpty(loggerName))
{
userFrameIndex = i;
break;
}
}
}
if (LogFactory != null)
{
return LogFactory.GetLogger(loggerName);
}
else
{
return LogManager.GetLogger(loggerName);
}
}
private void InitAttributes()
{
if (!_attributesLoaded)
{
_attributesLoaded = true;
if (Trace.AutoFlush)
{
// Avoid a world of hurt, by not constantly spawning new flush threads
// Also timeout exceptions thrown by Flush() will not break diagnostic Trace-logic
_disableFlush = true;
}
foreach (DictionaryEntry de in Attributes)
{
var key = (string)de.Key;
var value = (string)de.Value;
switch (key.ToUpperInvariant())
{
case "DEFAULTLOGLEVEL":
_defaultLogLevel = LogLevel.FromString(value);
break;
case "FORCELOGLEVEL":
_forceLogLevel = LogLevel.FromString(value);
break;
case "AUTOLOGGERNAME":
AutoLoggerName = XmlConvert.ToBoolean(value);
break;
case "DISABLEFLUSH":
_disableFlush = bool.Parse(value);
break;
}
}
}
}
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Internal.Resources
{
using Management;
using Internal;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ResourceGroupsOperations operations.
/// </summary>
public partial interface IResourceGroupsOperations
{
/// <summary>
/// Get all the resources for a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group with the resources to get.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<GenericResource>>> ListResourcesWithHttpMessagesAsync(string resourceGroupName, ODataQuery<GenericResourceFilter> odataQuery = default(ODataQuery<GenericResourceFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Checks whether a resource group exists.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to check. The name is case
/// insensitive.
/// </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>
Task<AzureOperationResponse<bool>> CheckExistenceWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to create or update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update a resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ResourceGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, ResourceGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a resource group.
/// </summary>
/// <remarks>
/// When you delete a resource group, all of its resources are also
/// deleted. Deleting a resource group deletes all of its template
/// deployments and currently stored operations.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group to delete. The name is case
/// insensitive.
/// </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>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ResourceGroup>> GetWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a resource group.
/// </summary>
/// <remarks>
/// Resource groups can be updated through a simple PATCH operation to
/// a group address. The format of the request is the same as that for
/// creating a resource group. If a field is unspecified, the current
/// value is retained.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group to update. The name is case
/// insensitive.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update a resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ResourceGroup>> PatchWithHttpMessagesAsync(string resourceGroupName, ResourceGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Captures the specified resource group as a template.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to export as a template.
/// </param>
/// <param name='parameters'>
/// Parameters for exporting the template.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ResourceGroupExportResult>> ExportTemplateWithHttpMessagesAsync(string resourceGroupName, ExportTemplateRequest parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the resource groups for a subscription.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ResourceGroup>>> ListWithHttpMessagesAsync(ODataQuery<ResourceGroupFilter> odataQuery = default(ODataQuery<ResourceGroupFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a resource group.
/// </summary>
/// <remarks>
/// When you delete a resource group, all of its resources are also
/// deleted. Deleting a resource group deletes all of its template
/// deployments and currently stored operations.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group to delete. The name is case
/// insensitive.
/// </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>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all the resources for a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<GenericResource>>> ListResourcesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the resource groups for a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ResourceGroup>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// 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.Linq;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace Internal.Cryptography
{
internal static partial class OidLookup
{
private static readonly ConcurrentDictionary<string, string> s_lateBoundOidToFriendlyName =
new ConcurrentDictionary<string, string>();
private static readonly ConcurrentDictionary<string, string> s_lateBoundFriendlyNameToOid =
new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
//
// Attempts to map a friendly name to an OID. Returns null if not a known name.
//
public static string ToFriendlyName(string oid, OidGroup oidGroup, bool fallBackToAllGroups)
{
if (oid == null)
throw new ArgumentNullException(nameof(oid));
string mappedName;
bool shouldUseCache = ShouldUseCache(oidGroup);
// On Unix shouldUseCache is always true, so no matter what OidGroup is passed in the Windows
// friendly name will be returned.
//
// On Windows shouldUseCache is only true for OidGroup.All, because otherwise the OS may filter
// out the answer based on the group criteria.
if (shouldUseCache)
{
if (s_oidToFriendlyName.TryGetValue(oid, out mappedName) ||
s_compatOids.TryGetValue(oid, out mappedName) ||
s_lateBoundOidToFriendlyName.TryGetValue(oid, out mappedName))
{
return mappedName;
}
}
mappedName = NativeOidToFriendlyName(oid, oidGroup, fallBackToAllGroups);
if (shouldUseCache && mappedName != null)
{
s_lateBoundOidToFriendlyName.TryAdd(oid, mappedName);
// Don't add the reverse here. Just because oid => name doesn't mean name => oid.
// And don't bother doing the reverse lookup proactively, just wait until they ask for it.
}
return mappedName;
}
//
// Attempts to retrieve the friendly name for an OID. Returns null if not a known or valid OID.
//
public static string ToOid(string friendlyName, OidGroup oidGroup, bool fallBackToAllGroups)
{
if (friendlyName == null)
throw new ArgumentNullException(nameof(friendlyName));
if (friendlyName.Length == 0)
return null;
string mappedOid;
bool shouldUseCache = ShouldUseCache(oidGroup);
if (shouldUseCache)
{
if (s_friendlyNameToOid.TryGetValue(friendlyName, out mappedOid) ||
s_lateBoundFriendlyNameToOid.TryGetValue(friendlyName, out mappedOid))
{
return mappedOid;
}
}
mappedOid = NativeFriendlyNameToOid(friendlyName, oidGroup, fallBackToAllGroups);
if (shouldUseCache && mappedOid != null)
{
s_lateBoundFriendlyNameToOid.TryAdd(friendlyName, mappedOid);
// Don't add the reverse here. Friendly Name => OID is a case insensitive search,
// so the casing provided as input here may not be the 'correct' one. Just let
// ToFriendlyName capture the response and cache it itself.
}
return mappedOid;
}
// This table was originally built by extracting every szOID #define out of wincrypt.h,
// and running them through new Oid(string) on Windows 10. Then, take the list of everything
// which produced a FriendlyName value, and run it through two other languages. If all 3 agree
// on the mapping, consider the value to be non-localized.
//
// This original list was produced on English (Win10), cross-checked with Spanish (Win8.1) and
// Japanese (Win10).
//
// Sometimes wincrypt.h has more than one OID which results in the same name. The OIDs whose value
// doesn't roundtrip (new Oid(new Oid(value).FriendlyName).Value) are contained in s_compatOids.
//
// X-Plat: The names (and casing) in this table come from Windows. Part of the intent of this table
// is to prevent issues wherein an identifier is different between CoreFX\Windows and CoreFX\Unix;
// since any existing code would be using the Windows identifier, it is the de facto standard.
private static readonly Dictionary<string, string> s_friendlyNameToOid =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "3des", "1.2.840.113549.3.7" },
{ "aes128", "2.16.840.1.101.3.4.1.2" },
{ "aes128wrap", "2.16.840.1.101.3.4.1.5" },
{ "aes192", "2.16.840.1.101.3.4.1.22" },
{ "aes192wrap", "2.16.840.1.101.3.4.1.25" },
{ "aes256", "2.16.840.1.101.3.4.1.42" },
{ "aes256wrap", "2.16.840.1.101.3.4.1.45" },
{ "brainpoolP160r1", "1.3.36.3.3.2.8.1.1.1" },
{ "brainpoolP160t1", "1.3.36.3.3.2.8.1.1.2" },
{ "brainpoolP192r1", "1.3.36.3.3.2.8.1.1.3" },
{ "brainpoolP192t1", "1.3.36.3.3.2.8.1.1.4" },
{ "brainpoolP224r1", "1.3.36.3.3.2.8.1.1.5" },
{ "brainpoolP224t1", "1.3.36.3.3.2.8.1.1.6" },
{ "brainpoolP256r1", "1.3.36.3.3.2.8.1.1.7" },
{ "brainpoolP256t1", "1.3.36.3.3.2.8.1.1.8" },
{ "brainpoolP320r1", "1.3.36.3.3.2.8.1.1.9" },
{ "brainpoolP320t1", "1.3.36.3.3.2.8.1.1.10" },
{ "brainpoolP384r1", "1.3.36.3.3.2.8.1.1.11" },
{ "brainpoolP384t1", "1.3.36.3.3.2.8.1.1.12" },
{ "brainpoolP512r1", "1.3.36.3.3.2.8.1.1.13" },
{ "brainpoolP512t1", "1.3.36.3.3.2.8.1.1.14" },
{ "C", "2.5.4.6" },
{ "CMS3DESwrap", "1.2.840.113549.1.9.16.3.6" },
{ "CMSRC2wrap", "1.2.840.113549.1.9.16.3.7" },
{ "CN", "2.5.4.3" },
{ "CPS", "1.3.6.1.5.5.7.2.1" },
{ "DC", "0.9.2342.19200300.100.1.25" },
{ "des", "1.3.14.3.2.7" },
{ "Description", "2.5.4.13" },
{ "DH", "1.2.840.10046.2.1" },
{ "dnQualifier", "2.5.4.46" },
{ "DSA", "1.2.840.10040.4.1" },
{ "dsaSHA1", "1.3.14.3.2.27" },
{ "E", "1.2.840.113549.1.9.1" },
{ "ec192wapi", "1.2.156.11235.1.1.2.1" },
{ "ECC", "1.2.840.10045.2.1" },
{ "ECDH_STD_SHA1_KDF", "1.3.133.16.840.63.0.2" },
{ "ECDH_STD_SHA256_KDF", "1.3.132.1.11.1" },
{ "ECDH_STD_SHA384_KDF", "1.3.132.1.11.2" },
{ "ECDSA_P256", "1.2.840.10045.3.1.7" },
{ "ECDSA_P384", "1.3.132.0.34" },
{ "ECDSA_P521", "1.3.132.0.35" },
{ "ESDH", "1.2.840.113549.1.9.16.3.5" },
{ "G", "2.5.4.42" },
{ "I", "2.5.4.43" },
{ "L", "2.5.4.7" },
{ "md2", "1.2.840.113549.2.2" },
{ "md2RSA", "1.2.840.113549.1.1.2" },
{ "md4", "1.2.840.113549.2.4" },
{ "md4RSA", "1.2.840.113549.1.1.3" },
{ "md5", "1.2.840.113549.2.5" },
{ "md5RSA", "1.2.840.113549.1.1.4" },
{ "mgf1", "1.2.840.113549.1.1.8" },
{ "mosaicKMandUpdSig", "2.16.840.1.101.2.1.1.20" },
{ "mosaicUpdatedSig", "2.16.840.1.101.2.1.1.19" },
{ "nistP192", "1.2.840.10045.3.1.1" },
{ "nistP224", "1.3.132.0.33" },
{ "NO_SIGN", "1.3.6.1.5.5.7.6.2" },
{ "O", "2.5.4.10" },
{ "OU", "2.5.4.11" },
{ "Phone", "2.5.4.20" },
{ "POBox", "2.5.4.18" },
{ "PostalCode", "2.5.4.17" },
{ "rc2", "1.2.840.113549.3.2" },
{ "rc4", "1.2.840.113549.3.4" },
{ "RSA", "1.2.840.113549.1.1.1" },
{ "RSAES_OAEP", "1.2.840.113549.1.1.7" },
{ "RSASSA-PSS", "1.2.840.113549.1.1.10" },
{ "S", "2.5.4.8" },
{ "secP160k1", "1.3.132.0.9" },
{ "secP160r1", "1.3.132.0.8" },
{ "secP160r2", "1.3.132.0.30" },
{ "secP192k1", "1.3.132.0.31" },
{ "secP224k1", "1.3.132.0.32" },
{ "secP256k1", "1.3.132.0.10" },
{ "SERIALNUMBER", "2.5.4.5" },
{ "sha1", "1.3.14.3.2.26" },
{ "sha1DSA", "1.2.840.10040.4.3" },
{ "sha1ECDSA", "1.2.840.10045.4.1" },
{ "sha1RSA", "1.2.840.113549.1.1.5" },
{ "sha256", "2.16.840.1.101.3.4.2.1" },
{ "sha256ECDSA", "1.2.840.10045.4.3.2" },
{ "sha256RSA", "1.2.840.113549.1.1.11" },
{ "sha384", "2.16.840.1.101.3.4.2.2" },
{ "sha384ECDSA", "1.2.840.10045.4.3.3" },
{ "sha384RSA", "1.2.840.113549.1.1.12" },
{ "sha512", "2.16.840.1.101.3.4.2.3" },
{ "sha512ECDSA", "1.2.840.10045.4.3.4" },
{ "sha512RSA", "1.2.840.113549.1.1.13" },
{ "SN", "2.5.4.4" },
{ "specifiedECDSA", "1.2.840.10045.4.3" },
{ "STREET", "2.5.4.9" },
{ "T", "2.5.4.12" },
{ "wtls9", "2.23.43.1.4.9" },
{ "X21Address", "2.5.4.24" },
{ "x962P192v2", "1.2.840.10045.3.1.2" },
{ "x962P192v3", "1.2.840.10045.3.1.3" },
{ "x962P239v1", "1.2.840.10045.3.1.4" },
{ "x962P239v2", "1.2.840.10045.3.1.5" },
{ "x962P239v3", "1.2.840.10045.3.1.6" },
};
private static readonly Dictionary<string, string> s_oidToFriendlyName =
s_friendlyNameToOid.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
private static readonly Dictionary<string, string> s_compatOids =
new Dictionary<string, string>
{
{ "1.2.840.113549.1.3.1", "DH" },
{ "1.3.14.3.2.12", "DSA" },
{ "1.3.14.3.2.13", "sha1DSA" },
{ "1.3.14.3.2.15", "shaRSA" },
{ "1.3.14.3.2.18", "sha" },
{ "1.3.14.3.2.2", "md4RSA" },
{ "1.3.14.3.2.22", "RSA_KEYX" },
{ "1.3.14.3.2.29", "sha1RSA" },
{ "1.3.14.3.2.3", "md5RSA" },
{ "1.3.14.3.2.4", "md4RSA" },
{ "1.3.14.7.2.3.1", "md2RSA" },
};
}
}
| |
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Encapsulates the native logic required to create,
/// configure, and show a TaskDialog,
/// via the TaskDialogIndirect() Win32 function.
/// </summary>
/// <remarks>A new instance of this class should
/// be created for each messagebox show, as
/// the HWNDs for TaskDialogs do not remain constant
/// across calls to TaskDialogIndirect.
/// </remarks>
internal class NativeTaskDialog : IDisposable
{
private TaskDialogNativeMethods.TASKDIALOGCONFIG nativeDialogConfig;
private NativeTaskDialogSettings settings;
private IntPtr hWndDialog;
private TaskDialog outerDialog;
private IntPtr[] updatedStrings = new IntPtr[Enum.GetNames(typeof(TaskDialogNativeMethods.TASKDIALOG_ELEMENTS)).Length];
private IntPtr buttonArray, radioButtonArray;
// Flag tracks whether our first radio
// button click event has come through.
private bool firstRadioButtonClicked = true;
#region Constructors
// Configuration is applied at dialog creation time.
internal NativeTaskDialog(
NativeTaskDialogSettings settings,
TaskDialog outerDialog)
{
nativeDialogConfig = settings.NativeConfiguration;
this.settings = settings;
// Wireup dialog proc message loop for this instance.
nativeDialogConfig.pfCallback =
new TaskDialogNativeMethods.PFTASKDIALOGCALLBACK(DialogProc);
// Keep a reference to the outer shell, so we can notify.
this.outerDialog = outerDialog;
}
#endregion
#region Public Properties
private DialogShowState showState =
DialogShowState.PreShow;
public DialogShowState ShowState
{
get { return showState; }
}
private int selectedButtonID;
internal int SelectedButtonID
{
get { return selectedButtonID; }
}
private int selectedRadioButtonID;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal int SelectedRadioButtonID
{
get { return selectedRadioButtonID; }
}
private bool checkBoxChecked;
internal bool CheckBoxChecked
{
get { return checkBoxChecked; }
}
#endregion
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)",
Justification = "We are not currently handling globalization or localization")]
internal void NativeShow()
{
// Applies config struct and other settings, then
// calls main Win32 function.
if (settings == null)
throw new InvalidOperationException(
"An error has occurred in dialog configuration.");
// Do a last-minute parse of the various dialog control lists,
// and only allocate the memory at the last minute.
MarshalDialogControlStructs();
// Make the call and show the dialog.
// NOTE: this call is BLOCKING, though the thread
// WILL re-enter via the DialogProc.
try
{
showState = DialogShowState.Showing;
// Here is the way we use "vanilla" P/Invoke to call
// TaskDialogIndirect().
HRESULT hresult = TaskDialogNativeMethods.TaskDialogIndirect(
nativeDialogConfig,
out selectedButtonID,
out selectedRadioButtonID,
out checkBoxChecked);
if (CoreErrorHelper.Failed(hresult))
{
string msg;
switch (hresult)
{
case HRESULT.E_INVALIDARG:
msg = "Invalid arguments to Win32 call.";
break;
case HRESULT.E_OUTOFMEMORY:
msg = "Dialog contents too complex.";
break;
default:
msg = String.Format(
"An unexpected internal error occurred in the Win32 call:{0:x}",
hresult);
break;
}
Exception e = Marshal.GetExceptionForHR((int)hresult);
throw new Win32Exception(msg, e);
}
}
catch (EntryPointNotFoundException)
{
throw new NotSupportedException("TaskDialog feature needs to load version 6 of comctl32.dll but a different version is current loaded in memory.");
}
finally
{
showState = DialogShowState.Closed;
}
}
// The new task dialog does not support the existing
// Win32 functions for closing (e.g. EndDialog()); instead,
// a "click button" message is sent. In this case, we're
// abstracting out to say that the TaskDialog consumer can
// simply call "Close" and we'll "click" the cancel button.
// Note that the cancel button doesn't actually
// have to exist for this to work.
internal void NativeClose(TaskDialogResult result)
{
showState = DialogShowState.Closing;
int id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDCANCEL;
if(result == TaskDialogResult.Close)
id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDCLOSE;
else if(result == TaskDialogResult.CustomButtonClicked)
id = DialogsDefaults.MinimumDialogControlId; // custom buttons
else if(result == TaskDialogResult.No)
id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDNO;
else if(result == TaskDialogResult.Ok)
id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDOK;
else if(result == TaskDialogResult.Retry)
id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDRETRY;
else if(result == TaskDialogResult.Yes)
id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDYES;
SendMessageHelper(TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_CLICK_BUTTON, id, 0);
}
#region Main Dialog Proc
private int DialogProc(
IntPtr hwnd,
uint msg,
IntPtr wParam,
IntPtr lParam,
IntPtr lpRefData)
{
// Fetch the HWND - it may be the first time we're getting it.
hWndDialog = hwnd;
// Big switch on the various notifications the
// dialog proc can get.
switch ((TaskDialogNativeMethods.TASKDIALOG_NOTIFICATIONS)msg)
{
case TaskDialogNativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_CREATED:
int result = PerformDialogInitialization();
outerDialog.RaiseOpenedEvent();
return result;
case TaskDialogNativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_BUTTON_CLICKED:
return HandleButtonClick((int)wParam);
case TaskDialogNativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_RADIO_BUTTON_CLICKED:
return HandleRadioButtonClick((int)wParam);
case TaskDialogNativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_HYPERLINK_CLICKED:
return HandleHyperlinkClick(lParam);
case TaskDialogNativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_HELP:
return HandleHelpInvocation();
case TaskDialogNativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_TIMER:
return HandleTick((int)wParam);
case TaskDialogNativeMethods.TASKDIALOG_NOTIFICATIONS.TDN_DESTROYED:
return PerformDialogCleanup();
default:
break;
}
return (int)HRESULT.S_OK;
}
// Once the task dialog HWND is open, we need to send
// additional messages to configure it.
private int PerformDialogInitialization()
{
// Initialize Progress or Marquee Bar.
if (IsOptionSet(TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_SHOW_PROGRESS_BAR))
{
UpdateProgressBarRange();
// The order of the following is important -
// state is more important than value,
// and non-normal states turn off the bar value change
// animation, which is likely the intended
// and preferable behavior.
UpdateProgressBarState(settings.ProgressBarState);
UpdateProgressBarValue(settings.ProgressBarValue);
// Due to a bug that wasn't fixed in time for RTM of Vista,
// second SendMessage is required if the state is non-Normal.
UpdateProgressBarValue(settings.ProgressBarValue);
}
else if (IsOptionSet(TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_SHOW_MARQUEE_PROGRESS_BAR))
{
// TDM_SET_PROGRESS_BAR_MARQUEE is necessary
// to cause the marquee to start animating.
// Note that this internal task dialog setting is
// round-tripped when the marquee is
// is set to different states, so it never has to
// be touched/sent again.
SendMessageHelper(TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_PROGRESS_BAR_MARQUEE, 1, 0);
UpdateProgressBarState(settings.ProgressBarState);
}
if (settings.ElevatedButtons != null && settings.ElevatedButtons.Count > 0)
{
foreach (int id in settings.ElevatedButtons)
{
UpdateElevationIcon(id, true);
}
}
return CoreErrorHelper.IGNORED;
}
private int HandleButtonClick(int id)
{
// First we raise a Click event, if there is a custom button
// However, we implement Close() by sending a cancel button, so
// we don't want to raise a click event in response to that.
if (showState != DialogShowState.Closing)
outerDialog.RaiseButtonClickEvent(id);
// Once that returns, we raise a Closing event for the dialog
// The Win32 API handles button clicking-and-closing
// as an atomic action,
// but it is more .NET friendly to split them up.
// Unfortunately, we do NOT have the return values at this stage.
if(id <= 9)
return outerDialog.RaiseClosingEvent(id);
else
return 1;
}
private int HandleRadioButtonClick(int id)
{
// When the dialog sets the radio button to default,
// it (somewhat confusingly)issues a radio button clicked event
// - we mask that out - though ONLY if
// we do have a default radio button
if (firstRadioButtonClicked && !IsOptionSet(TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_NO_DEFAULT_RADIO_BUTTON))
firstRadioButtonClicked = false;
else
{
outerDialog.RaiseButtonClickEvent(id);
}
// Note: we don't raise Closing, as radio
// buttons are non-committing buttons
return CoreErrorHelper.IGNORED;
}
private int HandleHyperlinkClick(IntPtr pszHREF)
{
string link = Marshal.PtrToStringUni(pszHREF);
outerDialog.RaiseHyperlinkClickEvent(link);
return CoreErrorHelper.IGNORED;
}
private int HandleTick(int ticks)
{
outerDialog.RaiseTickEvent(ticks);
return CoreErrorHelper.IGNORED;
}
private int HandleHelpInvocation()
{
outerDialog.RaiseHelpInvokedEvent();
return CoreErrorHelper.IGNORED;
}
// There should be little we need to do here,
// as the use of the NativeTaskDialog is
// that it is instantiated for a single show, then disposed of.
private int PerformDialogCleanup()
{
firstRadioButtonClicked = true;
return CoreErrorHelper.IGNORED;
}
#endregion
#region Update members
internal void UpdateProgressBarValue(int i)
{
AssertCurrentlyShowing();
SendMessageHelper(TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_PROGRESS_BAR_POS, i, 0);
}
internal void UpdateProgressBarRange()
{
AssertCurrentlyShowing();
// Build range LPARAM - note it is in REVERSE intuitive order.
long range = NativeTaskDialog.MakeLongLParam(
settings.ProgressBarMaximum,
settings.ProgressBarMinimum);
SendMessageHelper(TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_PROGRESS_BAR_RANGE, 0, range);
}
internal void UpdateProgressBarState(TaskDialogProgressBarState state)
{
AssertCurrentlyShowing();
SendMessageHelper(TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_PROGRESS_BAR_STATE, (int)state, 0);
}
internal void UpdateText(string text)
{
UpdateTextCore(text, TaskDialogNativeMethods.TASKDIALOG_ELEMENTS.TDE_CONTENT);
}
internal void UpdateInstruction(string instruction)
{
UpdateTextCore(instruction, TaskDialogNativeMethods.TASKDIALOG_ELEMENTS.TDE_MAIN_INSTRUCTION);
}
internal void UpdateFooterText(string footerText)
{
UpdateTextCore(footerText, TaskDialogNativeMethods.TASKDIALOG_ELEMENTS.TDE_FOOTER);
}
internal void UpdateExpandedText(string expandedText)
{
UpdateTextCore(expandedText, TaskDialogNativeMethods.TASKDIALOG_ELEMENTS.TDE_EXPANDED_INFORMATION);
}
private void UpdateTextCore(string s, TaskDialogNativeMethods.TASKDIALOG_ELEMENTS element)
{
AssertCurrentlyShowing();
FreeOldString(element);
SendMessageHelper(
TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_ELEMENT_TEXT,
(int)element,
(long)MakeNewString(s, element));
}
internal void UpdateMainIcon(TaskDialogStandardIcon mainIcon)
{
UpdateIconCore(mainIcon, TaskDialogNativeMethods.TASKDIALOG_ICON_ELEMENT.TDIE_ICON_MAIN);
}
internal void UpdateFooterIcon(TaskDialogStandardIcon footerIcon)
{
UpdateIconCore(footerIcon, TaskDialogNativeMethods.TASKDIALOG_ICON_ELEMENT.TDIE_ICON_FOOTER);
}
private void UpdateIconCore(TaskDialogStandardIcon icon, TaskDialogNativeMethods.TASKDIALOG_ICON_ELEMENT element)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_UPDATE_ICON,
(int)element,
(long)icon);
}
internal void UpdateCheckBoxChecked(bool cbc)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_CLICK_VERIFICATION,
(cbc ? 1 : 0),
1);
}
internal void UpdateElevationIcon(int buttonId, bool showIcon)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE,
buttonId,
Convert.ToInt32(showIcon));
}
internal void UpdateButtonEnabled(int buttonID, bool enabled)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_ENABLE_BUTTON, buttonID, enabled == true ? 1 : 0);
}
internal void UpdateRadioButtonEnabled(int buttonID, bool enabled)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_ENABLE_RADIO_BUTTON, buttonID, enabled == true? 1 : 0);
}
internal void AssertCurrentlyShowing()
{
Debug.Assert(showState == DialogShowState.Showing, "Update*() methods should only be called while native dialog is showing");
}
#endregion
#region Helpers
private int SendMessageHelper(TaskDialogNativeMethods.TASKDIALOG_MESSAGES msg, int wParam, long lParam)
{
// Be sure to at least assert here -
// messages to invalid handles often just disappear silently
Debug.Assert(hWndDialog != null,
"HWND for dialog is null during SendMessage");
return (int)CoreNativeMethods.SendMessage(
hWndDialog,
(uint)msg,
(IntPtr)wParam,
new IntPtr(lParam));
}
private bool IsOptionSet(TaskDialogNativeMethods.TASKDIALOG_FLAGS flag)
{
return ((nativeDialogConfig.dwFlags & flag) == flag);
}
// Allocates a new string on the unmanaged heap,
// and stores the pointer so we can free it later.
private IntPtr MakeNewString(string s,
TaskDialogNativeMethods.TASKDIALOG_ELEMENTS element)
{
IntPtr newStringPtr = Marshal.StringToHGlobalUni(s);
updatedStrings[(int)element] = newStringPtr;
return newStringPtr;
}
// Checks to see if the given element already has an
// updated string, and if so,
// frees it. This is done in preparation for a call to
// MakeNewString(), to prevent
// leaks from multiple updates calls on the same element
// within a single native dialog lifetime.
private void FreeOldString(TaskDialogNativeMethods.TASKDIALOG_ELEMENTS element)
{
int elementIndex = (int)element;
if (updatedStrings[elementIndex] != IntPtr.Zero)
{
Marshal.FreeHGlobal(updatedStrings[elementIndex]);
updatedStrings[elementIndex] = IntPtr.Zero;
}
}
// Based on the following defines in WinDef.h and WinUser.h:
// #define MAKELPARAM(l, h) ((LPARAM)(DWORD)MAKELONG(l, h))
// #define MAKELONG(a, b) ((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16))
private static long MakeLongLParam(int a, int b)
{
return (a << 16) + b;
}
// Builds the actual configuration that the
// NativeTaskDialog (and underlying Win32 API)
// expects, by parsing the various control lists,
// marshaling to the unmanaged heap, etc.
private void MarshalDialogControlStructs()
{
if (settings.Buttons != null && settings.Buttons.Length > 0)
{
buttonArray = AllocateAndMarshalButtons(settings.Buttons);
settings.NativeConfiguration.pButtons = buttonArray;
settings.NativeConfiguration.cButtons = (uint)settings.Buttons.Length;
}
if (settings.RadioButtons != null && settings.RadioButtons.Length > 0)
{
radioButtonArray = AllocateAndMarshalButtons(settings.RadioButtons);
settings.NativeConfiguration.pRadioButtons = radioButtonArray;
settings.NativeConfiguration.cRadioButtons = (uint)settings.RadioButtons.Length;
}
}
private static IntPtr AllocateAndMarshalButtons(TaskDialogNativeMethods.TASKDIALOG_BUTTON[] structs)
{
IntPtr initialPtr = Marshal.AllocHGlobal(
Marshal.SizeOf(typeof(TaskDialogNativeMethods.TASKDIALOG_BUTTON)) * structs.Length);
IntPtr currentPtr = initialPtr;
foreach (TaskDialogNativeMethods.TASKDIALOG_BUTTON button in structs)
{
Marshal.StructureToPtr(button, currentPtr, false);
currentPtr = (IntPtr)((int)currentPtr + Marshal.SizeOf(button));
}
return initialPtr;
}
#endregion
#region IDispose Pattern
private bool disposed;
// Finalizer and IDisposable implementation.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~NativeTaskDialog()
{
Dispose(false);
}
// Core disposing logic.
protected void Dispose(bool disposing)
{
if (!disposed)
{
disposed = true;
// Single biggest resource - make sure the dialog
// itself has been instructed to close.
if (showState == DialogShowState.Showing)
NativeClose(TaskDialogResult.Cancel);
// Clean up custom allocated strings that were updated
// while the dialog was showing. Note that the strings
// passed in the initial TaskDialogIndirect call will
// be cleaned up automagically by the default
// marshalling logic.
if (updatedStrings != null)
{
for (int i = 0; i < updatedStrings.Length; i++)
{
if (updatedStrings[i] != IntPtr.Zero)
{
Marshal.FreeHGlobal(updatedStrings[i]);
updatedStrings[i] = IntPtr.Zero;
}
}
}
// Clean up the button and radio button arrays, if any.
if (buttonArray != IntPtr.Zero)
{
Marshal.FreeHGlobal(buttonArray);
buttonArray = IntPtr.Zero;
}
if (radioButtonArray != IntPtr.Zero)
{
Marshal.FreeHGlobal(radioButtonArray);
radioButtonArray = IntPtr.Zero;
}
if (disposing)
{
// Clean up managed resources - currently there are none
// that are interesting.
}
}
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using osuTK;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Performance;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Visualisation;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.IO.Stores;
using osu.Framework.Localisation;
using osu.Framework.Platform;
namespace osu.Framework
{
public abstract class Game : Container, IKeyBindingHandler<FrameworkAction>, IHandleGlobalKeyboardInput
{
public IWindow Window => Host?.Window;
public ResourceStore<byte[]> Resources { get; private set; }
public TextureStore Textures { get; private set; }
protected GameHost Host { get; private set; }
private readonly Bindable<bool> isActive = new Bindable<bool>(true);
/// <summary>
/// Whether the game is active (in the foreground).
/// </summary>
public IBindable<bool> IsActive => isActive;
public AudioManager Audio { get; private set; }
public ShaderManager Shaders { get; private set; }
/// <summary>
/// A store containing fonts accessible game-wide.
/// </summary>
/// <remarks>
/// It is recommended to use <see cref="AddFont"/> when adding new fonts.
/// </remarks>
public FontStore Fonts { get; private set; }
private FontStore localFonts;
protected LocalisationManager Localisation { get; private set; }
private readonly Container content;
private DrawVisualiser drawVisualiser;
private TextureVisualiser textureVisualiser;
private LogOverlay logOverlay;
protected override Container<Drawable> Content => content;
protected internal virtual UserInputManager CreateUserInputManager() => new UserInputManager();
/// <summary>
/// Provide <see cref="FrameworkSetting"/> defaults which should override those provided by osu-framework.
/// <remarks>
/// Please check https://github.com/ppy/osu-framework/blob/master/osu.Framework/Configuration/FrameworkConfigManager.cs for expected types.
/// </remarks>
/// </summary>
protected internal virtual IDictionary<FrameworkSetting, object> GetFrameworkConfigDefaults() => null;
/// <summary>
/// Creates the <see cref="Storage"/> where this <see cref="Game"/> will reside.
/// </summary>
/// <param name="host">The <see cref="GameHost"/>.</param>
/// <param name="defaultStorage">The default <see cref="Storage"/> to be used if a custom <see cref="Storage"/> isn't desired.</param>
/// <returns>The <see cref="Storage"/>.</returns>
protected internal virtual Storage CreateStorage(GameHost host, Storage defaultStorage) => defaultStorage;
protected Game()
{
RelativeSizeAxes = Axes.Both;
AddRangeInternal(new Drawable[]
{
content = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
},
});
}
/// <summary>
/// As Load is run post host creation, you can override this method to alter properties of the host before it makes itself visible to the user.
/// </summary>
/// <param name="host"></param>
public virtual void SetHost(GameHost host)
{
Host = host;
host.Exiting += OnExiting;
host.Activated += () => isActive.Value = true;
host.Deactivated += () => isActive.Value = false;
}
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) =>
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager config)
{
Resources = new ResourceStore<byte[]>();
Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(typeof(Game).Assembly), @"Resources"));
Textures = new TextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures")));
Textures.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
dependencies.Cache(Textures);
var tracks = new ResourceStore<byte[]>();
tracks.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Tracks"));
tracks.AddStore(new OnlineStore());
var samples = new ResourceStore<byte[]>();
samples.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Samples"));
samples.AddStore(new OnlineStore());
Audio = new AudioManager(Host.AudioThread, tracks, samples) { EventScheduler = Scheduler };
dependencies.Cache(Audio);
dependencies.CacheAs(Audio.Tracks);
dependencies.CacheAs(Audio.Samples);
// attach our bindables to the audio subsystem.
config.BindWith(FrameworkSetting.AudioDevice, Audio.AudioDevice);
config.BindWith(FrameworkSetting.VolumeUniversal, Audio.Volume);
config.BindWith(FrameworkSetting.VolumeEffect, Audio.VolumeSample);
config.BindWith(FrameworkSetting.VolumeMusic, Audio.VolumeTrack);
Shaders = new ShaderManager(new NamespacedResourceStore<byte[]>(Resources, @"Shaders"));
dependencies.Cache(Shaders);
var cacheStorage = Host.Storage.GetStorageForDirectory(Path.Combine("cache", "fonts"));
// base store is for user fonts
Fonts = new FontStore(useAtlas: true, cacheStorage: cacheStorage);
// nested store for framework provided fonts.
// note that currently this means there could be two async font load operations.
Fonts.AddStore(localFonts = new FontStore(useAtlas: false));
addFont(localFonts, Resources, @"Fonts/OpenSans/OpenSans");
addFont(localFonts, Resources, @"Fonts/OpenSans/OpenSans-Bold");
addFont(localFonts, Resources, @"Fonts/OpenSans/OpenSans-Italic");
addFont(localFonts, Resources, @"Fonts/OpenSans/OpenSans-BoldItalic");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Solid");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Regular");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Brands");
dependencies.Cache(Fonts);
Localisation = new LocalisationManager(config);
dependencies.Cache(Localisation);
frameSyncMode = config.GetBindable<FrameSync>(FrameworkSetting.FrameSync);
executionMode = config.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
logOverlayVisibility = config.GetBindable<bool>(FrameworkSetting.ShowLogOverlay);
logOverlayVisibility.BindValueChanged(visibility =>
{
if (visibility.NewValue)
{
if (logOverlay == null)
{
LoadComponentAsync(logOverlay = new LogOverlay
{
Depth = float.MinValue / 2,
}, AddInternal);
}
logOverlay.Show();
}
else
{
logOverlay?.Hide();
}
}, true);
}
/// <summary>
/// Add a font to be globally accessible to the game.
/// </summary>
/// <param name="store">The backing store with font resources.</param>
/// <param name="assetName">The base name of the font.</param>
/// <param name="target">An optional target store to add the font to. If not specified, <see cref="Fonts"/> is used.</param>
public void AddFont(ResourceStore<byte[]> store, string assetName = null, FontStore target = null)
=> addFont(target ?? Fonts, store, assetName);
private void addFont(FontStore target, ResourceStore<byte[]> store, string assetName = null)
=> target.AddStore(new RawCachingGlyphStore(store, assetName, Host.CreateTextureLoaderStore(store)));
protected override void LoadComplete()
{
base.LoadComplete();
PerformanceOverlay performanceOverlay;
LoadComponentAsync(performanceOverlay = new PerformanceOverlay(Host.Threads)
{
Margin = new MarginPadding(5),
Direction = FillDirection.Vertical,
Spacing = new Vector2(10, 10),
AutoSizeAxes = Axes.Both,
Alpha = 0,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
Depth = float.MinValue
}, AddInternal);
FrameStatistics.BindValueChanged(e => performanceOverlay.State = e.NewValue, true);
}
protected readonly Bindable<FrameStatisticsMode> FrameStatistics = new Bindable<FrameStatisticsMode>();
private GlobalStatisticsDisplay globalStatistics;
private Bindable<bool> logOverlayVisibility;
private Bindable<FrameSync> frameSyncMode;
private Bindable<ExecutionMode> executionMode;
public bool OnPressed(FrameworkAction action)
{
switch (action)
{
case FrameworkAction.CycleFrameStatistics:
switch (FrameStatistics.Value)
{
case FrameStatisticsMode.None:
FrameStatistics.Value = FrameStatisticsMode.Minimal;
break;
case FrameStatisticsMode.Minimal:
FrameStatistics.Value = FrameStatisticsMode.Full;
break;
case FrameStatisticsMode.Full:
FrameStatistics.Value = FrameStatisticsMode.None;
break;
}
return true;
case FrameworkAction.ToggleGlobalStatistics:
if (globalStatistics == null)
{
LoadComponentAsync(globalStatistics = new GlobalStatisticsDisplay
{
Depth = float.MinValue / 2,
Position = new Vector2(100 + ToolWindow.WIDTH, 100)
}, AddInternal);
}
globalStatistics.ToggleVisibility();
return true;
case FrameworkAction.ToggleDrawVisualiser:
if (drawVisualiser == null)
{
LoadComponentAsync(drawVisualiser = new DrawVisualiser
{
ToolPosition = new Vector2(100),
Depth = float.MinValue / 2,
}, AddInternal);
}
drawVisualiser.ToggleVisibility();
return true;
case FrameworkAction.ToggleAtlasVisualiser:
if (textureVisualiser == null)
{
LoadComponentAsync(textureVisualiser = new TextureVisualiser
{
Position = new Vector2(100 + 2 * ToolWindow.WIDTH, 100),
Depth = float.MinValue / 2,
}, AddInternal);
}
textureVisualiser.ToggleVisibility();
return true;
case FrameworkAction.ToggleLogOverlay:
logOverlayVisibility.Value = !logOverlayVisibility.Value;
return true;
case FrameworkAction.ToggleFullscreen:
Window?.CycleMode();
return true;
case FrameworkAction.CycleFrameSync:
var nextFrameSync = frameSyncMode.Value + 1;
if (nextFrameSync > FrameSync.Unlimited)
nextFrameSync = FrameSync.VSync;
frameSyncMode.Value = nextFrameSync;
break;
case FrameworkAction.CycleExecutionMode:
var nextExecutionMode = executionMode.Value + 1;
if (nextExecutionMode > ExecutionMode.MultiThreaded)
nextExecutionMode = ExecutionMode.SingleThread;
executionMode.Value = nextExecutionMode;
break;
}
return false;
}
public void OnReleased(FrameworkAction action)
{
}
public void Exit()
{
if (Host == null)
throw new InvalidOperationException("Attempted to exit a game which has not yet been run");
Host.Exit();
}
protected virtual bool OnExiting() => false;
protected override void Dispose(bool isDisposing)
{
// ensure any async disposals are completed before we begin to rip components out.
// if we were to not wait, async disposals may throw unexpected exceptions.
AsyncDisposalQueue.WaitForEmpty();
base.Dispose(isDisposing);
// call a second time to protect against anything being potentially async disposed in the base.Dispose call.
AsyncDisposalQueue.WaitForEmpty();
Audio?.Dispose();
Audio = null;
Fonts?.Dispose();
Fonts = null;
localFonts?.Dispose();
localFonts = null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
namespace System
{
// Represents a Globally Unique Identifier.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid>
{
public static readonly Guid Empty = new Guid();
////////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////////
private int _a;
private short _b;
private short _c;
private byte _d;
private byte _e;
private byte _f;
private byte _g;
private byte _h;
private byte _i;
private byte _j;
private byte _k;
////////////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////////////
// Creates a new guid from an array of bytes.
//
public Guid(byte[] b)
{
if (b == null)
throw new ArgumentNullException(nameof(b));
if (b.Length != 16)
throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b));
Contract.EndContractBlock();
_a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0];
_b = (short)(((int)b[5] << 8) | b[4]);
_c = (short)(((int)b[7] << 8) | b[6]);
_d = b[8];
_e = b[9];
_f = b[10];
_g = b[11];
_h = b[12];
_i = b[13];
_j = b[14];
_k = b[15];
}
[CLSCompliant(false)]
public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = (int)a;
_b = (short)b;
_c = (short)c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
// Creates a new GUID initialized to the value represented by the arguments.
//
public Guid(int a, short b, short c, byte[] d)
{
if (d == null)
throw new ArgumentNullException(nameof(d));
// Check that array is not too big
if (d.Length != 8)
throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d));
Contract.EndContractBlock();
_a = a;
_b = b;
_c = c;
_d = d[0];
_e = d[1];
_f = d[2];
_g = d[3];
_h = d[4];
_i = d[5];
_j = d[6];
_k = d[7];
}
// Creates a new GUID initialized to the value represented by the
// arguments. The bytes are specified like this to avoid endianness issues.
//
public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = a;
_b = b;
_c = c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
[Flags]
private enum GuidStyles
{
None = 0x00000000,
AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens
AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces
AllowDashes = 0x00000004, //Allow the guid to contain dash group separators
AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd}
RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens
RequireBraces = 0x00000020, //Require the guid to be enclosed in braces
RequireDashes = 0x00000040, //Require the guid to contain dash group separators
RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd}
HexFormat = RequireBraces | RequireHexPrefix, /* X */
NumberFormat = None, /* N */
DigitFormat = RequireDashes, /* D */
BraceFormat = RequireBraces | RequireDashes, /* B */
ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */
Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix,
}
private enum GuidParseThrowStyle
{
None = 0,
All = 1,
AllButOverflow = 2
}
private enum ParseFailureKind
{
None = 0,
ArgumentNull = 1,
Format = 2,
FormatWithParameter = 3,
NativeException = 4,
FormatWithInnerException = 5
}
// This will store the result of the parsing. And it will eventually be used to construct a Guid instance.
private struct GuidResult
{
internal Guid parsedGuid;
internal GuidParseThrowStyle throwStyle;
internal ParseFailureKind m_failure;
internal string m_resourceMessageFormat;
internal object m_failureMessageFormatArgument;
internal string m_failureArgumentName;
internal Exception m_innerException;
internal void Init(GuidParseThrowStyle canThrow)
{
parsedGuid = Guid.Empty;
throwStyle = canThrow;
}
internal void SetFailure(Exception nativeException)
{
m_failure = ParseFailureKind.NativeException;
m_innerException = nativeException;
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID)
{
SetFailure(failure, failureMessageID, null, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument)
{
SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageFormat, object failureMessageFormatArgument,
string failureArgumentName, Exception innerException)
{
Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
m_failure = failure;
m_resourceMessageFormat = failureMessageFormat;
m_failureMessageFormatArgument = failureMessageFormatArgument;
m_failureArgumentName = failureArgumentName;
m_innerException = innerException;
if (throwStyle != GuidParseThrowStyle.None)
{
throw GetGuidParseException();
}
}
internal Exception GetGuidParseException()
{
switch (m_failure)
{
case ParseFailureKind.ArgumentNull:
return new ArgumentNullException(m_failureArgumentName, m_resourceMessageFormat);
case ParseFailureKind.FormatWithInnerException:
return new FormatException(m_resourceMessageFormat, m_innerException);
case ParseFailureKind.FormatWithParameter:
return new FormatException(SR.Format(m_resourceMessageFormat, m_failureMessageFormatArgument));
case ParseFailureKind.Format:
return new FormatException(m_resourceMessageFormat);
case ParseFailureKind.NativeException:
return m_innerException;
default:
Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure);
return new FormatException(SR.Format_GuidUnrecognized);
}
}
}
// Creates a new guid based on the value in the string. The value is made up
// of hex digits speared by the dash ("-"). The string may begin and end with
// brackets ("{", "}").
//
// The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where
// d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4,
// then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223"
//
public Guid(String g)
{
if (g == null)
{
throw new ArgumentNullException(nameof(g));
}
Contract.EndContractBlock();
this = Guid.Empty;
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.All);
if (TryParseGuid(g, GuidStyles.Any, ref result))
{
this = result.parsedGuid;
}
else
{
throw result.GetGuidParseException();
}
}
public static Guid Parse(String input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Contract.EndContractBlock();
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, GuidStyles.Any, ref result))
{
return result.parsedGuid;
}
else
{
throw result.GetGuidParseException();
}
}
public static bool TryParse(String input, out Guid result)
{
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, GuidStyles.Any, ref parseResult))
{
result = parseResult.parsedGuid;
return true;
}
else
{
result = Guid.Empty;
return false;
}
}
public static Guid ParseExact(String input, String format)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (format == null)
throw new ArgumentNullException(nameof(format));
if (format.Length != 1)
{
// all acceptable format strings are of length 1
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd')
{
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n')
{
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b')
{
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p')
{
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x')
{
style = GuidStyles.HexFormat;
}
else
{
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, style, ref result))
{
return result.parsedGuid;
}
else
{
throw result.GetGuidParseException();
}
}
public static bool TryParseExact(String input, String format, out Guid result)
{
if (format == null || format.Length != 1)
{
result = Guid.Empty;
return false;
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd')
{
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n')
{
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b')
{
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p')
{
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x')
{
style = GuidStyles.HexFormat;
}
else
{
// invalid guid format specification
result = Guid.Empty;
return false;
}
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, style, ref parseResult))
{
result = parseResult.parsedGuid;
return true;
}
else
{
result = Guid.Empty;
return false;
}
}
private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result)
{
if (g == null)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized);
return false;
}
String guidString = g.Trim(); //Remove Whitespace
if (guidString.Length == 0)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized);
return false;
}
// Check for dashes
bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0);
if (dashesExistInString)
{
if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0)
{
// dashes are not allowed
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized);
return false;
}
}
else
{
if ((flags & GuidStyles.RequireDashes) != 0)
{
// dashes are required
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized);
return false;
}
}
// Check for braces
bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0);
if (bracesExistInString)
{
if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0)
{
// braces are not allowed
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized);
return false;
}
}
else
{
if ((flags & GuidStyles.RequireBraces) != 0)
{
// braces are required
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized);
return false;
}
}
// Check for parenthesis
bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0);
if (parenthesisExistInString)
{
if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0)
{
// parenthesis are not allowed
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized);
return false;
}
}
else
{
if ((flags & GuidStyles.RequireParenthesis) != 0)
{
// parenthesis are required
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized);
return false;
}
}
try
{
// let's get on with the parsing
if (dashesExistInString)
{
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
return TryParseGuidWithDashes(guidString, ref result);
}
else if (bracesExistInString)
{
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
return TryParseGuidWithHexPrefix(guidString, ref result);
}
else
{
// Check if it's of the form dddddddddddddddddddddddddddddddd
return TryParseGuidWithNoStyle(guidString, ref result);
}
}
catch (IndexOutOfRangeException ex)
{
result.SetFailure(ParseFailureKind.FormatWithInnerException, SR.Format_GuidUnrecognized, null, null, ex);
return false;
}
catch (ArgumentException ex)
{
result.SetFailure(ParseFailureKind.FormatWithInnerException, SR.Format_GuidUnrecognized, null, null, ex);
return false;
}
}
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result)
{
int numStart = 0;
int numLen = 0;
// Eat all of the whitespace
guidString = EatAllWhitespace(guidString);
// Check for leading '{'
if (String.IsNullOrEmpty(guidString) || guidString[0] != '{')
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidBrace);
return false;
}
// Check for '0x'
if (!IsHexPrefix(guidString, 1))
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidHexPrefix, "{0xdddddddd, etc}");
return false;
}
// Find the end of this hex number (since it is not fixed length)
numStart = 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidComma);
return false;
}
if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
return false;
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidHexPrefix, "{0xdddddddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidComma);
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
return false;
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidHexPrefix, "{0xdddddddd, 0xdddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidComma);
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
return false;
// Check for '{'
if (guidString.Length <= numStart + numLen + 1 || guidString[numStart + numLen + 1] != '{')
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidBrace);
return false;
}
// Prepare for loop
numLen++;
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++)
{
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidHexPrefix, "{... { ... 0xdd, ...}}");
return false;
}
// +3 to get by ',0x' or '{0x' for first case
numStart = numStart + numLen + 3;
// Calculate number length
if (i < 7) // first 7 cases
{
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidComma);
return false;
}
}
else // last case ends with '}', not ','
{
numLen = guidString.IndexOf('}', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidBraceAfterLastNumber);
return false;
}
}
// Read in the number
uint number = (uint)ParseNumbers.StringToInt(guidString.Substring(numStart, numLen), 16, ParseNumbers.IsTight);
// check for overflow
if (number > 255)
{
result.SetFailure(ParseFailureKind.Format, SR.Overflow_Byte);
return false;
}
bytes[i] = (byte)number;
}
result.parsedGuid._d = bytes[0];
result.parsedGuid._e = bytes[1];
result.parsedGuid._f = bytes[2];
result.parsedGuid._g = bytes[3];
result.parsedGuid._h = bytes[4];
result.parsedGuid._i = bytes[5];
result.parsedGuid._j = bytes[6];
result.parsedGuid._k = bytes[7];
// Check for last '}'
if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}')
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidEndBrace);
return false;
}
// Check if we have extra characters at the end
if (numStart + numLen + 1 != guidString.Length - 1)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_ExtraJunkAtEnd);
return false;
}
return true;
}
// Check if it's of the form dddddddddddddddddddddddddddddddd
private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result)
{
int startPos = 0;
int temp;
long templ;
int currentPos = 0;
if (guidString.Length != 32)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen);
return false;
}
for (int i = 0; i < guidString.Length; i++)
{
char ch = guidString[i];
if (ch >= '0' && ch <= '9')
{
continue;
}
else
{
char upperCaseCh = Char.ToUpperInvariant(ch);
if (upperCaseCh >= 'A' && upperCaseCh <= 'F')
{
continue;
}
}
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvalidChar);
return false;
}
if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
return false;
startPos += 8;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
return false;
startPos += 4;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
return false;
startPos += 4;
if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result))
return false;
startPos += 4;
currentPos = startPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos != 12)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen);
return false;
}
result.parsedGuid._d = (byte)(temp >> 8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result.parsedGuid._f = (byte)(temp >> 8);
result.parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result.parsedGuid._h = (byte)(temp >> 24);
result.parsedGuid._i = (byte)(temp >> 16);
result.parsedGuid._j = (byte)(temp >> 8);
result.parsedGuid._k = (byte)(temp);
return true;
}
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result)
{
int startPos = 0;
int temp;
long templ;
int currentPos = 0;
// check to see that it's the proper length
if (guidString[0] == '{')
{
if (guidString.Length != 38 || guidString[37] != '}')
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen);
return false;
}
startPos = 1;
}
else if (guidString[0] == '(')
{
if (guidString.Length != 38 || guidString[37] != ')')
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen);
return false;
}
startPos = 1;
}
else if (guidString.Length != 36)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen);
return false;
}
if (guidString[8 + startPos] != '-' ||
guidString[13 + startPos] != '-' ||
guidString[18 + startPos] != '-' ||
guidString[23 + startPos] != '-')
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidDashes);
return false;
}
currentPos = startPos;
if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._a = temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._b = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._c = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
++currentPos; //Increment past the '-';
startPos = currentPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos != 12)
{
result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen);
return false;
}
result.parsedGuid._d = (byte)(temp >> 8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result.parsedGuid._f = (byte)(temp >> 8);
result.parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result.parsedGuid._h = (byte)(temp >> 24);
result.parsedGuid._i = (byte)(temp >> 16);
result.parsedGuid._j = (byte)(temp >> 8);
result.parsedGuid._k = (byte)(temp);
return true;
}
//
// StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines;
//
private static bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult)
{
int parsePos = 0;
return StringToShort(str, ref parsePos, requiredLength, flags, out result, ref parseResult);
}
private static bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult)
{
result = 0;
int x;
bool retValue = StringToInt(str, ref parsePos, requiredLength, flags, out x, ref parseResult);
result = (short)x;
return retValue;
}
private static bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult)
{
int parsePos = 0;
return StringToInt(str, ref parsePos, requiredLength, flags, out result, ref parseResult);
}
private static bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult)
{
result = 0;
int currStart = parsePos;
try
{
result = ParseNumbers.StringToInt(str, 16, flags, ref parsePos);
}
catch (OverflowException ex)
{
if (parseResult.throwStyle == GuidParseThrowStyle.All)
{
throw;
}
else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
{
throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
else
{
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex)
{
if (parseResult.throwStyle == GuidParseThrowStyle.None)
{
parseResult.SetFailure(ex);
return false;
}
else
{
throw;
}
}
//If we didn't parse enough characters, there's clearly an error.
if (requiredLength != -1 && parsePos - currStart != requiredLength)
{
parseResult.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvalidChar);
return false;
}
return true;
}
private static bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult)
{
result = 0;
try
{
result = ParseNumbers.StringToLong(str, 16, flags, ref parsePos);
}
catch (OverflowException ex)
{
if (parseResult.throwStyle == GuidParseThrowStyle.All)
{
throw;
}
else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
{
throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
else
{
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex)
{
if (parseResult.throwStyle == GuidParseThrowStyle.None)
{
parseResult.SetFailure(ex);
return false;
}
else
{
throw;
}
}
return true;
}
private static String EatAllWhitespace(String str)
{
int newLength = 0;
char[] chArr = new char[str.Length];
char curChar;
// Now get each char from str and if it is not whitespace add it to chArr
for (int i = 0; i < str.Length; i++)
{
curChar = str[i];
if (!Char.IsWhiteSpace(curChar))
{
chArr[newLength++] = curChar;
}
}
// Return a new string based on chArr
return new String(chArr, 0, newLength);
}
private static bool IsHexPrefix(String str, int i)
{
if (str.Length > i + 1 && str[i] == '0' && (Char.ToLowerInvariant(str[i + 1]) == 'x'))
return true;
else
return false;
}
// Returns an unsigned byte array containing the GUID.
public byte[] ToByteArray()
{
byte[] g = new byte[16];
g[0] = (byte)(_a);
g[1] = (byte)(_a >> 8);
g[2] = (byte)(_a >> 16);
g[3] = (byte)(_a >> 24);
g[4] = (byte)(_b);
g[5] = (byte)(_b >> 8);
g[6] = (byte)(_c);
g[7] = (byte)(_c >> 8);
g[8] = _d;
g[9] = _e;
g[10] = _f;
g[11] = _g;
g[12] = _h;
g[13] = _i;
g[14] = _j;
g[15] = _k;
return g;
}
// Returns the guid in "registry" format.
public override String ToString()
{
return ToString("D", null);
}
public unsafe override int GetHashCode()
{
// Simply XOR all the bits of the GUID 32 bits at a time.
fixed (int* ptr = &_a)
return ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3];
}
// Returns true if and only if the guid represented
// by o is the same as this instance.
public override bool Equals(Object o)
{
Guid g;
// Check that o is a Guid first
if (o == null || !(o is Guid))
return false;
else g = (Guid)o;
// Now compare each of the elements
if (g._a != _a)
return false;
if (g._b != _b)
return false;
if (g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
public bool Equals(Guid g)
{
// Now compare each of the elements
if (g._a != _a)
return false;
if (g._b != _b)
return false;
if (g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
internal bool Equals(ref Guid g)
{
// Now compare each of the elements
if (g._a != _a)
return false;
if (g._b != _b)
return false;
if (g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
private int GetResult(uint me, uint them)
{
if (me < them)
{
return -1;
}
return 1;
}
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (!(value is Guid))
{
throw new ArgumentException(SR.Arg_MustBeGuid, nameof(value));
}
Guid g = (Guid)value;
if (g._a != _a)
{
return GetResult((uint)_a, (uint)g._a);
}
if (g._b != _b)
{
return GetResult((uint)_b, (uint)g._b);
}
if (g._c != _c)
{
return GetResult((uint)_c, (uint)g._c);
}
if (g._d != _d)
{
return GetResult((uint)_d, (uint)g._d);
}
if (g._e != _e)
{
return GetResult((uint)_e, (uint)g._e);
}
if (g._f != _f)
{
return GetResult((uint)_f, (uint)g._f);
}
if (g._g != _g)
{
return GetResult((uint)_g, (uint)g._g);
}
if (g._h != _h)
{
return GetResult((uint)_h, (uint)g._h);
}
if (g._i != _i)
{
return GetResult((uint)_i, (uint)g._i);
}
if (g._j != _j)
{
return GetResult((uint)_j, (uint)g._j);
}
if (g._k != _k)
{
return GetResult((uint)_k, (uint)g._k);
}
return 0;
}
public int CompareTo(Guid value)
{
if (value._a != _a)
{
return GetResult((uint)_a, (uint)value._a);
}
if (value._b != _b)
{
return GetResult((uint)_b, (uint)value._b);
}
if (value._c != _c)
{
return GetResult((uint)_c, (uint)value._c);
}
if (value._d != _d)
{
return GetResult((uint)_d, (uint)value._d);
}
if (value._e != _e)
{
return GetResult((uint)_e, (uint)value._e);
}
if (value._f != _f)
{
return GetResult((uint)_f, (uint)value._f);
}
if (value._g != _g)
{
return GetResult((uint)_g, (uint)value._g);
}
if (value._h != _h)
{
return GetResult((uint)_h, (uint)value._h);
}
if (value._i != _i)
{
return GetResult((uint)_i, (uint)value._i);
}
if (value._j != _j)
{
return GetResult((uint)_j, (uint)value._j);
}
if (value._k != _k)
{
return GetResult((uint)_k, (uint)value._k);
}
return 0;
}
public static bool operator ==(Guid a, Guid b)
{
// Now compare each of the elements
if (a._a != b._a)
return false;
if (a._b != b._b)
return false;
if (a._c != b._c)
return false;
if (a._d != b._d)
return false;
if (a._e != b._e)
return false;
if (a._f != b._f)
return false;
if (a._g != b._g)
return false;
if (a._h != b._h)
return false;
if (a._i != b._i)
return false;
if (a._j != b._j)
return false;
if (a._k != b._k)
return false;
return true;
}
public static bool operator !=(Guid a, Guid b)
{
return !(a == b);
}
public String ToString(String format)
{
return ToString(format, null);
}
private static char HexToChar(int a)
{
a = a & 0xf;
return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30);
}
unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b)
{
return HexsToChars(guidChars, offset, a, b, false);
}
unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex)
{
if (hex)
{
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
}
guidChars[offset++] = HexToChar(a >> 4);
guidChars[offset++] = HexToChar(a);
if (hex)
{
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
}
guidChars[offset++] = HexToChar(b >> 4);
guidChars[offset++] = HexToChar(b);
return offset;
}
// IFormattable interface
// We currently ignore provider
public String ToString(String format, IFormatProvider provider)
{
if (format == null || format.Length == 0)
format = "D";
string guidString;
int offset = 0;
bool dash = true;
bool hex = false;
if (format.Length != 1)
{
// all acceptable format strings are of length 1
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd')
{
guidString = string.FastAllocateString(36);
}
else if (formatCh == 'N' || formatCh == 'n')
{
guidString = string.FastAllocateString(32);
dash = false;
}
else if (formatCh == 'B' || formatCh == 'b')
{
guidString = string.FastAllocateString(38);
unsafe
{
fixed (char* guidChars = guidString)
{
guidChars[offset++] = '{';
guidChars[37] = '}';
}
}
}
else if (formatCh == 'P' || formatCh == 'p')
{
guidString = string.FastAllocateString(38);
unsafe
{
fixed (char* guidChars = guidString)
{
guidChars[offset++] = '(';
guidChars[37] = ')';
}
}
}
else if (formatCh == 'X' || formatCh == 'x')
{
guidString = string.FastAllocateString(68);
unsafe
{
fixed (char* guidChars = guidString)
{
guidChars[offset++] = '{';
guidChars[67] = '}';
}
}
dash = false;
hex = true;
}
else
{
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
unsafe
{
fixed (char* guidChars = guidString)
{
if (hex)
{
// {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16);
offset = HexsToChars(guidChars, offset, _a >> 8, _a);
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset = HexsToChars(guidChars, offset, _b >> 8, _b);
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset = HexsToChars(guidChars, offset, _c >> 8, _c);
guidChars[offset++] = ',';
guidChars[offset++] = '{';
offset = HexsToChars(guidChars, offset, _d, _e, true);
guidChars[offset++] = ',';
offset = HexsToChars(guidChars, offset, _f, _g, true);
guidChars[offset++] = ',';
offset = HexsToChars(guidChars, offset, _h, _i, true);
guidChars[offset++] = ',';
offset = HexsToChars(guidChars, offset, _j, _k, true);
guidChars[offset++] = '}';
}
else
{
// [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)]
offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16);
offset = HexsToChars(guidChars, offset, _a >> 8, _a);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _b >> 8, _b);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _c >> 8, _c);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _d, _e);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _f, _g);
offset = HexsToChars(guidChars, offset, _h, _i);
offset = HexsToChars(guidChars, offset, _j, _k);
}
}
}
return guidString;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class Matrix3x2Tests
{
static Matrix3x2 GenerateMatrixNumberFrom1To6()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 1.0f;
a.M12 = 2.0f;
a.M21 = 3.0f;
a.M22 = 4.0f;
a.M31 = 5.0f;
a.M32 = 6.0f;
return a;
}
static Matrix3x2 GenerateTestMatrix()
{
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.Translation = new Vector2(111.0f, 222.0f);
return m;
}
// A test for Identity
[Fact]
public void Matrix3x2IdentityTest()
{
Matrix3x2 val = new Matrix3x2();
val.M11 = val.M22 = 1.0f;
Assert.True(MathHelper.Equal(val, Matrix3x2.Identity), "Matrix3x2.Indentity was not set correctly.");
}
// A test for Determinant
[Fact]
public void Matrix3x2DeterminantTest()
{
Matrix3x2 target = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
float val = 1.0f;
float det = target.GetDeterminant();
Assert.True(MathHelper.Equal(val, det), "Matrix3x2.Determinant was not set correctly.");
}
// A test for Determinant
// Determinant test |A| = 1 / |A'|
[Fact]
public void Matrix3x2DeterminantTest1()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 5.0f;
a.M12 = 2.0f;
a.M21 = 12.0f;
a.M22 = 6.8f;
a.M31 = 6.5f;
a.M32 = 1.0f;
Matrix3x2 i;
Assert.True(Matrix3x2.Invert(a, out i));
float detA = a.GetDeterminant();
float detI = i.GetDeterminant();
float t = 1.0f / detI;
// only accurate to 3 precision
Assert.True(System.Math.Abs(detA - t) < 1e-3, "Matrix3x2.Determinant was not set correctly.");
// sanity check against 4x4 version
Assert.Equal(new Matrix4x4(a).GetDeterminant(), detA);
Assert.Equal(new Matrix4x4(i).GetDeterminant(), detI);
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
Matrix3x2 expected = new Matrix3x2();
expected.M11 = 0.8660254f;
expected.M12 = -0.5f;
expected.M21 = 0.5f;
expected.M22 = 0.8660254f;
expected.M31 = 0;
expected.M32 = 0;
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.Invert did not return the expected value.");
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity), "Matrix3x2.Invert did not return the expected value.");
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertIdentityTest()
{
Matrix3x2 mtx = Matrix3x2.Identity;
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Assert.True(MathHelper.Equal(actual, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertTranslationTest()
{
Matrix3x2 mtx = Matrix3x2.CreateTranslation(23, 42);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertRotationTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(2);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertScaleTest()
{
Matrix3x2 mtx = Matrix3x2.CreateScale(23, -42);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertAffineTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(2) *
Matrix3x2.CreateScale(23, -42) *
Matrix3x2.CreateTranslation(17, 53);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for CreateRotation (float)
[Fact]
public void Matrix3x2CreateRotationTest()
{
float radians = MathHelper.ToRadians(50.0f);
Matrix3x2 expected = new Matrix3x2();
expected.M11 = 0.642787635f;
expected.M12 = 0.766044438f;
expected.M21 = -0.766044438f;
expected.M22 = 0.642787635f;
Matrix3x2 actual;
actual = Matrix3x2.CreateRotation(radians);
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.CreateRotation did not return the expected value.");
}
// A test for CreateRotation (float, Vector2f)
[Fact]
public void Matrix3x2CreateRotationCenterTest()
{
float radians = MathHelper.ToRadians(30.0f);
Vector2 center = new Vector2(23, 42);
Matrix3x2 rotateAroundZero = Matrix3x2.CreateRotation(radians, Vector2.Zero);
Matrix3x2 rotateAroundZeroExpected = Matrix3x2.CreateRotation(radians);
Assert.True(MathHelper.Equal(rotateAroundZero, rotateAroundZeroExpected));
Matrix3x2 rotateAroundCenter = Matrix3x2.CreateRotation(radians, center);
Matrix3x2 rotateAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateRotation(radians) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(rotateAroundCenter, rotateAroundCenterExpected));
}
// A test for CreateRotation (float)
[Fact]
public void Matrix3x2CreateRotationRightAngleTest()
{
// 90 degree rotations must be exact!
Matrix3x2 actual = Matrix3x2.CreateRotation(0);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi);
Assert.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, 0, 0), actual);
// But merely close-to-90 rotations should not be excessively clamped.
float delta = MathHelper.ToRadians(0.01f);
actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual));
actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual));
}
// A test for CreateRotation (float, Vector2f)
[Fact]
public void Matrix3x2CreateRotationRightAngleCenterTest()
{
Vector2 center = new Vector2(3, 7);
// 90 degree rotations must be exact!
Matrix3x2 actual = Matrix3x2.CreateRotation(0, center);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2, center);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 10, 4), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi, center);
Assert.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2, center);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, -4, 10), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2, center);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2, center);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 10, 4), actual);
actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2, center);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, -4, 10), actual);
// But merely close-to-90 rotations should not be excessively clamped.
float delta = MathHelper.ToRadians(0.01f);
actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta, center);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual));
actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta, center);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual));
}
// A test for Invert (Matrix3x2)
// Non invertible matrix - determinant is zero - singular matrix
[Fact]
public void Matrix3x2InvertTest1()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 0.0f;
a.M12 = 2.0f;
a.M21 = 0.0f;
a.M22 = 4.0f;
a.M31 = 5.0f;
a.M32 = 6.0f;
float detA = a.GetDeterminant();
Assert.True(MathHelper.Equal(detA, 0.0f), "Matrix3x2.Invert did not return the expected value.");
Matrix3x2 actual;
Assert.False(Matrix3x2.Invert(a, out actual));
// all the elements in Actual is NaN
Assert.True(
float.IsNaN(actual.M11) && float.IsNaN(actual.M12) &&
float.IsNaN(actual.M21) && float.IsNaN(actual.M22) &&
float.IsNaN(actual.M31) && float.IsNaN(actual.M32)
, "Matrix3x2.Invert did not return the expected value.");
}
// A test for Lerp (Matrix3x2, Matrix3x2, float)
[Fact]
public void Matrix3x2LerpTest()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 11.0f;
a.M12 = 12.0f;
a.M21 = 21.0f;
a.M22 = 22.0f;
a.M31 = 31.0f;
a.M32 = 32.0f;
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
float t = 0.5f;
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + (b.M11 - a.M11) * t;
expected.M12 = a.M12 + (b.M12 - a.M12) * t;
expected.M21 = a.M21 + (b.M21 - a.M21) * t;
expected.M22 = a.M22 + (b.M22 - a.M22) * t;
expected.M31 = a.M31 + (b.M31 - a.M31) * t;
expected.M32 = a.M32 + (b.M32 - a.M32) * t;
Matrix3x2 actual;
actual = Matrix3x2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.Lerp did not return the expected value.");
}
// A test for operator - (Matrix3x2)
[Fact]
public void Matrix3x2UnaryNegationTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = -1.0f;
expected.M12 = -2.0f;
expected.M21 = -3.0f;
expected.M22 = -4.0f;
expected.M31 = -5.0f;
expected.M32 = -6.0f;
Matrix3x2 actual = -a;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value.");
}
// A test for operator - (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2SubtractionTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
Matrix3x2 actual = a - b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value.");
}
// A test for operator * (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2MultiplyTest1()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 * b.M11 + a.M12 * b.M21;
expected.M12 = a.M11 * b.M12 + a.M12 * b.M22;
expected.M21 = a.M21 * b.M11 + a.M22 * b.M21;
expected.M22 = a.M21 * b.M12 + a.M22 * b.M22;
expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31;
expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32;
Matrix3x2 actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value.");
// Sanity check by comparison with 4x4 multiply.
a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42);
b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1);
actual = a * b;
Matrix4x4 a44 = new Matrix4x4(a);
Matrix4x4 b44 = new Matrix4x4(b);
Matrix4x4 expected44 = a44 * b44;
Matrix4x4 actual44 = new Matrix4x4(actual);
Assert.True(MathHelper.Equal(expected44, actual44), "Matrix3x2.operator * did not return the expected value.");
}
// A test for operator * (Matrix3x2, Matrix3x2)
// Multiply with identity matrix
[Fact]
public void Matrix3x2MultiplyTest4()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 1.0f;
a.M12 = 2.0f;
a.M21 = 5.0f;
a.M22 = -6.0f;
a.M31 = 9.0f;
a.M32 = 10.0f;
Matrix3x2 b = new Matrix3x2();
b = Matrix3x2.Identity;
Matrix3x2 expected = a;
Matrix3x2 actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value.");
}
// A test for operator + (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2AdditionTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + b.M11;
expected.M12 = a.M12 + b.M12;
expected.M21 = a.M21 + b.M21;
expected.M22 = a.M22 + b.M22;
expected.M31 = a.M31 + b.M31;
expected.M32 = a.M32 + b.M32;
Matrix3x2 actual;
actual = a + b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator + did not return the expected value.");
}
// A test for ToString ()
[Fact]
public void Matrix3x2ToStringTest()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 11.0f;
a.M12 = -12.0f;
a.M21 = 21.0f;
a.M22 = 22.0f;
a.M31 = 31.0f;
a.M32 = 32.0f;
string expected = "{ {M11:11 M12:-12} " +
"{M21:21 M22:22} " +
"{M31:31 M32:32} }";
string actual;
actual = a.ToString();
Assert.Equal(expected, actual);
}
// A test for Add (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2AddTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + b.M11;
expected.M12 = a.M12 + b.M12;
expected.M21 = a.M21 + b.M21;
expected.M22 = a.M22 + b.M22;
expected.M31 = a.M31 + b.M31;
expected.M32 = a.M32 + b.M32;
Matrix3x2 actual;
actual = Matrix3x2.Add(a, b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void Matrix3x2EqualsTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Vector4();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for GetHashCode ()
[Fact]
public void Matrix3x2GetHashCodeTest()
{
Matrix3x2 target = GenerateMatrixNumberFrom1To6();
int expected = target.M11.GetHashCode() + target.M12.GetHashCode() +
target.M21.GetHashCode() + target.M22.GetHashCode() +
target.M31.GetHashCode() + target.M32.GetHashCode();
int actual;
actual = target.GetHashCode();
Assert.Equal(expected, actual);
}
// A test for Multiply (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2MultiplyTest3()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 * b.M11 + a.M12 * b.M21;
expected.M12 = a.M11 * b.M12 + a.M12 * b.M22;
expected.M21 = a.M21 * b.M11 + a.M22 * b.M21;
expected.M22 = a.M21 * b.M12 + a.M22 * b.M22;
expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31;
expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32;
Matrix3x2 actual;
actual = Matrix3x2.Multiply(a, b);
Assert.Equal(expected, actual);
// Sanity check by comparison with 4x4 multiply.
a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42);
b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1);
actual = Matrix3x2.Multiply(a, b);
Matrix4x4 a44 = new Matrix4x4(a);
Matrix4x4 b44 = new Matrix4x4(b);
Matrix4x4 expected44 = Matrix4x4.Multiply(a44, b44);
Matrix4x4 actual44 = new Matrix4x4(actual);
Assert.True(MathHelper.Equal(expected44, actual44), "Matrix3x2.Multiply did not return the expected value.");
}
// A test for Multiply (Matrix3x2, float)
[Fact]
public void Matrix3x2MultiplyTest5()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18);
Matrix3x2 actual = Matrix3x2.Multiply(a, 3);
Assert.Equal(expected, actual);
}
// A test for Multiply (Matrix3x2, float)
[Fact]
public void Matrix3x2MultiplyTest6()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18);
Matrix3x2 actual = a * 3;
Assert.Equal(expected, actual);
}
// A test for Negate (Matrix3x2)
[Fact]
public void Matrix3x2NegateTest()
{
Matrix3x2 m = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = -1.0f;
expected.M12 = -2.0f;
expected.M21 = -3.0f;
expected.M22 = -4.0f;
expected.M31 = -5.0f;
expected.M32 = -6.0f;
Matrix3x2 actual;
actual = Matrix3x2.Negate(m);
Assert.Equal(expected, actual);
}
// A test for operator != (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2InequalityTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2EqualityTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for Subtract (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2SubtractTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
Matrix3x2 actual;
actual = Matrix3x2.Subtract(a, b);
Assert.Equal(expected, actual);
}
// A test for CreateScale (Vector2f)
[Fact]
public void Matrix3x2CreateScaleTest1()
{
Vector2 scales = new Vector2(2.0f, 3.0f);
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 3.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(scales);
Assert.Equal(expected, actual);
}
// A test for CreateScale (Vector2f, Vector2f)
[Fact]
public void Matrix3x2CreateScaleCenterTest1()
{
Vector2 scale = new Vector2(3, 4);
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale);
Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateScale (float)
[Fact]
public void Matrix3x2CreateScaleTest2()
{
float scale = 2.0f;
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 2.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(scale);
Assert.Equal(expected, actual);
}
// A test for CreateScale (float, Vector2f)
[Fact]
public void Matrix3x2CreateScaleCenterTest2()
{
float scale = 5;
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale);
Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateScale (float, float)
[Fact]
public void Matrix3x2CreateScaleTest3()
{
float xScale = 2.0f;
float yScale = 3.0f;
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 3.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(xScale, yScale);
Assert.Equal(expected, actual);
}
// A test for CreateScale (float, float, Vector2f)
[Fact]
public void Matrix3x2CreateScaleCenterTest3()
{
Vector2 scale = new Vector2(3, 4);
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale.X, scale.Y, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale.X, scale.Y);
Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale.X, scale.Y, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale.X, scale.Y) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateTranslation (Vector2f)
[Fact]
public void Matrix3x2CreateTranslationTest1()
{
Vector2 position = new Vector2(2.0f, 3.0f);
Matrix3x2 expected = new Matrix3x2(
1.0f, 0.0f,
0.0f, 1.0f,
2.0f, 3.0f);
Matrix3x2 actual = Matrix3x2.CreateTranslation(position);
Assert.Equal(expected, actual);
}
// A test for CreateTranslation (float, float)
[Fact]
public void Matrix3x2CreateTranslationTest2()
{
float xPosition = 2.0f;
float yPosition = 3.0f;
Matrix3x2 expected = new Matrix3x2(
1.0f, 0.0f,
0.0f, 1.0f,
2.0f, 3.0f);
Matrix3x2 actual = Matrix3x2.CreateTranslation(xPosition, yPosition);
Assert.Equal(expected, actual);
}
// A test for Translation
[Fact]
public void Matrix3x2TranslationTest()
{
Matrix3x2 a = GenerateTestMatrix();
Matrix3x2 b = a;
// Transfomed vector that has same semantics of property must be same.
Vector2 val = new Vector2(a.M31, a.M32);
Assert.Equal(val, a.Translation);
// Set value and get value must be same.
val = new Vector2(1.0f, 2.0f);
a.Translation = val;
Assert.Equal(val, a.Translation);
// Make sure it only modifies expected value of matrix.
Assert.True(
a.M11 == b.M11 && a.M12 == b.M12 &&
a.M21 == b.M21 && a.M22 == b.M22 &&
a.M31 != b.M31 && a.M32 != b.M32,
"Matrix3x2.Translation modified unexpected value of matrix.");
}
// A test for Equals (Matrix3x2)
[Fact]
public void Matrix3x2EqualsTest1()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewIdentityTest()
{
Matrix3x2 expected = Matrix3x2.Identity;
Matrix3x2 actual = Matrix3x2.CreateSkew(0, 0);
Assert.Equal(expected, actual);
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewXTest()
{
Matrix3x2 expected = new Matrix3x2(1, 0, -0.414213562373095f, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(-MathHelper.Pi / 8, 0);
Assert.True(MathHelper.Equal(expected, actual));
expected = new Matrix3x2(1, 0, 0.414213562373095f, 1, 0, 0);
actual = Matrix3x2.CreateSkew(MathHelper.Pi / 8, 0);
Assert.True(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(0, 1), actual);
Assert.True(MathHelper.Equal(new Vector2(0.414213568f, 1), result));
result = Vector2.Transform(new Vector2(0, -1), actual);
Assert.True(MathHelper.Equal(new Vector2(-0.414213568f, -1), result));
result = Vector2.Transform(new Vector2(3, 10), actual);
Assert.True(MathHelper.Equal(new Vector2(7.14213568f, 10), result));
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewYTest()
{
Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 0, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(0, -MathHelper.Pi / 8);
Assert.True(MathHelper.Equal(expected, actual));
expected = new Matrix3x2(1, 0.414213562373095f, 0, 1, 0, 0);
actual = Matrix3x2.CreateSkew(0, MathHelper.Pi / 8);
Assert.True(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(1, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(1, 0.414213568f), result));
result = Vector2.Transform(new Vector2(-1, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(-1, -0.414213568f), result));
result = Vector2.Transform(new Vector2(10, 3), actual);
Assert.True(MathHelper.Equal(new Vector2(10, 7.14213568f), result));
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewXYTest()
{
Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 1, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(MathHelper.Pi / 4, -MathHelper.Pi / 8);
Assert.True(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(1, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(1, -0.414213562373095f), result));
result = Vector2.Transform(new Vector2(0, 1), actual);
Assert.True(MathHelper.Equal(new Vector2(1, 1), result));
result = Vector2.Transform(new Vector2(1, 1), actual);
Assert.True(MathHelper.Equal(new Vector2(2, 0.585786437626905f), result));
}
// A test for CreateSkew (float, float, Vector2f)
[Fact]
public void Matrix3x2CreateSkewCenterTest()
{
float skewX = 1, skewY = 2;
Vector2 center = new Vector2(23, 42);
Matrix3x2 skewAroundZero = Matrix3x2.CreateSkew(skewX, skewY, Vector2.Zero);
Matrix3x2 skewAroundZeroExpected = Matrix3x2.CreateSkew(skewX, skewY);
Assert.True(MathHelper.Equal(skewAroundZero, skewAroundZeroExpected));
Matrix3x2 skewAroundCenter = Matrix3x2.CreateSkew(skewX, skewY, center);
Matrix3x2 skewAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateSkew(skewX, skewY) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(skewAroundCenter, skewAroundCenterExpected));
}
// A test for IsIdentity
[Fact]
public void Matrix3x2IsIdentityTest()
{
Assert.True(Matrix3x2.Identity.IsIdentity);
Assert.True(new Matrix3x2(1, 0, 0, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(0, 0, 0, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 1, 0, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 1, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 0, 0, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 0, 1, 1, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 0, 1, 0, 1).IsIdentity);
}
// A test for Matrix3x2 comparison involving NaN values
[Fact]
public void Matrix3x2EqualsNanTest()
{
Matrix3x2 a = new Matrix3x2(float.NaN, 0, 0, 0, 0, 0);
Matrix3x2 b = new Matrix3x2(0, float.NaN, 0, 0, 0, 0);
Matrix3x2 c = new Matrix3x2(0, 0, float.NaN, 0, 0, 0);
Matrix3x2 d = new Matrix3x2(0, 0, 0, float.NaN, 0, 0);
Matrix3x2 e = new Matrix3x2(0, 0, 0, 0, float.NaN, 0);
Matrix3x2 f = new Matrix3x2(0, 0, 0, 0, 0, float.NaN);
Assert.False(a == new Matrix3x2());
Assert.False(b == new Matrix3x2());
Assert.False(c == new Matrix3x2());
Assert.False(d == new Matrix3x2());
Assert.False(e == new Matrix3x2());
Assert.False(f == new Matrix3x2());
Assert.True(a != new Matrix3x2());
Assert.True(b != new Matrix3x2());
Assert.True(c != new Matrix3x2());
Assert.True(d != new Matrix3x2());
Assert.True(e != new Matrix3x2());
Assert.True(f != new Matrix3x2());
Assert.False(a.Equals(new Matrix3x2()));
Assert.False(b.Equals(new Matrix3x2()));
Assert.False(c.Equals(new Matrix3x2()));
Assert.False(d.Equals(new Matrix3x2()));
Assert.False(e.Equals(new Matrix3x2()));
Assert.False(f.Equals(new Matrix3x2()));
Assert.False(a.IsIdentity);
Assert.False(b.IsIdentity);
Assert.False(c.IsIdentity);
Assert.False(d.IsIdentity);
Assert.False(e.IsIdentity);
Assert.False(f.IsIdentity);
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
Assert.False(c.Equals(c));
Assert.False(d.Equals(d));
Assert.False(e.Equals(e));
Assert.False(f.Equals(f));
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void Matrix3x2SizeofTest()
{
Assert.Equal(24, sizeof(Matrix3x2));
Assert.Equal(48, sizeof(Matrix3x2_2x));
Assert.Equal(28, sizeof(Matrix3x2PlusFloat));
Assert.Equal(56, sizeof(Matrix3x2PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2_2x
{
private Matrix3x2 _a;
private Matrix3x2 _b;
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2PlusFloat
{
private Matrix3x2 _v;
private float _f;
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2PlusFloat_2x
{
private Matrix3x2PlusFloat _a;
private Matrix3x2PlusFloat _b;
}
//// A test to make sure the fields are laid out how we expect
//[Fact]
//public unsafe void Matrix3x2FieldOffsetTest()
//{
// Matrix3x2* ptr = (Matrix3x2*)0;
// Assert.Equal(new IntPtr(0), new IntPtr(&ptr->M11));
// Assert.Equal(new IntPtr(4), new IntPtr(&ptr->M12));
// Assert.Equal(new IntPtr(8), new IntPtr(&ptr->M21));
// Assert.Equal(new IntPtr(12), new IntPtr(&ptr->M22));
// Assert.Equal(new IntPtr(16), new IntPtr(&ptr->M31));
// Assert.Equal(new IntPtr(20), new IntPtr(&ptr->M32));
//}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Rooms
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SM : EduHubEntity
{
#region Navigation Property Cache
private KSF Cache_FACULTY_KSF;
private SCI Cache_CAMPUS_SCI;
private SF Cache_STAFF_CODE_SF;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<KGC> Cache_ROOM_KGC_ROOM;
private IReadOnlyList<SAD> Cache_ROOM_SAD_ROOM;
private IReadOnlyList<SCAM> Cache_ROOM_SCAM_MEETING_ROOM;
private IReadOnlyList<SCL> Cache_ROOM_SCL_ROOM01;
private IReadOnlyList<SCL> Cache_ROOM_SCL_ROOM02;
private IReadOnlyList<SF> Cache_ROOM_SF_ROOM;
private IReadOnlyList<SF> Cache_ROOM_SF_OTHER_LOCATION;
private IReadOnlyList<SGM> Cache_ROOM_SGM_MEETING_ROOM;
private IReadOnlyList<SMAQ> Cache_ROOM_SMAQ_SMAQKEY;
private IReadOnlyList<SMAV> Cache_ROOM_SMAV_ROOM;
private IReadOnlyList<SMGROUP> Cache_ROOM_SMGROUP_GROUPKEY;
private IReadOnlyList<SMGROUP> Cache_ROOM_SMGROUP_ROOM;
private IReadOnlyList<TCTB> Cache_ROOM_TCTB_ROOM;
private IReadOnlyList<TCTQ> Cache_ROOM_TCTQ_R1ROOM;
private IReadOnlyList<TCTQ> Cache_ROOM_TCTQ_R2ROOM;
private IReadOnlyList<TCTQ> Cache_ROOM_TCTQ_EXTRA_ROOM;
private IReadOnlyList<TCTR> Cache_ROOM_TCTR_ROOM;
private IReadOnlyList<TE> Cache_ROOM_TE_LOCATION;
private IReadOnlyList<TETE> Cache_ROOM_TETE_LOCATION;
private IReadOnlyList<THTQ> Cache_ROOM_THTQ_R1ROOM;
private IReadOnlyList<THTQ> Cache_ROOM_THTQ_R2ROOM;
private IReadOnlyList<THTQ> Cache_ROOM_THTQ_EXTRA_ROOM;
private IReadOnlyList<TTEF> Cache_ROOM_TTEF_ROOM;
private IReadOnlyList<TTEX> Cache_ROOM_TTEX_EXAM_ROOM;
private IReadOnlyList<TTTG> Cache_ROOM_TTTG_R1ROOM;
private IReadOnlyList<TTTG> Cache_ROOM_TTTG_R2ROOM;
private IReadOnlyList<TXAS> Cache_ROOM_TXAS_LOCATION;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Room code
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string ROOM { get; internal set; }
/// <summary>
/// Room name
/// [Alphanumeric (30)]
/// </summary>
public string TITLE { get; internal set; }
/// <summary>
/// Maximum capacity
/// </summary>
public short? SEATING { get; internal set; }
/// <summary>
/// Description of room
/// [Alphanumeric (40)]
/// </summary>
public string DESCRIPTION { get; internal set; }
/// <summary>
/// Is this room available for timetabled activities? R=available, otherwise not
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string ROOM_TYPE { get; internal set; }
/// <summary>
/// Code of the faculty responsible for this room
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string FACULTY { get; internal set; }
/// <summary>
/// (V) (NRM) << What exactly is this field for?
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string AREA_CODE { get; internal set; }
/// <summary>
/// ID of the campus on which this room is located
/// </summary>
public int? CAMPUS { get; internal set; }
/// <summary>
/// Code of the staff member responsible for this room (V) (NRM)
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string STAFF_CODE { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Memo]
/// </summary>
public string COMMENTA { get; internal set; }
/// <summary>
/// Type of board provided (blackboard, whiteboard, etc.)
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string BOARD { get; internal set; }
/// <summary>
/// Does this room have blackout provision? (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string BLACKOUT { get; internal set; }
/// <summary>
/// Normal load for this room
/// </summary>
public short? NORMAL_ALLOTMENT { get; internal set; }
/// <summary>
/// Flag indicating if this is a single room or a group of rooms
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string GROUP_INDICATOR { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// KSF (Faculties) related entity by [SM.FACULTY]->[KSF.KSFKEY]
/// Code of the faculty responsible for this room
/// </summary>
public KSF FACULTY_KSF
{
get
{
if (FACULTY == null)
{
return null;
}
if (Cache_FACULTY_KSF == null)
{
Cache_FACULTY_KSF = Context.KSF.FindByKSFKEY(FACULTY);
}
return Cache_FACULTY_KSF;
}
}
/// <summary>
/// SCI (School Information) related entity by [SM.CAMPUS]->[SCI.SCIKEY]
/// ID of the campus on which this room is located
/// </summary>
public SCI CAMPUS_SCI
{
get
{
if (CAMPUS == null)
{
return null;
}
if (Cache_CAMPUS_SCI == null)
{
Cache_CAMPUS_SCI = Context.SCI.FindBySCIKEY(CAMPUS.Value);
}
return Cache_CAMPUS_SCI;
}
}
/// <summary>
/// SF (Staff) related entity by [SM.STAFF_CODE]->[SF.SFKEY]
/// Code of the staff member responsible for this room (V) (NRM)
/// </summary>
public SF STAFF_CODE_SF
{
get
{
if (STAFF_CODE == null)
{
return null;
}
if (Cache_STAFF_CODE_SF == null)
{
Cache_STAFF_CODE_SF = Context.SF.FindBySFKEY(STAFF_CODE);
}
return Cache_STAFF_CODE_SF;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// KGC (Home Groups) related entities by [SM.ROOM]->[KGC.ROOM]
/// Room code
/// </summary>
public IReadOnlyList<KGC> ROOM_KGC_ROOM
{
get
{
if (Cache_ROOM_KGC_ROOM == null &&
!Context.KGC.TryFindByROOM(ROOM, out Cache_ROOM_KGC_ROOM))
{
Cache_ROOM_KGC_ROOM = new List<KGC>().AsReadOnly();
}
return Cache_ROOM_KGC_ROOM;
}
}
/// <summary>
/// SAD (Accidents) related entities by [SM.ROOM]->[SAD.ROOM]
/// Room code
/// </summary>
public IReadOnlyList<SAD> ROOM_SAD_ROOM
{
get
{
if (Cache_ROOM_SAD_ROOM == null &&
!Context.SAD.TryFindByROOM(ROOM, out Cache_ROOM_SAD_ROOM))
{
Cache_ROOM_SAD_ROOM = new List<SAD>().AsReadOnly();
}
return Cache_ROOM_SAD_ROOM;
}
}
/// <summary>
/// SCAM (School Association Meetings) related entities by [SM.ROOM]->[SCAM.MEETING_ROOM]
/// Room code
/// </summary>
public IReadOnlyList<SCAM> ROOM_SCAM_MEETING_ROOM
{
get
{
if (Cache_ROOM_SCAM_MEETING_ROOM == null &&
!Context.SCAM.TryFindByMEETING_ROOM(ROOM, out Cache_ROOM_SCAM_MEETING_ROOM))
{
Cache_ROOM_SCAM_MEETING_ROOM = new List<SCAM>().AsReadOnly();
}
return Cache_ROOM_SCAM_MEETING_ROOM;
}
}
/// <summary>
/// SCL (Subject Classes) related entities by [SM.ROOM]->[SCL.ROOM01]
/// Room code
/// </summary>
public IReadOnlyList<SCL> ROOM_SCL_ROOM01
{
get
{
if (Cache_ROOM_SCL_ROOM01 == null &&
!Context.SCL.TryFindByROOM01(ROOM, out Cache_ROOM_SCL_ROOM01))
{
Cache_ROOM_SCL_ROOM01 = new List<SCL>().AsReadOnly();
}
return Cache_ROOM_SCL_ROOM01;
}
}
/// <summary>
/// SCL (Subject Classes) related entities by [SM.ROOM]->[SCL.ROOM02]
/// Room code
/// </summary>
public IReadOnlyList<SCL> ROOM_SCL_ROOM02
{
get
{
if (Cache_ROOM_SCL_ROOM02 == null &&
!Context.SCL.TryFindByROOM02(ROOM, out Cache_ROOM_SCL_ROOM02))
{
Cache_ROOM_SCL_ROOM02 = new List<SCL>().AsReadOnly();
}
return Cache_ROOM_SCL_ROOM02;
}
}
/// <summary>
/// SF (Staff) related entities by [SM.ROOM]->[SF.ROOM]
/// Room code
/// </summary>
public IReadOnlyList<SF> ROOM_SF_ROOM
{
get
{
if (Cache_ROOM_SF_ROOM == null &&
!Context.SF.TryFindByROOM(ROOM, out Cache_ROOM_SF_ROOM))
{
Cache_ROOM_SF_ROOM = new List<SF>().AsReadOnly();
}
return Cache_ROOM_SF_ROOM;
}
}
/// <summary>
/// SF (Staff) related entities by [SM.ROOM]->[SF.OTHER_LOCATION]
/// Room code
/// </summary>
public IReadOnlyList<SF> ROOM_SF_OTHER_LOCATION
{
get
{
if (Cache_ROOM_SF_OTHER_LOCATION == null &&
!Context.SF.TryFindByOTHER_LOCATION(ROOM, out Cache_ROOM_SF_OTHER_LOCATION))
{
Cache_ROOM_SF_OTHER_LOCATION = new List<SF>().AsReadOnly();
}
return Cache_ROOM_SF_OTHER_LOCATION;
}
}
/// <summary>
/// SGM (Special Group Meetings) related entities by [SM.ROOM]->[SGM.MEETING_ROOM]
/// Room code
/// </summary>
public IReadOnlyList<SGM> ROOM_SGM_MEETING_ROOM
{
get
{
if (Cache_ROOM_SGM_MEETING_ROOM == null &&
!Context.SGM.TryFindByMEETING_ROOM(ROOM, out Cache_ROOM_SGM_MEETING_ROOM))
{
Cache_ROOM_SGM_MEETING_ROOM = new List<SGM>().AsReadOnly();
}
return Cache_ROOM_SGM_MEETING_ROOM;
}
}
/// <summary>
/// SMAQ (Room Availability in Quilt) related entities by [SM.ROOM]->[SMAQ.SMAQKEY]
/// Room code
/// </summary>
public IReadOnlyList<SMAQ> ROOM_SMAQ_SMAQKEY
{
get
{
if (Cache_ROOM_SMAQ_SMAQKEY == null &&
!Context.SMAQ.TryFindBySMAQKEY(ROOM, out Cache_ROOM_SMAQ_SMAQKEY))
{
Cache_ROOM_SMAQ_SMAQKEY = new List<SMAQ>().AsReadOnly();
}
return Cache_ROOM_SMAQ_SMAQKEY;
}
}
/// <summary>
/// SMAV (Room Availablity Extras) related entities by [SM.ROOM]->[SMAV.ROOM]
/// Room code
/// </summary>
public IReadOnlyList<SMAV> ROOM_SMAV_ROOM
{
get
{
if (Cache_ROOM_SMAV_ROOM == null &&
!Context.SMAV.TryFindByROOM(ROOM, out Cache_ROOM_SMAV_ROOM))
{
Cache_ROOM_SMAV_ROOM = new List<SMAV>().AsReadOnly();
}
return Cache_ROOM_SMAV_ROOM;
}
}
/// <summary>
/// SMGROUP (Rooms group) related entities by [SM.ROOM]->[SMGROUP.GROUPKEY]
/// Room code
/// </summary>
public IReadOnlyList<SMGROUP> ROOM_SMGROUP_GROUPKEY
{
get
{
if (Cache_ROOM_SMGROUP_GROUPKEY == null &&
!Context.SMGROUP.TryFindByGROUPKEY(ROOM, out Cache_ROOM_SMGROUP_GROUPKEY))
{
Cache_ROOM_SMGROUP_GROUPKEY = new List<SMGROUP>().AsReadOnly();
}
return Cache_ROOM_SMGROUP_GROUPKEY;
}
}
/// <summary>
/// SMGROUP (Rooms group) related entities by [SM.ROOM]->[SMGROUP.ROOM]
/// Room code
/// </summary>
public IReadOnlyList<SMGROUP> ROOM_SMGROUP_ROOM
{
get
{
if (Cache_ROOM_SMGROUP_ROOM == null &&
!Context.SMGROUP.TryFindByROOM(ROOM, out Cache_ROOM_SMGROUP_ROOM))
{
Cache_ROOM_SMGROUP_ROOM = new List<SMGROUP>().AsReadOnly();
}
return Cache_ROOM_SMGROUP_ROOM;
}
}
/// <summary>
/// TCTB (Teacher Absences) related entities by [SM.ROOM]->[TCTB.ROOM]
/// Room code
/// </summary>
public IReadOnlyList<TCTB> ROOM_TCTB_ROOM
{
get
{
if (Cache_ROOM_TCTB_ROOM == null &&
!Context.TCTB.TryFindByROOM(ROOM, out Cache_ROOM_TCTB_ROOM))
{
Cache_ROOM_TCTB_ROOM = new List<TCTB>().AsReadOnly();
}
return Cache_ROOM_TCTB_ROOM;
}
}
/// <summary>
/// TCTQ (Calendar Class Information) related entities by [SM.ROOM]->[TCTQ.R1ROOM]
/// Room code
/// </summary>
public IReadOnlyList<TCTQ> ROOM_TCTQ_R1ROOM
{
get
{
if (Cache_ROOM_TCTQ_R1ROOM == null &&
!Context.TCTQ.TryFindByR1ROOM(ROOM, out Cache_ROOM_TCTQ_R1ROOM))
{
Cache_ROOM_TCTQ_R1ROOM = new List<TCTQ>().AsReadOnly();
}
return Cache_ROOM_TCTQ_R1ROOM;
}
}
/// <summary>
/// TCTQ (Calendar Class Information) related entities by [SM.ROOM]->[TCTQ.R2ROOM]
/// Room code
/// </summary>
public IReadOnlyList<TCTQ> ROOM_TCTQ_R2ROOM
{
get
{
if (Cache_ROOM_TCTQ_R2ROOM == null &&
!Context.TCTQ.TryFindByR2ROOM(ROOM, out Cache_ROOM_TCTQ_R2ROOM))
{
Cache_ROOM_TCTQ_R2ROOM = new List<TCTQ>().AsReadOnly();
}
return Cache_ROOM_TCTQ_R2ROOM;
}
}
/// <summary>
/// TCTQ (Calendar Class Information) related entities by [SM.ROOM]->[TCTQ.EXTRA_ROOM]
/// Room code
/// </summary>
public IReadOnlyList<TCTQ> ROOM_TCTQ_EXTRA_ROOM
{
get
{
if (Cache_ROOM_TCTQ_EXTRA_ROOM == null &&
!Context.TCTQ.TryFindByEXTRA_ROOM(ROOM, out Cache_ROOM_TCTQ_EXTRA_ROOM))
{
Cache_ROOM_TCTQ_EXTRA_ROOM = new List<TCTQ>().AsReadOnly();
}
return Cache_ROOM_TCTQ_EXTRA_ROOM;
}
}
/// <summary>
/// TCTR (Teacher Replacements) related entities by [SM.ROOM]->[TCTR.ROOM]
/// Room code
/// </summary>
public IReadOnlyList<TCTR> ROOM_TCTR_ROOM
{
get
{
if (Cache_ROOM_TCTR_ROOM == null &&
!Context.TCTR.TryFindByROOM(ROOM, out Cache_ROOM_TCTR_ROOM))
{
Cache_ROOM_TCTR_ROOM = new List<TCTR>().AsReadOnly();
}
return Cache_ROOM_TCTR_ROOM;
}
}
/// <summary>
/// TE (Calendar Events) related entities by [SM.ROOM]->[TE.LOCATION]
/// Room code
/// </summary>
public IReadOnlyList<TE> ROOM_TE_LOCATION
{
get
{
if (Cache_ROOM_TE_LOCATION == null &&
!Context.TE.TryFindByLOCATION(ROOM, out Cache_ROOM_TE_LOCATION))
{
Cache_ROOM_TE_LOCATION = new List<TE>().AsReadOnly();
}
return Cache_ROOM_TE_LOCATION;
}
}
/// <summary>
/// TETE (Event Instances) related entities by [SM.ROOM]->[TETE.LOCATION]
/// Room code
/// </summary>
public IReadOnlyList<TETE> ROOM_TETE_LOCATION
{
get
{
if (Cache_ROOM_TETE_LOCATION == null &&
!Context.TETE.TryFindByLOCATION(ROOM, out Cache_ROOM_TETE_LOCATION))
{
Cache_ROOM_TETE_LOCATION = new List<TETE>().AsReadOnly();
}
return Cache_ROOM_TETE_LOCATION;
}
}
/// <summary>
/// THTQ (Timetable Quilt Entries) related entities by [SM.ROOM]->[THTQ.R1ROOM]
/// Room code
/// </summary>
public IReadOnlyList<THTQ> ROOM_THTQ_R1ROOM
{
get
{
if (Cache_ROOM_THTQ_R1ROOM == null &&
!Context.THTQ.TryFindByR1ROOM(ROOM, out Cache_ROOM_THTQ_R1ROOM))
{
Cache_ROOM_THTQ_R1ROOM = new List<THTQ>().AsReadOnly();
}
return Cache_ROOM_THTQ_R1ROOM;
}
}
/// <summary>
/// THTQ (Timetable Quilt Entries) related entities by [SM.ROOM]->[THTQ.R2ROOM]
/// Room code
/// </summary>
public IReadOnlyList<THTQ> ROOM_THTQ_R2ROOM
{
get
{
if (Cache_ROOM_THTQ_R2ROOM == null &&
!Context.THTQ.TryFindByR2ROOM(ROOM, out Cache_ROOM_THTQ_R2ROOM))
{
Cache_ROOM_THTQ_R2ROOM = new List<THTQ>().AsReadOnly();
}
return Cache_ROOM_THTQ_R2ROOM;
}
}
/// <summary>
/// THTQ (Timetable Quilt Entries) related entities by [SM.ROOM]->[THTQ.EXTRA_ROOM]
/// Room code
/// </summary>
public IReadOnlyList<THTQ> ROOM_THTQ_EXTRA_ROOM
{
get
{
if (Cache_ROOM_THTQ_EXTRA_ROOM == null &&
!Context.THTQ.TryFindByEXTRA_ROOM(ROOM, out Cache_ROOM_THTQ_EXTRA_ROOM))
{
Cache_ROOM_THTQ_EXTRA_ROOM = new List<THTQ>().AsReadOnly();
}
return Cache_ROOM_THTQ_EXTRA_ROOM;
}
}
/// <summary>
/// TTEF (Exam Staff) related entities by [SM.ROOM]->[TTEF.ROOM]
/// Room code
/// </summary>
public IReadOnlyList<TTEF> ROOM_TTEF_ROOM
{
get
{
if (Cache_ROOM_TTEF_ROOM == null &&
!Context.TTEF.TryFindByROOM(ROOM, out Cache_ROOM_TTEF_ROOM))
{
Cache_ROOM_TTEF_ROOM = new List<TTEF>().AsReadOnly();
}
return Cache_ROOM_TTEF_ROOM;
}
}
/// <summary>
/// TTEX (Exam Grid) related entities by [SM.ROOM]->[TTEX.EXAM_ROOM]
/// Room code
/// </summary>
public IReadOnlyList<TTEX> ROOM_TTEX_EXAM_ROOM
{
get
{
if (Cache_ROOM_TTEX_EXAM_ROOM == null &&
!Context.TTEX.TryFindByEXAM_ROOM(ROOM, out Cache_ROOM_TTEX_EXAM_ROOM))
{
Cache_ROOM_TTEX_EXAM_ROOM = new List<TTEX>().AsReadOnly();
}
return Cache_ROOM_TTEX_EXAM_ROOM;
}
}
/// <summary>
/// TTTG (Grid Subjects) related entities by [SM.ROOM]->[TTTG.R1ROOM]
/// Room code
/// </summary>
public IReadOnlyList<TTTG> ROOM_TTTG_R1ROOM
{
get
{
if (Cache_ROOM_TTTG_R1ROOM == null &&
!Context.TTTG.TryFindByR1ROOM(ROOM, out Cache_ROOM_TTTG_R1ROOM))
{
Cache_ROOM_TTTG_R1ROOM = new List<TTTG>().AsReadOnly();
}
return Cache_ROOM_TTTG_R1ROOM;
}
}
/// <summary>
/// TTTG (Grid Subjects) related entities by [SM.ROOM]->[TTTG.R2ROOM]
/// Room code
/// </summary>
public IReadOnlyList<TTTG> ROOM_TTTG_R2ROOM
{
get
{
if (Cache_ROOM_TTTG_R2ROOM == null &&
!Context.TTTG.TryFindByR2ROOM(ROOM, out Cache_ROOM_TTTG_R2ROOM))
{
Cache_ROOM_TTTG_R2ROOM = new List<TTTG>().AsReadOnly();
}
return Cache_ROOM_TTTG_R2ROOM;
}
}
/// <summary>
/// TXAS (Actual Sessions) related entities by [SM.ROOM]->[TXAS.LOCATION]
/// Room code
/// </summary>
public IReadOnlyList<TXAS> ROOM_TXAS_LOCATION
{
get
{
if (Cache_ROOM_TXAS_LOCATION == null &&
!Context.TXAS.TryFindByLOCATION(ROOM, out Cache_ROOM_TXAS_LOCATION))
{
Cache_ROOM_TXAS_LOCATION = new List<TXAS>().AsReadOnly();
}
return Cache_ROOM_TXAS_LOCATION;
}
}
#endregion
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Branding.UIElementPersonalizationWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Kraken.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// <copyright file="PrometheusSerializer.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if NETCOREAPP3_1_OR_GREATER
using System;
#endif
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace OpenTelemetry.Exporter.Prometheus
{
/// <summary>
/// Basic PrometheusSerializer which has no OpenTelemetry dependency.
/// </summary>
internal static partial class PrometheusSerializer
{
#pragma warning disable SA1310 // Field name should not contain an underscore
private const byte ASCII_QUOTATION_MARK = 0x22; // '"'
private const byte ASCII_FULL_STOP = 0x2E; // '.'
private const byte ASCII_HYPHEN_MINUS = 0x2D; // '-'
private const byte ASCII_REVERSE_SOLIDUS = 0x5C; // '\\'
private const byte ASCII_LINEFEED = 0x0A; // `\n`
#pragma warning restore SA1310 // Field name should not contain an underscore
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteDouble(byte[] buffer, int cursor, double value)
{
#if NETCOREAPP3_1_OR_GREATER
if (double.IsFinite(value))
#else
if (!double.IsInfinity(value) && !double.IsNaN(value))
#endif
{
#if NETCOREAPP3_1_OR_GREATER
Span<char> span = stackalloc char[128];
var result = value.TryFormat(span, out var cchWritten, "G", CultureInfo.InvariantCulture);
Debug.Assert(result, $"{nameof(result)} should be true.");
for (int i = 0; i < cchWritten; i++)
{
buffer[cursor++] = unchecked((byte)span[i]);
}
#else
cursor = WriteAsciiStringNoEscape(buffer, cursor, value.ToString(CultureInfo.InvariantCulture));
#endif
}
else if (double.IsPositiveInfinity(value))
{
cursor = WriteAsciiStringNoEscape(buffer, cursor, "+Inf");
}
else if (double.IsNegativeInfinity(value))
{
cursor = WriteAsciiStringNoEscape(buffer, cursor, "-Inf");
}
else
{
Debug.Assert(double.IsNaN(value), $"{nameof(value)} should be NaN.");
cursor = WriteAsciiStringNoEscape(buffer, cursor, "Nan");
}
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteLong(byte[] buffer, int cursor, long value)
{
#if NETCOREAPP3_1_OR_GREATER
Span<char> span = stackalloc char[20];
var result = value.TryFormat(span, out var cchWritten, "G", CultureInfo.InvariantCulture);
Debug.Assert(result, $"{nameof(result)} should be true.");
for (int i = 0; i < cchWritten; i++)
{
buffer[cursor++] = unchecked((byte)span[i]);
}
#else
cursor = WriteAsciiStringNoEscape(buffer, cursor, value.ToString(CultureInfo.InvariantCulture));
#endif
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteAsciiStringNoEscape(byte[] buffer, int cursor, string value)
{
for (int i = 0; i < value.Length; i++)
{
buffer[cursor++] = unchecked((byte)value[i]);
}
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteUnicodeNoEscape(byte[] buffer, int cursor, ushort ordinal)
{
if (ordinal <= 0x7F)
{
buffer[cursor++] = unchecked((byte)ordinal);
}
else if (ordinal <= 0x07FF)
{
buffer[cursor++] = unchecked((byte)(0b_1100_0000 | (ordinal >> 6)));
buffer[cursor++] = unchecked((byte)(0b_1000_0000 | (ordinal & 0b_0011_1111)));
}
else if (ordinal <= 0xFFFF)
{
buffer[cursor++] = unchecked((byte)(0b_1110_0000 | (ordinal >> 12)));
buffer[cursor++] = unchecked((byte)(0b_1000_0000 | ((ordinal >> 6) & 0b_0011_1111)));
buffer[cursor++] = unchecked((byte)(0b_1000_0000 | (ordinal & 0b_0011_1111)));
}
else
{
Debug.Assert(ordinal <= 0xFFFF, ".NET string should not go beyond Unicode BMP.");
}
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteUnicodeString(byte[] buffer, int cursor, string value)
{
for (int i = 0; i < value.Length; i++)
{
var ordinal = (ushort)value[i];
switch (ordinal)
{
case ASCII_REVERSE_SOLIDUS:
buffer[cursor++] = ASCII_REVERSE_SOLIDUS;
buffer[cursor++] = ASCII_REVERSE_SOLIDUS;
break;
case ASCII_LINEFEED:
buffer[cursor++] = ASCII_REVERSE_SOLIDUS;
buffer[cursor++] = unchecked((byte)'n');
break;
default:
cursor = WriteUnicodeNoEscape(buffer, cursor, ordinal);
break;
}
}
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteLabelKey(byte[] buffer, int cursor, string value)
{
Debug.Assert(!string.IsNullOrEmpty(value), $"{nameof(value)} should not be null or empty.");
var ordinal = (ushort)value[0];
if (ordinal >= (ushort)'0' && ordinal <= (ushort)'9')
{
buffer[cursor++] = unchecked((byte)'_');
}
for (int i = 0; i < value.Length; i++)
{
ordinal = (ushort)value[i];
if ((ordinal >= (ushort)'A' && ordinal <= (ushort)'Z') ||
(ordinal >= (ushort)'a' && ordinal <= (ushort)'z') ||
(ordinal >= (ushort)'0' && ordinal <= (ushort)'9'))
{
buffer[cursor++] = unchecked((byte)ordinal);
}
else
{
buffer[cursor++] = unchecked((byte)'_');
}
}
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteLabelValue(byte[] buffer, int cursor, string value)
{
Debug.Assert(value != null, $"{nameof(value)} should not be null.");
for (int i = 0; i < value.Length; i++)
{
var ordinal = (ushort)value[i];
switch (ordinal)
{
case ASCII_QUOTATION_MARK:
buffer[cursor++] = ASCII_REVERSE_SOLIDUS;
buffer[cursor++] = ASCII_QUOTATION_MARK;
break;
case ASCII_REVERSE_SOLIDUS:
buffer[cursor++] = ASCII_REVERSE_SOLIDUS;
buffer[cursor++] = ASCII_REVERSE_SOLIDUS;
break;
case ASCII_LINEFEED:
buffer[cursor++] = ASCII_REVERSE_SOLIDUS;
buffer[cursor++] = unchecked((byte)'n');
break;
default:
cursor = WriteUnicodeNoEscape(buffer, cursor, ordinal);
break;
}
}
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteLabel(byte[] buffer, int cursor, string labelKey, object labelValue)
{
cursor = WriteLabelKey(buffer, cursor, labelKey);
buffer[cursor++] = unchecked((byte)'=');
buffer[cursor++] = unchecked((byte)'"');
// In Prometheus, a label with an empty label value is considered equivalent to a label that does not exist.
cursor = WriteLabelValue(buffer, cursor, labelValue?.ToString() ?? string.Empty);
buffer[cursor++] = unchecked((byte)'"');
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteMetricName(byte[] buffer, int cursor, string metricName, string metricUnit = null)
{
Debug.Assert(!string.IsNullOrEmpty(metricName), $"{nameof(metricName)} should not be null or empty.");
for (int i = 0; i < metricName.Length; i++)
{
var ordinal = (ushort)metricName[i];
switch (ordinal)
{
case ASCII_FULL_STOP:
case ASCII_HYPHEN_MINUS:
buffer[cursor++] = unchecked((byte)'_');
break;
default:
buffer[cursor++] = unchecked((byte)ordinal);
break;
}
}
if (!string.IsNullOrEmpty(metricUnit))
{
buffer[cursor++] = unchecked((byte)'_');
for (int i = 0; i < metricUnit.Length; i++)
{
var ordinal = (ushort)metricUnit[i];
if ((ordinal >= (ushort)'A' && ordinal <= (ushort)'Z') ||
(ordinal >= (ushort)'a' && ordinal <= (ushort)'z') ||
(ordinal >= (ushort)'0' && ordinal <= (ushort)'9'))
{
buffer[cursor++] = unchecked((byte)ordinal);
}
else
{
buffer[cursor++] = unchecked((byte)'_');
}
}
}
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteHelpText(byte[] buffer, int cursor, string metricName, string metricUnit = null, string metricDescription = null)
{
cursor = WriteAsciiStringNoEscape(buffer, cursor, "# HELP ");
cursor = WriteMetricName(buffer, cursor, metricName, metricUnit);
if (!string.IsNullOrEmpty(metricDescription))
{
buffer[cursor++] = unchecked((byte)' ');
cursor = WriteUnicodeString(buffer, cursor, metricDescription);
}
buffer[cursor++] = ASCII_LINEFEED;
return cursor;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int WriteTypeInfo(byte[] buffer, int cursor, string metricName, string metricUnit, string metricType)
{
Debug.Assert(!string.IsNullOrEmpty(metricType), $"{nameof(metricType)} should not be null or empty.");
cursor = WriteAsciiStringNoEscape(buffer, cursor, "# TYPE ");
cursor = WriteMetricName(buffer, cursor, metricName, metricUnit);
buffer[cursor++] = unchecked((byte)' ');
cursor = WriteAsciiStringNoEscape(buffer, cursor, metricType);
buffer[cursor++] = ASCII_LINEFEED;
return cursor;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Summarizes the state of a compute node.
/// </summary>
public partial class ComputeNode : IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<string> AffinityIdProperty;
public readonly PropertyAccessor<DateTime?> AllocationTimeProperty;
public readonly PropertyAccessor<IReadOnlyList<CertificateReference>> CertificateReferencesProperty;
public readonly PropertyAccessor<IReadOnlyList<ComputeNodeError>> ErrorsProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<string> IPAddressProperty;
public readonly PropertyAccessor<DateTime?> LastBootTimeProperty;
public readonly PropertyAccessor<IReadOnlyList<TaskInformation>> RecentTasksProperty;
public readonly PropertyAccessor<int?> RunningTasksCountProperty;
public readonly PropertyAccessor<Common.SchedulingState?> SchedulingStateProperty;
public readonly PropertyAccessor<StartTask> StartTaskProperty;
public readonly PropertyAccessor<StartTaskInformation> StartTaskInformationProperty;
public readonly PropertyAccessor<Common.ComputeNodeState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<int?> TotalTasksRunProperty;
public readonly PropertyAccessor<int?> TotalTasksSucceededProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<string> VirtualMachineSizeProperty;
public PropertyContainer(Models.ComputeNode protocolObject) : base(BindingState.Bound)
{
this.AffinityIdProperty = this.CreatePropertyAccessor(
protocolObject.AffinityId,
"AffinityId",
BindingAccess.Read);
this.AllocationTimeProperty = this.CreatePropertyAccessor(
protocolObject.AllocationTime,
"AllocationTime",
BindingAccess.Read);
this.CertificateReferencesProperty = this.CreatePropertyAccessor(
CertificateReference.ConvertFromProtocolCollectionReadOnly(protocolObject.CertificateReferences),
"CertificateReferences",
BindingAccess.Read);
this.ErrorsProperty = this.CreatePropertyAccessor(
ComputeNodeError.ConvertFromProtocolCollectionReadOnly(protocolObject.Errors),
"Errors",
BindingAccess.Read);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
"Id",
BindingAccess.Read);
this.IPAddressProperty = this.CreatePropertyAccessor(
protocolObject.IpAddress,
"IPAddress",
BindingAccess.Read);
this.LastBootTimeProperty = this.CreatePropertyAccessor(
protocolObject.LastBootTime,
"LastBootTime",
BindingAccess.Read);
this.RecentTasksProperty = this.CreatePropertyAccessor(
TaskInformation.ConvertFromProtocolCollectionReadOnly(protocolObject.RecentTasks),
"RecentTasks",
BindingAccess.Read);
this.RunningTasksCountProperty = this.CreatePropertyAccessor(
protocolObject.RunningTasksCount,
"RunningTasksCount",
BindingAccess.Read);
this.SchedulingStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.SchedulingState, Common.SchedulingState>(protocolObject.SchedulingState),
"SchedulingState",
BindingAccess.Read);
this.StartTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o).Freeze()),
"StartTask",
BindingAccess.Read);
this.StartTaskInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTaskInfo, o => new StartTaskInformation(o).Freeze()),
"StartTaskInformation",
BindingAccess.Read);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.ComputeNodeState, Common.ComputeNodeState>(protocolObject.State),
"State",
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
"StateTransitionTime",
BindingAccess.Read);
this.TotalTasksRunProperty = this.CreatePropertyAccessor(
protocolObject.TotalTasksRun,
"TotalTasksRun",
BindingAccess.Read);
this.TotalTasksSucceededProperty = this.CreatePropertyAccessor(
protocolObject.TotalTasksSucceeded,
"TotalTasksSucceeded",
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
"Url",
BindingAccess.Read);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(
protocolObject.VmSize,
"VirtualMachineSize",
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
private readonly string parentPoolId;
internal string ParentPoolId
{
get
{
return this.parentPoolId;
}
}
#region Constructors
internal ComputeNode(
BatchClient parentBatchClient,
string parentPoolId,
Models.ComputeNode protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentPoolId = parentPoolId;
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="ComputeNode"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region ComputeNode
/// <summary>
/// Gets an opaque string that contains information about the location of the compute node.
/// </summary>
public string AffinityId
{
get { return this.propertyContainer.AffinityIdProperty.Value; }
}
/// <summary>
/// Gets the time at which this compute node was allocated to the pool.
/// </summary>
public DateTime? AllocationTime
{
get { return this.propertyContainer.AllocationTimeProperty.Value; }
}
/// <summary>
/// Gets the list of certificates installed on this compute node.
/// </summary>
public IReadOnlyList<CertificateReference> CertificateReferences
{
get { return this.propertyContainer.CertificateReferencesProperty.Value; }
}
/// <summary>
/// Gets the list of errors that are currently being encountered by the compute node.
/// </summary>
public IReadOnlyList<ComputeNodeError> Errors
{
get { return this.propertyContainer.ErrorsProperty.Value; }
}
/// <summary>
/// Gets the id of compute node.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
}
/// <summary>
/// Gets the IP address associated with the compute node.
/// </summary>
public string IPAddress
{
get { return this.propertyContainer.IPAddressProperty.Value; }
}
/// <summary>
/// Gets the time at which the compute node was started.
/// </summary>
public DateTime? LastBootTime
{
get { return this.propertyContainer.LastBootTimeProperty.Value; }
}
/// <summary>
/// Gets the execution information for the most recent tasks that ran on this compute node. Note that this element
/// is only returned if at least one task was run on this compute node since the time it was assigned to its current
/// pool.
/// </summary>
public IReadOnlyList<TaskInformation> RecentTasks
{
get { return this.propertyContainer.RecentTasksProperty.Value; }
}
/// <summary>
/// Gets the total number of currently running tasks on the compute node. This includes Job Preparation, Job Release,
/// and Job Manager tasks, but not the pool start task.
/// </summary>
public int? RunningTasksCount
{
get { return this.propertyContainer.RunningTasksCountProperty.Value; }
}
/// <summary>
/// Gets whether the node is available for task scheduling.
/// </summary>
public Common.SchedulingState? SchedulingState
{
get { return this.propertyContainer.SchedulingStateProperty.Value; }
}
/// <summary>
/// Gets the start task associated with all compute nodes in this pool.
/// </summary>
public StartTask StartTask
{
get { return this.propertyContainer.StartTaskProperty.Value; }
}
/// <summary>
/// Gets the detailed runtime information of the start task, including current state, error details, exit code, start
/// time, end time, etc.
/// </summary>
public StartTaskInformation StartTaskInformation
{
get { return this.propertyContainer.StartTaskInformationProperty.Value; }
}
/// <summary>
/// Gets the current state of the compute node.
/// </summary>
public Common.ComputeNodeState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the compute node entered the current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets the number of tasks that have been run on this compute node from the time it was allocated to this pool.
/// This includes Job Preparation, Job Release, and Job Manager tasks, but not the pool start task.
/// </summary>
public int? TotalTasksRun
{
get { return this.propertyContainer.TotalTasksRunProperty.Value; }
}
/// <summary>
/// Gets the total number of tasks which completed successfully (with exitCode 0) on the compute node. This includes
/// Job Preparation, Job Release, and Job Manager tasks, but not the pool start task.
/// </summary>
public int? TotalTasksSucceeded
{
get { return this.propertyContainer.TotalTasksSucceededProperty.Value; }
}
/// <summary>
/// Gets the URL of compute node.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets the size of the virtual machine hosting the compute node.
/// </summary>
public string VirtualMachineSize
{
get { return this.propertyContainer.VirtualMachineSizeProperty.Value; }
}
#endregion // ComputeNode
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
}
}
| |
// 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.
//Testing simple math on local vars and fields - mul
#pragma warning disable 0414
using System;
internal class lclfldmul
{
//user-defined class that overloads operator *
public class numHolder
{
private int _i_num;
private uint _ui_num;
private long _l_num;
private ulong _ul_num;
private float _f_num;
private double _d_num;
private decimal _m_num;
public numHolder(int i_num)
{
_i_num = Convert.ToInt32(i_num);
_ui_num = Convert.ToUInt32(i_num);
_l_num = Convert.ToInt64(i_num);
_ul_num = Convert.ToUInt64(i_num);
_f_num = Convert.ToSingle(i_num);
_d_num = Convert.ToDouble(i_num);
_m_num = Convert.ToDecimal(i_num);
}
public static int operator *(numHolder a, int b)
{
return a._i_num * b;
}
public numHolder(uint ui_num)
{
_i_num = Convert.ToInt32(ui_num);
_ui_num = Convert.ToUInt32(ui_num);
_l_num = Convert.ToInt64(ui_num);
_ul_num = Convert.ToUInt64(ui_num);
_f_num = Convert.ToSingle(ui_num);
_d_num = Convert.ToDouble(ui_num);
_m_num = Convert.ToDecimal(ui_num);
}
public static uint operator *(numHolder a, uint b)
{
return a._ui_num * b;
}
public numHolder(long l_num)
{
_i_num = Convert.ToInt32(l_num);
_ui_num = Convert.ToUInt32(l_num);
_l_num = Convert.ToInt64(l_num);
_ul_num = Convert.ToUInt64(l_num);
_f_num = Convert.ToSingle(l_num);
_d_num = Convert.ToDouble(l_num);
_m_num = Convert.ToDecimal(l_num);
}
public static long operator *(numHolder a, long b)
{
return a._l_num * b;
}
public numHolder(ulong ul_num)
{
_i_num = Convert.ToInt32(ul_num);
_ui_num = Convert.ToUInt32(ul_num);
_l_num = Convert.ToInt64(ul_num);
_ul_num = Convert.ToUInt64(ul_num);
_f_num = Convert.ToSingle(ul_num);
_d_num = Convert.ToDouble(ul_num);
_m_num = Convert.ToDecimal(ul_num);
}
public static long operator *(numHolder a, ulong b)
{
return (long)(a._ul_num * b);
}
public numHolder(float f_num)
{
_i_num = Convert.ToInt32(f_num);
_ui_num = Convert.ToUInt32(f_num);
_l_num = Convert.ToInt64(f_num);
_ul_num = Convert.ToUInt64(f_num);
_f_num = Convert.ToSingle(f_num);
_d_num = Convert.ToDouble(f_num);
_m_num = Convert.ToDecimal(f_num);
}
public static float operator *(numHolder a, float b)
{
return a._f_num * b;
}
public numHolder(double d_num)
{
_i_num = Convert.ToInt32(d_num);
_ui_num = Convert.ToUInt32(d_num);
_l_num = Convert.ToInt64(d_num);
_ul_num = Convert.ToUInt64(d_num);
_f_num = Convert.ToSingle(d_num);
_d_num = Convert.ToDouble(d_num);
_m_num = Convert.ToDecimal(d_num);
}
public static double operator *(numHolder a, double b)
{
return a._d_num * b;
}
public numHolder(decimal m_num)
{
_i_num = Convert.ToInt32(m_num);
_ui_num = Convert.ToUInt32(m_num);
_l_num = Convert.ToInt64(m_num);
_ul_num = Convert.ToUInt64(m_num);
_f_num = Convert.ToSingle(m_num);
_d_num = Convert.ToDouble(m_num);
_m_num = Convert.ToDecimal(m_num);
}
public static int operator *(numHolder a, decimal b)
{
return (int)(a._m_num * b);
}
public static int operator *(numHolder a, numHolder b)
{
return a._i_num * b._i_num;
}
}
private static int s_i_s_op1 = 3;
private static uint s_ui_s_op1 = 3;
private static long s_l_s_op1 = 3;
private static ulong s_ul_s_op1 = 3;
private static float s_f_s_op1 = 3;
private static double s_d_s_op1 = 3;
private static decimal s_m_s_op1 = 3;
private static int s_i_s_op2 = 7;
private static uint s_ui_s_op2 = 7;
private static long s_l_s_op2 = 7;
private static ulong s_ul_s_op2 = 7;
private static float s_f_s_op2 = 7;
private static double s_d_s_op2 = 7;
private static decimal s_m_s_op2 = 7;
private static numHolder s_nHldr_s_op2 = new numHolder(7);
public static int i_f(String s)
{
if (s == "op1")
return 3;
else
return 7;
}
public static uint ui_f(String s)
{
if (s == "op1")
return 3;
else
return 7;
}
public static long l_f(String s)
{
if (s == "op1")
return 3;
else
return 7;
}
public static ulong ul_f(String s)
{
if (s == "op1")
return 3;
else
return 7;
}
public static float f_f(String s)
{
if (s == "op1")
return 3;
else
return 7;
}
public static double d_f(String s)
{
if (s == "op1")
return 3;
else
return 7;
}
public static decimal m_f(String s)
{
if (s == "op1")
return 3;
else
return 7;
}
public static numHolder nHldr_f(String s)
{
if (s == "op1")
return new numHolder(3);
else
return new numHolder(7);
}
private class CL
{
public int i_cl_op1 = 3;
public uint ui_cl_op1 = 3;
public long l_cl_op1 = 3;
public ulong ul_cl_op1 = 3;
public float f_cl_op1 = 3;
public double d_cl_op1 = 3;
public decimal m_cl_op1 = 3;
public int i_cl_op2 = 7;
public uint ui_cl_op2 = 7;
public long l_cl_op2 = 7;
public ulong ul_cl_op2 = 7;
public float f_cl_op2 = 7;
public double d_cl_op2 = 7;
public decimal m_cl_op2 = 7;
public numHolder nHldr_cl_op2 = new numHolder(7);
}
private struct VT
{
public int i_vt_op1;
public uint ui_vt_op1;
public long l_vt_op1;
public ulong ul_vt_op1;
public float f_vt_op1;
public double d_vt_op1;
public decimal m_vt_op1;
public int i_vt_op2;
public uint ui_vt_op2;
public long l_vt_op2;
public ulong ul_vt_op2;
public float f_vt_op2;
public double d_vt_op2;
public decimal m_vt_op2;
public numHolder nHldr_vt_op2;
}
public static int Main()
{
bool passed = true;
//initialize class
CL cl1 = new CL();
//initialize struct
VT vt1;
vt1.i_vt_op1 = 3;
vt1.ui_vt_op1 = 3;
vt1.l_vt_op1 = 3;
vt1.ul_vt_op1 = 3;
vt1.f_vt_op1 = 3;
vt1.d_vt_op1 = 3;
vt1.m_vt_op1 = 3;
vt1.i_vt_op2 = 7;
vt1.ui_vt_op2 = 7;
vt1.l_vt_op2 = 7;
vt1.ul_vt_op2 = 7;
vt1.f_vt_op2 = 7;
vt1.d_vt_op2 = 7;
vt1.m_vt_op2 = 7;
vt1.nHldr_vt_op2 = new numHolder(7);
int[] i_arr1d_op1 = { 0, 3 };
int[,] i_arr2d_op1 = { { 0, 3 }, { 1, 1 } };
int[,,] i_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } };
uint[] ui_arr1d_op1 = { 0, 3 };
uint[,] ui_arr2d_op1 = { { 0, 3 }, { 1, 1 } };
uint[,,] ui_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } };
long[] l_arr1d_op1 = { 0, 3 };
long[,] l_arr2d_op1 = { { 0, 3 }, { 1, 1 } };
long[,,] l_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } };
ulong[] ul_arr1d_op1 = { 0, 3 };
ulong[,] ul_arr2d_op1 = { { 0, 3 }, { 1, 1 } };
ulong[,,] ul_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } };
float[] f_arr1d_op1 = { 0, 3 };
float[,] f_arr2d_op1 = { { 0, 3 }, { 1, 1 } };
float[,,] f_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } };
double[] d_arr1d_op1 = { 0, 3 };
double[,] d_arr2d_op1 = { { 0, 3 }, { 1, 1 } };
double[,,] d_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } };
decimal[] m_arr1d_op1 = { 0, 3 };
decimal[,] m_arr2d_op1 = { { 0, 3 }, { 1, 1 } };
decimal[,,] m_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } };
int[] i_arr1d_op2 = { 7, 0, 1 };
int[,] i_arr2d_op2 = { { 0, 7 }, { 1, 1 } };
int[,,] i_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } };
uint[] ui_arr1d_op2 = { 7, 0, 1 };
uint[,] ui_arr2d_op2 = { { 0, 7 }, { 1, 1 } };
uint[,,] ui_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } };
long[] l_arr1d_op2 = { 7, 0, 1 };
long[,] l_arr2d_op2 = { { 0, 7 }, { 1, 1 } };
long[,,] l_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } };
ulong[] ul_arr1d_op2 = { 7, 0, 1 };
ulong[,] ul_arr2d_op2 = { { 0, 7 }, { 1, 1 } };
ulong[,,] ul_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } };
float[] f_arr1d_op2 = { 7, 0, 1 };
float[,] f_arr2d_op2 = { { 0, 7 }, { 1, 1 } };
float[,,] f_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } };
double[] d_arr1d_op2 = { 7, 0, 1 };
double[,] d_arr2d_op2 = { { 0, 7 }, { 1, 1 } };
double[,,] d_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } };
decimal[] m_arr1d_op2 = { 7, 0, 1 };
decimal[,] m_arr2d_op2 = { { 0, 7 }, { 1, 1 } };
decimal[,,] m_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } };
numHolder[] nHldr_arr1d_op2 = { new numHolder(7), new numHolder(0), new numHolder(1) };
numHolder[,] nHldr_arr2d_op2 = { { new numHolder(0), new numHolder(7) }, { new numHolder(1), new numHolder(1) } };
numHolder[,,] nHldr_arr3d_op2 = { { { new numHolder(0), new numHolder(7) }, { new numHolder(1), new numHolder(1) } } };
int[,] index = { { 0, 0 }, { 1, 1 } };
{
int i_l_op1 = 3;
int i_l_op2 = 7;
uint ui_l_op2 = 7;
long l_l_op2 = 7;
ulong ul_l_op2 = 7;
float f_l_op2 = 7;
double d_l_op2 = 7;
decimal m_l_op2 = 7;
numHolder nHldr_l_op2 = new numHolder(7);
if ((i_l_op1 * i_l_op2 != i_l_op1 * ui_l_op2) || (i_l_op1 * ui_l_op2 != i_l_op1 * l_l_op2) || (i_l_op1 * l_l_op2 != i_l_op1 * (int)ul_l_op2) || (i_l_op1 * (int)ul_l_op2 != i_l_op1 * f_l_op2) || (i_l_op1 * f_l_op2 != i_l_op1 * d_l_op2) || ((decimal)(i_l_op1 * d_l_op2) != i_l_op1 * m_l_op2) || (i_l_op1 * m_l_op2 != i_l_op1 * i_l_op2) || (i_l_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 1 failed");
passed = false;
}
if ((i_l_op1 * s_i_s_op2 != i_l_op1 * s_ui_s_op2) || (i_l_op1 * s_ui_s_op2 != i_l_op1 * s_l_s_op2) || (i_l_op1 * s_l_s_op2 != i_l_op1 * (int)s_ul_s_op2) || (i_l_op1 * (int)s_ul_s_op2 != i_l_op1 * s_f_s_op2) || (i_l_op1 * s_f_s_op2 != i_l_op1 * s_d_s_op2) || ((decimal)(i_l_op1 * s_d_s_op2) != i_l_op1 * s_m_s_op2) || (i_l_op1 * s_m_s_op2 != i_l_op1 * s_i_s_op2) || (i_l_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 2 failed");
passed = false;
}
if ((s_i_s_op1 * i_l_op2 != s_i_s_op1 * ui_l_op2) || (s_i_s_op1 * ui_l_op2 != s_i_s_op1 * l_l_op2) || (s_i_s_op1 * l_l_op2 != s_i_s_op1 * (int)ul_l_op2) || (s_i_s_op1 * (int)ul_l_op2 != s_i_s_op1 * f_l_op2) || (s_i_s_op1 * f_l_op2 != s_i_s_op1 * d_l_op2) || ((decimal)(s_i_s_op1 * d_l_op2) != s_i_s_op1 * m_l_op2) || (s_i_s_op1 * m_l_op2 != s_i_s_op1 * i_l_op2) || (s_i_s_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 3 failed");
passed = false;
}
if ((s_i_s_op1 * s_i_s_op2 != s_i_s_op1 * s_ui_s_op2) || (s_i_s_op1 * s_ui_s_op2 != s_i_s_op1 * s_l_s_op2) || (s_i_s_op1 * s_l_s_op2 != s_i_s_op1 * (int)s_ul_s_op2) || (s_i_s_op1 * (int)s_ul_s_op2 != s_i_s_op1 * s_f_s_op2) || (s_i_s_op1 * s_f_s_op2 != s_i_s_op1 * s_d_s_op2) || ((decimal)(s_i_s_op1 * s_d_s_op2) != s_i_s_op1 * s_m_s_op2) || (s_i_s_op1 * s_m_s_op2 != s_i_s_op1 * s_i_s_op2) || (s_i_s_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 4 failed");
passed = false;
}
}
{
uint ui_l_op1 = 3;
int i_l_op2 = 7;
uint ui_l_op2 = 7;
long l_l_op2 = 7;
ulong ul_l_op2 = 7;
float f_l_op2 = 7;
double d_l_op2 = 7;
decimal m_l_op2 = 7;
numHolder nHldr_l_op2 = new numHolder(7);
if ((ui_l_op1 * i_l_op2 != ui_l_op1 * ui_l_op2) || (ui_l_op1 * ui_l_op2 != ui_l_op1 * l_l_op2) || ((ulong)(ui_l_op1 * l_l_op2) != ui_l_op1 * ul_l_op2) || (ui_l_op1 * ul_l_op2 != ui_l_op1 * f_l_op2) || (ui_l_op1 * f_l_op2 != ui_l_op1 * d_l_op2) || ((decimal)(ui_l_op1 * d_l_op2) != ui_l_op1 * m_l_op2) || (ui_l_op1 * m_l_op2 != ui_l_op1 * i_l_op2) || (ui_l_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 5 failed");
passed = false;
}
if ((ui_l_op1 * s_i_s_op2 != ui_l_op1 * s_ui_s_op2) || (ui_l_op1 * s_ui_s_op2 != ui_l_op1 * s_l_s_op2) || ((ulong)(ui_l_op1 * s_l_s_op2) != ui_l_op1 * s_ul_s_op2) || (ui_l_op1 * s_ul_s_op2 != ui_l_op1 * s_f_s_op2) || (ui_l_op1 * s_f_s_op2 != ui_l_op1 * s_d_s_op2) || ((decimal)(ui_l_op1 * s_d_s_op2) != ui_l_op1 * s_m_s_op2) || (ui_l_op1 * s_m_s_op2 != ui_l_op1 * s_i_s_op2) || (ui_l_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 6 failed");
passed = false;
}
if ((s_ui_s_op1 * i_l_op2 != s_ui_s_op1 * ui_l_op2) || (s_ui_s_op1 * ui_l_op2 != s_ui_s_op1 * l_l_op2) || ((ulong)(s_ui_s_op1 * l_l_op2) != s_ui_s_op1 * ul_l_op2) || (s_ui_s_op1 * ul_l_op2 != s_ui_s_op1 * f_l_op2) || (s_ui_s_op1 * f_l_op2 != s_ui_s_op1 * d_l_op2) || ((decimal)(s_ui_s_op1 * d_l_op2) != s_ui_s_op1 * m_l_op2) || (s_ui_s_op1 * m_l_op2 != s_ui_s_op1 * i_l_op2) || (s_ui_s_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 7 failed");
passed = false;
}
if ((s_ui_s_op1 * s_i_s_op2 != s_ui_s_op1 * s_ui_s_op2) || (s_ui_s_op1 * s_ui_s_op2 != s_ui_s_op1 * s_l_s_op2) || ((ulong)(s_ui_s_op1 * s_l_s_op2) != s_ui_s_op1 * s_ul_s_op2) || (s_ui_s_op1 * s_ul_s_op2 != s_ui_s_op1 * s_f_s_op2) || (s_ui_s_op1 * s_f_s_op2 != s_ui_s_op1 * s_d_s_op2) || ((decimal)(s_ui_s_op1 * s_d_s_op2) != s_ui_s_op1 * s_m_s_op2) || (s_ui_s_op1 * s_m_s_op2 != s_ui_s_op1 * s_i_s_op2) || (s_ui_s_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 8 failed");
passed = false;
}
}
{
long l_l_op1 = 3;
int i_l_op2 = 7;
uint ui_l_op2 = 7;
long l_l_op2 = 7;
ulong ul_l_op2 = 7;
float f_l_op2 = 7;
double d_l_op2 = 7;
decimal m_l_op2 = 7;
numHolder nHldr_l_op2 = new numHolder(7);
if ((l_l_op1 * i_l_op2 != l_l_op1 * ui_l_op2) || (l_l_op1 * ui_l_op2 != l_l_op1 * l_l_op2) || (l_l_op1 * l_l_op2 != l_l_op1 * (long)ul_l_op2) || (l_l_op1 * (long)ul_l_op2 != l_l_op1 * f_l_op2) || (l_l_op1 * f_l_op2 != l_l_op1 * d_l_op2) || ((decimal)(l_l_op1 * d_l_op2) != l_l_op1 * m_l_op2) || (l_l_op1 * m_l_op2 != l_l_op1 * i_l_op2) || (l_l_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 9 failed");
passed = false;
}
if ((l_l_op1 * s_i_s_op2 != l_l_op1 * s_ui_s_op2) || (l_l_op1 * s_ui_s_op2 != l_l_op1 * s_l_s_op2) || (l_l_op1 * s_l_s_op2 != l_l_op1 * (long)s_ul_s_op2) || (l_l_op1 * (long)s_ul_s_op2 != l_l_op1 * s_f_s_op2) || (l_l_op1 * s_f_s_op2 != l_l_op1 * s_d_s_op2) || ((decimal)(l_l_op1 * s_d_s_op2) != l_l_op1 * s_m_s_op2) || (l_l_op1 * s_m_s_op2 != l_l_op1 * s_i_s_op2) || (l_l_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 10 failed");
passed = false;
}
if ((s_l_s_op1 * i_l_op2 != s_l_s_op1 * ui_l_op2) || (s_l_s_op1 * ui_l_op2 != s_l_s_op1 * l_l_op2) || (s_l_s_op1 * l_l_op2 != s_l_s_op1 * (long)ul_l_op2) || (s_l_s_op1 * (long)ul_l_op2 != s_l_s_op1 * f_l_op2) || (s_l_s_op1 * f_l_op2 != s_l_s_op1 * d_l_op2) || ((decimal)(s_l_s_op1 * d_l_op2) != s_l_s_op1 * m_l_op2) || (s_l_s_op1 * m_l_op2 != s_l_s_op1 * i_l_op2) || (s_l_s_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 11 failed");
passed = false;
}
if ((s_l_s_op1 * s_i_s_op2 != s_l_s_op1 * s_ui_s_op2) || (s_l_s_op1 * s_ui_s_op2 != s_l_s_op1 * s_l_s_op2) || (s_l_s_op1 * s_l_s_op2 != s_l_s_op1 * (long)s_ul_s_op2) || (s_l_s_op1 * (long)s_ul_s_op2 != s_l_s_op1 * s_f_s_op2) || (s_l_s_op1 * s_f_s_op2 != s_l_s_op1 * s_d_s_op2) || ((decimal)(s_l_s_op1 * s_d_s_op2) != s_l_s_op1 * s_m_s_op2) || (s_l_s_op1 * s_m_s_op2 != s_l_s_op1 * s_i_s_op2) || (s_l_s_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 12 failed");
passed = false;
}
}
{
ulong ul_l_op1 = 3;
int i_l_op2 = 7;
uint ui_l_op2 = 7;
long l_l_op2 = 7;
ulong ul_l_op2 = 7;
float f_l_op2 = 7;
double d_l_op2 = 7;
decimal m_l_op2 = 7;
numHolder nHldr_l_op2 = new numHolder(7);
if ((ul_l_op1 * (ulong)i_l_op2 != ul_l_op1 * ui_l_op2) || (ul_l_op1 * ui_l_op2 != ul_l_op1 * (ulong)l_l_op2) || (ul_l_op1 * (ulong)l_l_op2 != ul_l_op1 * ul_l_op2) || (ul_l_op1 * ul_l_op2 != ul_l_op1 * f_l_op2) || (ul_l_op1 * f_l_op2 != ul_l_op1 * d_l_op2) || ((decimal)(ul_l_op1 * d_l_op2) != ul_l_op1 * m_l_op2) || (ul_l_op1 * m_l_op2 != ul_l_op1 * (ulong)i_l_op2) || (ul_l_op1 * (ulong)i_l_op2 != 21))
{
Console.WriteLine("testcase 13 failed");
passed = false;
}
if ((ul_l_op1 * (ulong)s_i_s_op2 != ul_l_op1 * s_ui_s_op2) || (ul_l_op1 * s_ui_s_op2 != ul_l_op1 * (ulong)s_l_s_op2) || (ul_l_op1 * (ulong)s_l_s_op2 != ul_l_op1 * s_ul_s_op2) || (ul_l_op1 * s_ul_s_op2 != ul_l_op1 * s_f_s_op2) || (ul_l_op1 * s_f_s_op2 != ul_l_op1 * s_d_s_op2) || ((decimal)(ul_l_op1 * s_d_s_op2) != ul_l_op1 * s_m_s_op2) || (ul_l_op1 * s_m_s_op2 != ul_l_op1 * (ulong)s_i_s_op2) || (ul_l_op1 * (ulong)s_i_s_op2 != 21))
{
Console.WriteLine("testcase 14 failed");
passed = false;
}
if ((s_ul_s_op1 * (ulong)i_l_op2 != s_ul_s_op1 * ui_l_op2) || (s_ul_s_op1 * ui_l_op2 != s_ul_s_op1 * (ulong)l_l_op2) || (s_ul_s_op1 * (ulong)l_l_op2 != s_ul_s_op1 * ul_l_op2) || (s_ul_s_op1 * ul_l_op2 != s_ul_s_op1 * f_l_op2) || (s_ul_s_op1 * f_l_op2 != s_ul_s_op1 * d_l_op2) || ((decimal)(s_ul_s_op1 * d_l_op2) != s_ul_s_op1 * m_l_op2) || (s_ul_s_op1 * m_l_op2 != s_ul_s_op1 * (ulong)i_l_op2) || (s_ul_s_op1 * (ulong)i_l_op2 != 21))
{
Console.WriteLine("testcase 15 failed");
passed = false;
}
if ((s_ul_s_op1 * (ulong)s_i_s_op2 != s_ul_s_op1 * s_ui_s_op2) || (s_ul_s_op1 * s_ui_s_op2 != s_ul_s_op1 * (ulong)s_l_s_op2) || (s_ul_s_op1 * (ulong)s_l_s_op2 != s_ul_s_op1 * s_ul_s_op2) || (s_ul_s_op1 * s_ul_s_op2 != s_ul_s_op1 * s_f_s_op2) || (s_ul_s_op1 * s_f_s_op2 != s_ul_s_op1 * s_d_s_op2) || ((decimal)(s_ul_s_op1 * s_d_s_op2) != s_ul_s_op1 * s_m_s_op2) || (s_ul_s_op1 * s_m_s_op2 != s_ul_s_op1 * (ulong)s_i_s_op2) || (s_ul_s_op1 * (ulong)s_i_s_op2 != 21))
{
Console.WriteLine("testcase 16 failed");
passed = false;
}
}
{
float f_l_op1 = 3;
int i_l_op2 = 7;
uint ui_l_op2 = 7;
long l_l_op2 = 7;
ulong ul_l_op2 = 7;
float f_l_op2 = 7;
double d_l_op2 = 7;
decimal m_l_op2 = 7;
numHolder nHldr_l_op2 = new numHolder(7);
if ((f_l_op1 * i_l_op2 != f_l_op1 * ui_l_op2) || (f_l_op1 * ui_l_op2 != f_l_op1 * l_l_op2) || (f_l_op1 * l_l_op2 != f_l_op1 * ul_l_op2) || (f_l_op1 * ul_l_op2 != f_l_op1 * f_l_op2) || (f_l_op1 * f_l_op2 != f_l_op1 * d_l_op2) || (f_l_op1 * d_l_op2 != f_l_op1 * (float)m_l_op2) || (f_l_op1 * (float)m_l_op2 != f_l_op1 * i_l_op2) || (f_l_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 17 failed");
passed = false;
}
if ((f_l_op1 * s_i_s_op2 != f_l_op1 * s_ui_s_op2) || (f_l_op1 * s_ui_s_op2 != f_l_op1 * s_l_s_op2) || (f_l_op1 * s_l_s_op2 != f_l_op1 * s_ul_s_op2) || (f_l_op1 * s_ul_s_op2 != f_l_op1 * s_f_s_op2) || (f_l_op1 * s_f_s_op2 != f_l_op1 * s_d_s_op2) || (f_l_op1 * s_d_s_op2 != f_l_op1 * (float)s_m_s_op2) || (f_l_op1 * (float)s_m_s_op2 != f_l_op1 * s_i_s_op2) || (f_l_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 18 failed");
passed = false;
}
if ((s_f_s_op1 * i_l_op2 != s_f_s_op1 * ui_l_op2) || (s_f_s_op1 * ui_l_op2 != s_f_s_op1 * l_l_op2) || (s_f_s_op1 * l_l_op2 != s_f_s_op1 * ul_l_op2) || (s_f_s_op1 * ul_l_op2 != s_f_s_op1 * f_l_op2) || (s_f_s_op1 * f_l_op2 != s_f_s_op1 * d_l_op2) || (s_f_s_op1 * d_l_op2 != s_f_s_op1 * (float)m_l_op2) || (s_f_s_op1 * (float)m_l_op2 != s_f_s_op1 * i_l_op2) || (s_f_s_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 19 failed");
passed = false;
}
if ((s_f_s_op1 * s_i_s_op2 != s_f_s_op1 * s_ui_s_op2) || (s_f_s_op1 * s_ui_s_op2 != s_f_s_op1 * s_l_s_op2) || (s_f_s_op1 * s_l_s_op2 != s_f_s_op1 * s_ul_s_op2) || (s_f_s_op1 * s_ul_s_op2 != s_f_s_op1 * s_f_s_op2) || (s_f_s_op1 * s_f_s_op2 != s_f_s_op1 * s_d_s_op2) || (s_f_s_op1 * s_d_s_op2 != s_f_s_op1 * (float)s_m_s_op2) || (s_f_s_op1 * (float)s_m_s_op2 != s_f_s_op1 * s_i_s_op2) || (s_f_s_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 20 failed");
passed = false;
}
}
{
double d_l_op1 = 3;
int i_l_op2 = 7;
uint ui_l_op2 = 7;
long l_l_op2 = 7;
ulong ul_l_op2 = 7;
float f_l_op2 = 7;
double d_l_op2 = 7;
decimal m_l_op2 = 7;
numHolder nHldr_l_op2 = new numHolder(7);
if ((d_l_op1 * i_l_op2 != d_l_op1 * ui_l_op2) || (d_l_op1 * ui_l_op2 != d_l_op1 * l_l_op2) || (d_l_op1 * l_l_op2 != d_l_op1 * ul_l_op2) || (d_l_op1 * ul_l_op2 != d_l_op1 * f_l_op2) || (d_l_op1 * f_l_op2 != d_l_op1 * d_l_op2) || (d_l_op1 * d_l_op2 != d_l_op1 * (double)m_l_op2) || (d_l_op1 * (double)m_l_op2 != d_l_op1 * i_l_op2) || (d_l_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 21 failed");
passed = false;
}
if ((d_l_op1 * s_i_s_op2 != d_l_op1 * s_ui_s_op2) || (d_l_op1 * s_ui_s_op2 != d_l_op1 * s_l_s_op2) || (d_l_op1 * s_l_s_op2 != d_l_op1 * s_ul_s_op2) || (d_l_op1 * s_ul_s_op2 != d_l_op1 * s_f_s_op2) || (d_l_op1 * s_f_s_op2 != d_l_op1 * s_d_s_op2) || (d_l_op1 * s_d_s_op2 != d_l_op1 * (double)s_m_s_op2) || (d_l_op1 * (double)s_m_s_op2 != d_l_op1 * s_i_s_op2) || (d_l_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 22 failed");
passed = false;
}
if ((s_d_s_op1 * i_l_op2 != s_d_s_op1 * ui_l_op2) || (s_d_s_op1 * ui_l_op2 != s_d_s_op1 * l_l_op2) || (s_d_s_op1 * l_l_op2 != s_d_s_op1 * ul_l_op2) || (s_d_s_op1 * ul_l_op2 != s_d_s_op1 * f_l_op2) || (s_d_s_op1 * f_l_op2 != s_d_s_op1 * d_l_op2) || (s_d_s_op1 * d_l_op2 != s_d_s_op1 * (double)m_l_op2) || (s_d_s_op1 * (double)m_l_op2 != s_d_s_op1 * i_l_op2) || (s_d_s_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 23 failed");
passed = false;
}
if ((s_d_s_op1 * s_i_s_op2 != s_d_s_op1 * s_ui_s_op2) || (s_d_s_op1 * s_ui_s_op2 != s_d_s_op1 * s_l_s_op2) || (s_d_s_op1 * s_l_s_op2 != s_d_s_op1 * s_ul_s_op2) || (s_d_s_op1 * s_ul_s_op2 != s_d_s_op1 * s_f_s_op2) || (s_d_s_op1 * s_f_s_op2 != s_d_s_op1 * s_d_s_op2) || (s_d_s_op1 * s_d_s_op2 != s_d_s_op1 * (double)s_m_s_op2) || (s_d_s_op1 * (double)s_m_s_op2 != s_d_s_op1 * s_i_s_op2) || (s_d_s_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 24 failed");
passed = false;
}
}
{
decimal m_l_op1 = 3;
int i_l_op2 = 7;
uint ui_l_op2 = 7;
long l_l_op2 = 7;
ulong ul_l_op2 = 7;
float f_l_op2 = 7;
double d_l_op2 = 7;
decimal m_l_op2 = 7;
numHolder nHldr_l_op2 = new numHolder(7);
if ((m_l_op1 * i_l_op2 != m_l_op1 * ui_l_op2) || (m_l_op1 * ui_l_op2 != m_l_op1 * l_l_op2) || (m_l_op1 * l_l_op2 != m_l_op1 * ul_l_op2) || (m_l_op1 * ul_l_op2 != m_l_op1 * (decimal)f_l_op2) || (m_l_op1 * (decimal)f_l_op2 != m_l_op1 * (decimal)d_l_op2) || (m_l_op1 * (decimal)d_l_op2 != m_l_op1 * m_l_op2) || (m_l_op1 * m_l_op2 != m_l_op1 * i_l_op2) || (m_l_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 25 failed");
passed = false;
}
if ((m_l_op1 * s_i_s_op2 != m_l_op1 * s_ui_s_op2) || (m_l_op1 * s_ui_s_op2 != m_l_op1 * s_l_s_op2) || (m_l_op1 * s_l_s_op2 != m_l_op1 * s_ul_s_op2) || (m_l_op1 * s_ul_s_op2 != m_l_op1 * (decimal)s_f_s_op2) || (m_l_op1 * (decimal)s_f_s_op2 != m_l_op1 * (decimal)s_d_s_op2) || (m_l_op1 * (decimal)s_d_s_op2 != m_l_op1 * s_m_s_op2) || (m_l_op1 * s_m_s_op2 != m_l_op1 * s_i_s_op2) || (m_l_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 26 failed");
passed = false;
}
if ((s_m_s_op1 * i_l_op2 != s_m_s_op1 * ui_l_op2) || (s_m_s_op1 * ui_l_op2 != s_m_s_op1 * l_l_op2) || (s_m_s_op1 * l_l_op2 != s_m_s_op1 * ul_l_op2) || (s_m_s_op1 * ul_l_op2 != s_m_s_op1 * (decimal)f_l_op2) || (s_m_s_op1 * (decimal)f_l_op2 != s_m_s_op1 * (decimal)d_l_op2) || (s_m_s_op1 * (decimal)d_l_op2 != s_m_s_op1 * m_l_op2) || (s_m_s_op1 * m_l_op2 != s_m_s_op1 * i_l_op2) || (s_m_s_op1 * i_l_op2 != 21))
{
Console.WriteLine("testcase 27 failed");
passed = false;
}
if ((s_m_s_op1 * s_i_s_op2 != s_m_s_op1 * s_ui_s_op2) || (s_m_s_op1 * s_ui_s_op2 != s_m_s_op1 * s_l_s_op2) || (s_m_s_op1 * s_l_s_op2 != s_m_s_op1 * s_ul_s_op2) || (s_m_s_op1 * s_ul_s_op2 != s_m_s_op1 * (decimal)s_f_s_op2) || (s_m_s_op1 * (decimal)s_f_s_op2 != s_m_s_op1 * (decimal)s_d_s_op2) || (s_m_s_op1 * (decimal)s_d_s_op2 != s_m_s_op1 * s_m_s_op2) || (s_m_s_op1 * s_m_s_op2 != s_m_s_op1 * s_i_s_op2) || (s_m_s_op1 * s_i_s_op2 != 21))
{
Console.WriteLine("testcase 28 failed");
passed = false;
}
}
if (!passed)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
#if NET_2_0
using System.Collections.Generic;
#endif
namespace NAssert.Constraints
{
/// <summary>
/// ConstraintBuilder maintains the stacks that are used in
/// processing a ConstraintExpression. An OperatorStack
/// is used to hold operators that are waiting for their
/// operands to be reognized. a ConstraintStack holds
/// input constraints as well as the results of each
/// operator applied.
/// </summary>
public class ConstraintBuilder
{
#region Nested Operator Stack Class
/// <summary>
/// OperatorStack is a type-safe stack for holding ConstraintOperators
/// </summary>
public class OperatorStack
{
#if NET_2_0
private Stack<ConstraintOperator> stack = new Stack<ConstraintOperator>();
#else
private Stack stack = new Stack();
#endif
/// <summary>
/// Initializes a new instance of the <see cref="T:OperatorStack"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public OperatorStack(ConstraintBuilder builder)
{
}
/// <summary>
/// Gets a value indicating whether this <see cref="T:OpStack"/> is empty.
/// </summary>
/// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
public bool Empty
{
get { return stack.Count == 0; }
}
/// <summary>
/// Gets the topmost operator without modifying the stack.
/// </summary>
/// <value>The top.</value>
public ConstraintOperator Top
{
get { return (ConstraintOperator)stack.Peek(); }
}
/// <summary>
/// Pushes the specified operator onto the stack.
/// </summary>
/// <param name="op">The op.</param>
public void Push(ConstraintOperator op)
{
stack.Push(op);
}
/// <summary>
/// Pops the topmost operator from the stack.
/// </summary>
/// <returns></returns>
public ConstraintOperator Pop()
{
return (ConstraintOperator)stack.Pop();
}
}
#endregion
#region Nested Constraint Stack Class
/// <summary>
/// ConstraintStack is a type-safe stack for holding Constraints
/// </summary>
public class ConstraintStack
{
#if NET_2_0
private Stack<Constraint> stack = new Stack<Constraint>();
#else
private Stack stack = new Stack();
#endif
private ConstraintBuilder builder;
/// <summary>
/// Initializes a new instance of the <see cref="T:ConstraintStack"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public ConstraintStack(ConstraintBuilder builder)
{
this.builder = builder;
}
/// <summary>
/// Gets a value indicating whether this <see cref="T:ConstraintStack"/> is empty.
/// </summary>
/// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
public bool Empty
{
get { return stack.Count == 0; }
}
/// <summary>
/// Gets the topmost constraint without modifying the stack.
/// </summary>
/// <value>The topmost constraint</value>
public Constraint Top
{
get { return (Constraint)stack.Peek(); }
}
/// <summary>
/// Pushes the specified constraint. As a side effect,
/// the constraint's builder field is set to the
/// ConstraintBuilder owning this stack.
/// </summary>
/// <param name="constraint">The constraint.</param>
public void Push(Constraint constraint)
{
stack.Push(constraint);
constraint.SetBuilder( this.builder );
}
/// <summary>
/// Pops this topmost constrait from the stack.
/// As a side effect, the constraint's builder
/// field is set to null.
/// </summary>
/// <returns></returns>
public Constraint Pop()
{
Constraint constraint = (Constraint)stack.Pop();
constraint.SetBuilder( null );
return constraint;
}
}
#endregion
#region Instance Fields
private OperatorStack ops;
private ConstraintStack constraints;
private object lastPushed;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="T:ConstraintBuilder"/> class.
/// </summary>
public ConstraintBuilder()
{
this.ops = new OperatorStack(this);
this.constraints = new ConstraintStack(this);
}
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether this instance is resolvable.
/// </summary>
/// <value>
/// <c>true</c> if this instance is resolvable; otherwise, <c>false</c>.
/// </value>
public bool IsResolvable
{
get { return lastPushed is Constraint || lastPushed is SelfResolvingOperator; }
}
#endregion
#region Public Methods
/// <summary>
/// Appends the specified operator to the expression by first
/// reducing the operator stack and then pushing the new
/// operator on the stack.
/// </summary>
/// <param name="op">The operator to push.</param>
public void Append(ConstraintOperator op)
{
op.LeftContext = lastPushed;
if (lastPushed is ConstraintOperator)
SetTopOperatorRightContext(op);
// Reduce any lower precedence operators
ReduceOperatorStack(op.LeftPrecedence);
ops.Push(op);
lastPushed = op;
}
/// <summary>
/// Appends the specified constraint to the expresson by pushing
/// it on the constraint stack.
/// </summary>
/// <param name="constraint">The constraint to push.</param>
public void Append(Constraint constraint)
{
if (lastPushed is ConstraintOperator)
SetTopOperatorRightContext(constraint);
constraints.Push(constraint);
lastPushed = constraint;
constraint.SetBuilder( this );
}
/// <summary>
/// Sets the top operator right context.
/// </summary>
/// <param name="rightContext">The right context.</param>
private void SetTopOperatorRightContext(object rightContext)
{
// Some operators change their precedence based on
// the right context - save current precedence.
int oldPrecedence = ops.Top.LeftPrecedence;
ops.Top.RightContext = rightContext;
// If the precedence increased, we may be able to
// reduce the region of the stack below the operator
if (ops.Top.LeftPrecedence > oldPrecedence)
{
ConstraintOperator changedOp = ops.Pop();
ReduceOperatorStack(changedOp.LeftPrecedence);
ops.Push(changedOp);
}
}
/// <summary>
/// Reduces the operator stack until the topmost item
/// precedence is greater than or equal to the target precedence.
/// </summary>
/// <param name="targetPrecedence">The target precedence.</param>
private void ReduceOperatorStack(int targetPrecedence)
{
while (!ops.Empty && ops.Top.RightPrecedence < targetPrecedence)
ops.Pop().Reduce(constraints);
}
/// <summary>
/// Resolves this instance, returning a Constraint. If the builder
/// is not currently in a resolvable state, an exception is thrown.
/// </summary>
/// <returns>The resolved constraint</returns>
public Constraint Resolve()
{
if (!IsResolvable)
throw new InvalidOperationException("A partial expression may not be resolved");
while (!ops.Empty)
{
ConstraintOperator op = ops.Pop();
op.Reduce(constraints);
}
return constraints.Pop();
}
#endregion
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class AttachSegmentsRequestDecoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 56;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private AttachSegmentsRequestDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public AttachSegmentsRequestDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public AttachSegmentsRequestDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int RecordingIdId()
{
return 3;
}
public static int RecordingIdSinceVersion()
{
return 0;
}
public static int RecordingIdEncodingOffset()
{
return 16;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long RecordingId()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[AttachSegmentsRequest](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("RecordingId=");
builder.Append(RecordingId());
Limit(originalLimit);
return builder;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.InvokeDelegateWithConditionalAccess
{
internal static class Constants
{
public const string Kind = nameof(Kind);
public const string VariableAndIfStatementForm = nameof(VariableAndIfStatementForm);
public const string SingleIfStatementForm = nameof(SingleIfStatementForm);
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class InvokeDelegateWithConditionalAccessAnalyzer : DiagnosticAnalyzer, IBuiltInAnalyzer
{
private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor(
IDEDiagnosticIds.InvokeDelegateWithConditionalAccessId,
CSharpFeaturesResources.Delegate_invocation_can_be_simplified,
CSharpFeaturesResources.Delegate_invocation_can_be_simplified,
DiagnosticCategory.Style,
DiagnosticSeverity.Hidden,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor);
public bool RunInProcess => false;
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(SyntaxNodeAction, SyntaxKind.IfStatement);
}
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
{
// look for the form "if (a != null)" or "if (null != a)"
var ifStatement = (IfStatementSyntax)syntaxContext.Node;
// ?. is only available in C# 6.0 and above. Don't offer this refactoring
// in projects targetting a lesser version.
if (((CSharpParseOptions)ifStatement.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp6)
{
return;
}
if (!ifStatement.Condition.IsKind(SyntaxKind.NotEqualsExpression))
{
return;
}
if (ifStatement.Else != null)
{
return;
}
// Check for both: "if (...) { a(); }" and "if (...) a();"
var innerStatement = ifStatement.Statement;
if (innerStatement.IsKind(SyntaxKind.Block))
{
var block = (BlockSyntax)innerStatement;
if (block.Statements.Count != 1)
{
return;
}
innerStatement = block.Statements[0];
}
if (!innerStatement.IsKind(SyntaxKind.ExpressionStatement))
{
return;
}
var expressionStatement = (ExpressionStatementSyntax)innerStatement;
// Check that it's of the form: "if (a != null) { a(); }
var invocationExpression = ((ExpressionStatementSyntax)innerStatement).Expression as InvocationExpressionSyntax;
if (invocationExpression == null)
{
return;
}
var condition = (BinaryExpressionSyntax)ifStatement.Condition;
if (TryCheckVariableAndIfStatementForm(syntaxContext, ifStatement, condition, expressionStatement, invocationExpression))
{
return;
}
TryCheckSingleIfStatementForm(syntaxContext, ifStatement, condition, expressionStatement, invocationExpression);
}
private bool TryCheckSingleIfStatementForm(
SyntaxNodeAnalysisContext syntaxContext,
IfStatementSyntax ifStatement,
BinaryExpressionSyntax condition,
ExpressionStatementSyntax expressionStatement,
InvocationExpressionSyntax invocationExpression)
{
var cancellationToken = syntaxContext.CancellationToken;
// Look for the form: "if (someExpr != null) someExpr()"
if (condition.Left.IsKind(SyntaxKind.NullLiteralExpression) ||
condition.Right.IsKind(SyntaxKind.NullLiteralExpression))
{
var expr = condition.Left.IsKind(SyntaxKind.NullLiteralExpression)
? condition.Right
: condition.Left;
cancellationToken.ThrowIfCancellationRequested();
if (SyntaxFactory.AreEquivalent(expr, invocationExpression.Expression, topLevel: false))
{
cancellationToken.ThrowIfCancellationRequested();
// Looks good!
var tree = syntaxContext.SemanticModel.SyntaxTree;
var additionalLocations = new List<Location>
{
Location.Create(tree, ifStatement.Span),
Location.Create(tree, expressionStatement.Span)
};
var properties = ImmutableDictionary<string, string>.Empty.Add(Constants.Kind, Constants.SingleIfStatementForm);
syntaxContext.ReportDiagnostic(Diagnostic.Create(s_descriptor,
Location.Create(tree, TextSpan.FromBounds(ifStatement.SpanStart, expressionStatement.SpanStart)),
additionalLocations, properties));
if (expressionStatement.Span.End != ifStatement.Span.End)
{
syntaxContext.ReportDiagnostic(Diagnostic.Create(s_descriptor,
Location.Create(tree, TextSpan.FromBounds(expressionStatement.Span.End, ifStatement.Span.End)),
additionalLocations, properties));
}
return true;
}
}
return false;
}
private bool TryCheckVariableAndIfStatementForm(
SyntaxNodeAnalysisContext syntaxContext,
IfStatementSyntax ifStatement,
BinaryExpressionSyntax condition,
ExpressionStatementSyntax expressionStatement,
InvocationExpressionSyntax invocationExpression)
{
var cancellationToken = syntaxContext.CancellationToken;
cancellationToken.ThrowIfCancellationRequested();
// look for the form "if (a != null)" or "if (null != a)"
if (!ifStatement.Parent.IsKind(SyntaxKind.Block))
{
return false;
}
if (!IsNullCheckExpression(condition.Left, condition.Right) &&
!IsNullCheckExpression(condition.Right, condition.Left))
{
return false;
}
var expression = invocationExpression.Expression;
if (!expression.IsKind(SyntaxKind.IdentifierName))
{
return false;
}
var conditionName = condition.Left is IdentifierNameSyntax
? (IdentifierNameSyntax)condition.Left
: (IdentifierNameSyntax)condition.Right;
var invocationName = (IdentifierNameSyntax)expression;
if (!Equals(conditionName.Identifier.ValueText, invocationName.Identifier.ValueText))
{
return false;
}
// Now make sure the previous statement is "var a = ..."
var parentBlock = (BlockSyntax)ifStatement.Parent;
var ifIndex = parentBlock.Statements.IndexOf(ifStatement);
if (ifIndex == 0)
{
return false;
}
var previousStatement = parentBlock.Statements[ifIndex - 1];
if (!previousStatement.IsKind(SyntaxKind.LocalDeclarationStatement))
{
return false;
}
var localDeclarationStatement = (LocalDeclarationStatementSyntax)previousStatement;
var variableDeclaration = localDeclarationStatement.Declaration;
if (variableDeclaration.Variables.Count != 1)
{
return false;
}
var declarator = variableDeclaration.Variables[0];
if (declarator.Initializer == null)
{
return false;
}
cancellationToken.ThrowIfCancellationRequested();
if (!Equals(declarator.Identifier.ValueText, conditionName.Identifier.ValueText))
{
return false;
}
// Syntactically this looks good. Now make sure that the local is a delegate type.
var semanticModel = syntaxContext.SemanticModel;
var localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken);
// Ok, we made a local just to check it for null and invoke it. Looks like something
// we can suggest an improvement for!
// But first make sure we're only using the local only within the body of this if statement.
var analysis = semanticModel.AnalyzeDataFlow(localDeclarationStatement, ifStatement);
if (analysis.ReadOutside.Contains(localSymbol) || analysis.WrittenOutside.Contains(localSymbol))
{
return false;
}
// Looks good!
var tree = semanticModel.SyntaxTree;
var additionalLocations = new List<Location>
{
Location.Create(tree, localDeclarationStatement.Span),
Location.Create(tree, ifStatement.Span),
Location.Create(tree, expressionStatement.Span)
};
var properties = ImmutableDictionary<string, string>.Empty.Add(Constants.Kind, Constants.VariableAndIfStatementForm);
syntaxContext.ReportDiagnostic(Diagnostic.Create(s_descriptor,
Location.Create(tree, TextSpan.FromBounds(localDeclarationStatement.SpanStart, expressionStatement.SpanStart)),
additionalLocations, properties));
if (expressionStatement.Span.End != ifStatement.Span.End)
{
syntaxContext.ReportDiagnostic(Diagnostic.Create(s_descriptor,
Location.Create(tree, TextSpan.FromBounds(expressionStatement.Span.End, ifStatement.Span.End)),
additionalLocations, properties));
}
return true;
}
private bool IsNullCheckExpression(ExpressionSyntax left, ExpressionSyntax right) =>
left.IsKind(SyntaxKind.IdentifierName) && right.IsKind(SyntaxKind.NullLiteralExpression);
public DiagnosticAnalyzerCategory GetAnalyzerCategory()
{
return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis;
}
}
}
| |
// -------------------------------------------------------------------------------------------
// <copyright file="EntityHelper.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// -------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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 Sitecore.Ecommerce.Data
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using Diagnostics;
using DomainModel.Data;
using Microsoft.Practices.Unity;
using Sitecore.Ecommerce.Unity;
using Utils;
/// <summary>
/// The Entity Serializer implementation.
/// </summary>
public class EntityHelper
{
/// <summary>
/// Serializes the specified entity to the key-value collection of properties values.
/// </summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <param name="entity">The entity. </param>
/// <returns>The key-value collection of properties values.</returns>
public virtual IDictionary<string, object> GetPropertiesValues<T>(T entity)
{
Assert.ArgumentNotNull(entity, "entity");
Dictionary<string, object> dictionary = new Dictionary<string, object>();
var entityType = entity.GetType();
object obj = Context.Entity.HasRegistration(entityType) ? Context.Entity.Resolve(entityType) : entity;
foreach (PropertyInfo info in entity.GetType().GetProperties())
{
EntityAttribute entityAttribute = Attribute.GetCustomAttribute(obj.GetType().GetProperty(info.Name), typeof(EntityAttribute)) as EntityAttribute;
if (entityAttribute == null || string.IsNullOrEmpty(entityAttribute.FieldName))
{
continue;
}
if (info.PropertyType.IsClass && !info.PropertyType.IsValueType && !info.PropertyType.IsPrimitive && info.PropertyType.FullName != "System.String")
{
object nestedEntity = info.GetValue(entity, null);
IDictionary<string, object> fieldsCollection = nestedEntity != null ? this.GetPropertiesValues(nestedEntity) : new Dictionary<string, object>();
if (nestedEntity is IEntity)
{
string aliasValue = ((IEntity)nestedEntity).Alias;
if (!dictionary.ContainsKey(entityAttribute.FieldName))
{
dictionary.Add(entityAttribute.FieldName, aliasValue);
}
}
foreach (KeyValuePair<string, object> keyValuePair in fieldsCollection)
{
string key = string.Concat(entityAttribute.FieldName, keyValuePair.Key);
if (!dictionary.ContainsKey(key))
{
dictionary.Add(key, keyValuePair.Value);
}
}
}
else
{
if (!dictionary.ContainsKey(entityAttribute.FieldName))
{
dictionary.Add(entityAttribute.FieldName, info.GetValue(entity, null));
}
}
}
return dictionary;
}
/// <summary>
/// Gets the field.
/// </summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <param name="property">The property.</param>
/// <returns>The field name.</returns>
public virtual string GetField<T>(Expression<Func<T, object>> property)
{
Assert.ArgumentNotNull(property, "property");
Assert.ArgumentNotNull(property.Body, "property.Body");
MemberExpression memberExpression = property.Body as MemberExpression;
if (memberExpression == null)
{
return string.Empty;
}
string propertyName = memberExpression.Member.Name;
return string.IsNullOrEmpty(propertyName) ? string.Empty : this.GetField(typeof(T), propertyName);
}
/// <summary>
/// Gets the field.
/// </summary>
/// <param name="type">The entity type.</param>
/// <param name="propertyName">Name of the property.</param>
/// <returns>The field name.</returns>
public virtual string GetField(Type type, string propertyName)
{
Assert.ArgumentNotNullOrEmpty(propertyName, "propertyName");
Assert.ArgumentNotNull(type, "type");
if (Context.Entity.HasRegistration(type))
{
type = Context.Entity.Resolve(type).GetType();
}
PropertyInfo info = type.GetProperty(propertyName);
if (info == null)
{
return string.Empty;
}
EntityAttribute entityAttribute = Attribute.GetCustomAttribute(info, typeof(EntityAttribute), true) as EntityAttribute;
if (entityAttribute == null || string.IsNullOrEmpty(entityAttribute.FieldName))
{
return string.Empty;
}
return entityAttribute.FieldName;
}
/// <summary>
/// Gets the template.
/// </summary>
/// <param name="type">The type of the object.</param>
/// <returns>The template Id.</returns>
public virtual string GetTemplate(Type type)
{
Assert.ArgumentNotNull(type, "type");
if (Context.Entity.HasRegistration(type))
{
type = Context.Entity.Resolve(type).GetType();
}
EntityAttribute entityAttribute = Attribute.GetCustomAttribute(type, typeof(EntityAttribute), true) as EntityAttribute;
if (entityAttribute != null && !string.IsNullOrEmpty(entityAttribute.TemplateId))
{
return entityAttribute.TemplateId;
}
return string.Empty;
}
/// <summary>
/// Gets the template.
/// </summary>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The template Id.</returns>
public virtual string GetTemplate<T>()
{
return this.GetTemplate(typeof(T));
}
/// <summary>
/// Gets the name of the property value by attribute.
/// </summary>
/// <typeparam name="T">The object type.</typeparam>
/// <typeparam name="Tr">The type of the business object.</typeparam>
/// <param name="entity">The entity instance.</param>
/// <param name="fieldName">Name of the field.</param>
/// <returns>The object value.</returns>
public virtual T GetPropertyValueByField<T, Tr>(Tr entity, string fieldName)
{
Assert.ArgumentNotNull(entity, "entity");
Assert.ArgumentNotNullOrEmpty(fieldName, "fieldName");
var entityType = entity.GetType();
object obj = Context.Entity.HasRegistration(entityType) ? Context.Entity.Resolve(entityType) : entity;
foreach (PropertyInfo info in entity.GetType().GetProperties())
{
EntityAttribute entityAttribute = Attribute.GetCustomAttribute(obj.GetType().GetProperty(info.Name), typeof(EntityAttribute), true) as EntityAttribute;
if (entityAttribute == null || string.IsNullOrEmpty(entityAttribute.FieldName) || !string.Equals(fieldName, entityAttribute.FieldName))
{
continue;
}
return TypeUtil.TryParse(info.GetValue(entity, null), default(T));
}
return default(T);
}
/// <summary>
/// Copies the properties values.
/// </summary>
/// <typeparam name="T">The type of the source entity</typeparam>
/// <typeparam name="Tr">The type of the target entity.</typeparam>
/// <param name="sourceEntity">The source entity.</param>
/// <param name="targetEntity">The target entity.</param>
public virtual void CopyPropertiesValues<T, Tr>(T sourceEntity, ref Tr targetEntity)
{
Assert.ArgumentNotNull(sourceEntity, "Argument source entity is null");
Assert.ArgumentNotNull(targetEntity, "Argument target entity is null");
var sourceEntityType = sourceEntity.GetType();
object sourceObject = Context.Entity.HasRegistration(sourceEntityType) ? Context.Entity.Resolve(sourceEntityType) : sourceEntity;
var targetEntityType = targetEntity.GetType();
object targetObject = Context.Entity.HasRegistration(targetEntityType) ? Context.Entity.Resolve(targetEntityType) : targetEntity;
foreach (PropertyInfo targetInfo in targetEntity.GetType().GetProperties())
{
EntityAttribute targetEntityAttribute = Attribute.GetCustomAttribute(targetObject.GetType().GetProperty(targetInfo.Name), typeof(EntityAttribute)) as EntityAttribute;
if (targetEntityAttribute == null || string.IsNullOrEmpty(targetEntityAttribute.FieldName))
{
continue;
}
foreach (PropertyInfo sourceInfo in sourceEntity.GetType().GetProperties())
{
EntityAttribute sourcerEntityAttribute = Attribute.GetCustomAttribute(sourceObject.GetType().GetProperty(sourceInfo.Name), typeof(EntityAttribute)) as EntityAttribute;
if (sourcerEntityAttribute == null || string.IsNullOrEmpty(sourcerEntityAttribute.FieldName) || !string.Equals(sourcerEntityAttribute.FieldName, targetEntityAttribute.FieldName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (!sourceInfo.CanRead || !targetInfo.CanWrite || sourceInfo.PropertyType != targetInfo.PropertyType)
{
continue;
}
object source = sourceInfo.GetValue(sourceEntity, null);
if (source != null)
{
targetInfo.SetValue(targetEntity, source, null);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using BTDB.StreamLayer;
namespace BTDB.KVDBLayer
{
public class InMemoryFileCollection : IFileCollection
{
// disable invalid warning about using volatile inside Interlocked.CompareExchange
#pragma warning disable 420
volatile Dictionary<uint, File> _files = new Dictionary<uint, File>();
int _maxFileId;
public InMemoryFileCollection()
{
_maxFileId = 0;
}
class File : IFileCollectionFile
{
readonly InMemoryFileCollection _owner;
readonly uint _index;
byte[][] _data = Array.Empty<byte[]>();
readonly Writer _writer;
long _flushedSize;
const int OneBufSize = 128 * 1024;
public File(InMemoryFileCollection owner, uint index)
{
_owner = owner;
_index = index;
_writer = new Writer(this);
}
public uint Index => _index;
sealed class Reader : AbstractBufferedReader
{
readonly File _file;
ulong _ofs;
readonly ulong _totalSize;
public Reader(File file)
{
_file = file;
_totalSize = file.GetSize();
_ofs = 0;
FillBuffer();
}
protected override void FillBuffer()
{
if (_ofs == _totalSize)
{
Pos = -1;
End = -1;
return;
}
Buf = _file._data[(int) (_ofs / OneBufSize)];
End = (int) Math.Min(_totalSize - _ofs, OneBufSize);
_ofs += (ulong) End;
Pos = 0;
}
public override long GetCurrentPosition()
{
return (long) _ofs - End + Pos;
}
}
public AbstractBufferedReader GetExclusiveReader()
{
return new Reader(this);
}
public void AdvisePrefetch()
{
}
public void RandomRead(Span<byte> data, ulong position, bool doNotCache)
{
var storage = Volatile.Read(ref _data);
while (!data.IsEmpty)
{
var buf = storage[(int) (position / OneBufSize)];
var bufOfs = (int) (position % OneBufSize);
var copy = Math.Min(data.Length, OneBufSize - bufOfs);
buf.AsSpan(bufOfs,copy).CopyTo(data);
data = data.Slice(copy);
position += (ulong) copy;
}
}
sealed class Writer : AbstractBufferedWriter
{
readonly File _file;
ulong _ofs;
public Writer(File file)
{
_file = file;
Pos = 0;
Buf = null;
End = 0;
}
public override void FlushBuffer()
{
if (Pos != End) return;
_ofs += (ulong)End;
Pos = 0;
Buf = new byte[OneBufSize];
End = OneBufSize;
var storage = _file._data;
Array.Resize(ref storage, storage.Length + 1);
storage[storage.Length - 1] = Buf;
Volatile.Write(ref _file._data, storage);
}
public override long GetCurrentPosition()
{
return (long) (_ofs + (ulong) Pos);
}
internal void SimulateCorruptionBySetSize(int size)
{
if (size > OneBufSize || _ofs != 0) throw new ArgumentOutOfRangeException();
Array.Clear(Buf, size, Pos - size);
Pos = size;
}
}
public AbstractBufferedWriter GetAppenderWriter()
{
return _writer;
}
public AbstractBufferedWriter GetExclusiveAppenderWriter()
{
return _writer;
}
public void Flush()
{
_flushedSize = _writer.GetCurrentPosition();
Interlocked.MemoryBarrier();
}
public void HardFlush()
{
Flush();
}
public void SetSize(long size)
{
if ((ulong) size != GetSize())
throw new InvalidOperationException(
"For in memory collection SetSize should never be set to something else than GetSize");
}
public void Truncate()
{
}
public void HardFlushTruncateSwitchToReadOnlyMode()
{
Flush();
}
public void HardFlushTruncateSwitchToDisposedMode()
{
Flush();
}
public ulong GetSize()
{
Volatile.Read(ref _data);
return (ulong) _flushedSize;
}
public void Remove()
{
Dictionary<uint, File> newFiles;
Dictionary<uint, File> oldFiles;
do
{
oldFiles = _owner._files;
File value;
if (!oldFiles.TryGetValue(_index, out value)) return;
newFiles = new Dictionary<uint, File>(oldFiles);
newFiles.Remove(_index);
} while (Interlocked.CompareExchange(ref _owner._files, newFiles, oldFiles) != oldFiles);
}
internal void SimulateCorruptionBySetSize(int size)
{
_writer.SimulateCorruptionBySetSize(size);
}
}
public IFileCollectionFile AddFile(string humanHint)
{
var index = (uint) Interlocked.Increment(ref _maxFileId);
var file = new File(this, index);
Dictionary<uint, File> newFiles;
Dictionary<uint, File> oldFiles;
do
{
oldFiles = _files;
newFiles = new Dictionary<uint, File>(oldFiles) {{index, file}};
} while (Interlocked.CompareExchange(ref _files, newFiles, oldFiles) != oldFiles);
return file;
}
public uint GetCount()
{
return (uint) _files.Count;
}
public IFileCollectionFile GetFile(uint index)
{
File value;
return _files.TryGetValue(index, out value) ? value : null;
}
public IEnumerable<IFileCollectionFile> Enumerate()
{
return _files.Values;
}
public void ConcurrentTemporaryTruncate(uint index, uint offset)
{
// Nothing to do
}
public void Dispose()
{
}
internal void SimulateCorruptionBySetSize(int size)
{
_files[1].SimulateCorruptionBySetSize(size);
}
}
}
| |
// 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.Immutable;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class DynamicTests : CSharpResultProviderTestBase
{
[Fact]
public void Simple()
{
var value = CreateDkmClrValue(new object());
var rootExpr = "d";
var evalResult = FormatResult(rootExpr, rootExpr, value, declaredType: new DkmClrType((TypeImpl)typeof(object)), declaredTypeInfo: new[] { true });
Verify(evalResult,
EvalResult(rootExpr, "{object}", "dynamic {object}", rootExpr));
}
[Fact]
public void Member()
{
var source = @"
class C
{
dynamic F;
dynamic P { get; set; }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(Activator.CreateInstance(type));
var rootExpr = "new C()";
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "null", "dynamic {object}", "(new C()).F"),
EvalResult("P", "null", "dynamic {object}", "(new C()).P"));
}
[Fact]
public void Member_ConstructedType()
{
var source = @"
class C<T, U>
{
T Simple;
U[] Array;
C<U, T> Constructed;
C<C<C<object, T>, dynamic[]>, U[]>[] Complex;
}";
var assembly = GetAssembly(source);
var typeC = assembly.GetType("C`2");
var typeC_Constructed1 = typeC.MakeGenericType(typeof(object), typeof(object)); // C<object, dynamic>
var typeC_Constructed2 = typeC.MakeGenericType(typeof(object), typeC_Constructed1); // C<dynamic, C<object, dynamic>> (i.e. T = dynamic, U = C<object, dynamic>)
var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed2));
var rootExpr = "c";
var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed2), new[] { false, true, false, false, true });
Verify(evalResult,
EvalResult(rootExpr, "{C<object, C<object, object>>}", "C<dynamic, C<object, dynamic>> {C<object, C<object, object>>}", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Array", "null", "C<object, dynamic>[] {C<object, object>[]}", "c.Array"),
EvalResult("Complex", "null", "C<C<C<object, dynamic>, dynamic[]>, C<object, dynamic>[]>[] {C<C<C<object, object>, object[]>, C<object, object>[]>[]}", "c.Complex"),
EvalResult("Constructed", "null", "C<C<object, dynamic>, dynamic> {C<C<object, object>, object>}", "c.Constructed"),
EvalResult("Simple", "null", "dynamic {object}", "c.Simple"));
}
[Fact]
public void Member_NestedType()
{
var source = @"
class Outer<T>
{
class Inner<U>
{
T Simple;
U[] Array;
Outer<U>.Inner<T> Constructed;
}
}";
var assembly = GetAssembly(source);
var typeInner = assembly.GetType("Outer`1+Inner`1");
var typeInner_Constructed = typeInner.MakeGenericType(typeof(object), typeof(object)); // Outer<dynamic>.Inner<object>
var value = CreateDkmClrValue(Activator.CreateInstance(typeInner_Constructed));
var rootExpr = "i";
var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeInner_Constructed), new[] { false, true, false });
Verify(evalResult,
EvalResult(rootExpr, "{Outer<object>.Inner<object>}", "Outer<dynamic>.Inner<object> {Outer<object>.Inner<object>}", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Array", "null", "object[]", "i.Array"),
EvalResult("Constructed", "null", "Outer<object>.Inner<dynamic> {Outer<object>.Inner<object>}", "i.Constructed"),
EvalResult("Simple", "null", "dynamic {object}", "i.Simple"));
}
[Fact]
public void Member_ConstructedTypeMember()
{
var source = @"
class C<T>
where T : new()
{
T Simple = new T();
T[] Array = new[] { new T() };
D<T, object, dynamic> Constructed = new D<T, object, dynamic>();
}
class D<T, U, V>
{
T TT;
U UU;
V VV;
}";
var assembly = GetAssembly(source);
var typeD = assembly.GetType("D`3");
var typeD_Constructed = typeD.MakeGenericType(typeof(object), typeof(object), typeof(int)); // D<object, dynamic, int>
var typeC = assembly.GetType("C`1");
var typeC_Constructed = typeC.MakeGenericType(typeD_Constructed); // C<D<object, dynamic, int>>
var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed));
var rootExpr = "c";
var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed), new[] { false, false, false, true, false });
Verify(evalResult,
EvalResult(rootExpr, "{C<D<object, object, int>>}", "C<D<object, dynamic, int>> {C<D<object, object, int>>}", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Array", "{D<object, object, int>[1]}", "D<object, dynamic, int>[] {D<object, object, int>[]}", "c.Array", DkmEvaluationResultFlags.Expandable),
EvalResult("Constructed", "{D<D<object, object, int>, object, object>}", "D<D<object, dynamic, int>, object, dynamic> {D<D<object, object, int>, object, object>}", "c.Constructed", DkmEvaluationResultFlags.Expandable),
EvalResult("Simple", "{D<object, object, int>}", "D<object, dynamic, int> {D<object, object, int>}", "c.Simple", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[0]),
EvalResult("[0]", "{D<object, object, int>}", "D<object, dynamic, int> {D<object, object, int>}", "c.Array[0]", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[1]),
EvalResult("TT", "null", "D<object, dynamic, int> {D<object, object, int>}", "c.Constructed.TT"),
EvalResult("UU", "null", "object", "c.Constructed.UU"),
EvalResult("VV", "null", "dynamic {object}", "c.Constructed.VV"));
Verify(GetChildren(children[2]),
EvalResult("TT", "null", "object", "c.Simple.TT"),
EvalResult("UU", "null", "dynamic {object}", "c.Simple.UU"),
EvalResult("VV", "0", "int", "c.Simple.VV"));
}
[Fact]
public void Member_ExplicitInterfaceImplementation()
{
var source = @"
interface I<V, W>
{
V P { get; set; }
W Q { get; set; }
}
class C<T, U> : I<long, T>, I<bool, U>
{
long I<long, T>.P { get; set; }
T I<long, T>.Q { get; set; }
bool I<bool, U>.P { get; set; }
U I<bool, U>.Q { get; set; }
}";
var assembly = GetAssembly(source);
var typeC = assembly.GetType("C`2");
var typeC_Constructed = typeC.MakeGenericType(typeof(object), typeof(object)); // C<dynamic, object>
var value = CreateDkmClrValue(Activator.CreateInstance(typeC_Constructed));
var rootExpr = "c";
var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeC_Constructed), new[] { false, true, false });
Verify(evalResult,
EvalResult(rootExpr, "{C<object, object>}", "C<dynamic, object> {C<object, object>}", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("I<bool, object>.P", "false", "bool", "((I<bool, object>)c).P", DkmEvaluationResultFlags.Boolean),
EvalResult("I<bool, object>.Q", "null", "object", "((I<bool, object>)c).Q"),
EvalResult("I<long, dynamic>.P", "0", "long", "((I<long, dynamic>)c).P"),
EvalResult("I<long, dynamic>.Q", "null", "dynamic {object}", "((I<long, dynamic>)c).Q"));
}
[Fact]
public void Member_BaseType()
{
var source = @"
class Base<T, U, V, W>
{
public T P;
public U Q;
public V R;
public W S;
}
class Derived<T, U> : Base<T, U, object, dynamic>
{
new public T[] P;
new public U[] Q;
new public dynamic[] R;
new public object[] S;
}";
var assembly = GetAssembly(source);
var typeDerived = assembly.GetType("Derived`2");
var typeDerived_Constructed = typeDerived.MakeGenericType(typeof(object), typeof(object)); // Derived<dynamic, object>
var value = CreateDkmClrValue(Activator.CreateInstance(typeDerived_Constructed));
var rootExpr = "d";
var evalResult = FormatResult(rootExpr, rootExpr, value, new DkmClrType((TypeImpl)typeDerived_Constructed), new[] { false, true, false });
Verify(evalResult,
EvalResult(rootExpr, "{Derived<object, object>}", "Derived<dynamic, object> {Derived<object, object>}", rootExpr, DkmEvaluationResultFlags.Expandable));
// CONSIDER: It would be nice to substitute "dynamic" where appropriate.
var children = GetChildren(evalResult);
Verify(children,
EvalResult("P (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).P"),
EvalResult("P", "null", "dynamic[] {object[]}", "d.P"),
EvalResult("Q (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).Q"),
EvalResult("Q", "null", "object[]", "d.Q"),
EvalResult("R (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).R"),
EvalResult("R", "null", "dynamic[] {object[]}", "d.R"),
EvalResult("S (Base<object, object, object, object>)", "null", "object", "((Base<object, object, object, object>)d).S"),
EvalResult("S", "null", "object[]", "d.S"));
}
[Fact]
public void ArrayElement()
{
var value = CreateDkmClrValue(new object[1]);
var rootExpr = "d";
var evalResult = FormatResult(rootExpr, rootExpr, value, declaredType: new DkmClrType((TypeImpl)typeof(object[])), declaredTypeInfo: new[] { false, true });
Verify(evalResult,
EvalResult(rootExpr, "{object[1]}", "dynamic[] {object[]}", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "null", "dynamic {object}", "d[0]"));
}
[Fact]
public void TypeVariables()
{
var intrinsicSource =
@".class private abstract sealed beforefieldinit specialname '<>c__TypeVariables'<T,U,V>
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ret }
}";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CommonTestBase.EmitILToArray(intrinsicSource, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var reflectionType = assembly.GetType(ExpressionCompilerConstants.TypeVariablesClassName).MakeGenericType(new[] { typeof(object), typeof(object), typeof(object[]) });
var value = CreateDkmClrValue(value: null, type: reflectionType, valueFlags: DkmClrValueFlags.Synthetic);
var evalResult = FormatResult("typevars", "typevars", value, new DkmClrType((TypeImpl)reflectionType), new[] { false, true, false, false, true });
Verify(evalResult,
EvalResult("Type variables", "", "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("T", "dynamic", "dynamic", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("U", "object", "object", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("V", "dynamic[]", "dynamic[]", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the CreateDBCluster operation.
/// Creates a new Amazon Aurora DB cluster. For more information on Amazon Aurora, see
/// <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Aurora.html">Aurora
/// on Amazon RDS</a> in the <i>Amazon RDS User Guide.</i>
/// </summary>
public partial class CreateDBClusterRequest : AmazonRDSRequest
{
private List<string> _availabilityZones = new List<string>();
private int? _backupRetentionPeriod;
private string _characterSetName;
private string _databaseName;
private string _dbClusterIdentifier;
private string _dbClusterParameterGroupName;
private string _dbSubnetGroupName;
private string _engine;
private string _engineVersion;
private string _masterUsername;
private string _masterUserPassword;
private string _optionGroupName;
private int? _port;
private string _preferredBackupWindow;
private string _preferredMaintenanceWindow;
private List<Tag> _tags = new List<Tag>();
private List<string> _vpcSecurityGroupIds = new List<string>();
/// <summary>
/// Gets and sets the property AvailabilityZones.
/// <para>
/// A list of EC2 Availability Zones that instances in the DB cluster can be created in.
/// For information on regions and Availability Zones, see <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html">Regions
/// and Availability Zones</a>.
/// </para>
/// </summary>
public List<string> AvailabilityZones
{
get { return this._availabilityZones; }
set { this._availabilityZones = value; }
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this._availabilityZones != null && this._availabilityZones.Count > 0;
}
/// <summary>
/// Gets and sets the property BackupRetentionPeriod.
/// <para>
/// The number of days for which automated backups are retained. Setting this parameter
/// to a positive number enables backups. Setting this parameter to 0 disables automated
/// backups.
/// </para>
///
/// <para>
/// Default: 1
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be a value from 0 to 35</li> </ul>
/// </summary>
public int BackupRetentionPeriod
{
get { return this._backupRetentionPeriod.GetValueOrDefault(); }
set { this._backupRetentionPeriod = value; }
}
// Check to see if BackupRetentionPeriod property is set
internal bool IsSetBackupRetentionPeriod()
{
return this._backupRetentionPeriod.HasValue;
}
/// <summary>
/// Gets and sets the property CharacterSetName.
/// <para>
/// A value that indicates that the DB cluster should be associated with the specified
/// CharacterSet.
/// </para>
/// </summary>
public string CharacterSetName
{
get { return this._characterSetName; }
set { this._characterSetName = value; }
}
// Check to see if CharacterSetName property is set
internal bool IsSetCharacterSetName()
{
return this._characterSetName != null;
}
/// <summary>
/// Gets and sets the property DatabaseName.
/// <para>
/// The name for your database of up to 8 alpha-numeric characters. If you do not provide
/// a name, Amazon RDS will not create a database in the DB cluster you are creating.
/// </para>
/// </summary>
public string DatabaseName
{
get { return this._databaseName; }
set { this._databaseName = value; }
}
// Check to see if DatabaseName property is set
internal bool IsSetDatabaseName()
{
return this._databaseName != null;
}
/// <summary>
/// Gets and sets the property DBClusterIdentifier.
/// <para>
/// The DB cluster identifier. This parameter is stored as a lowercase string.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must contain from 1 to 63 alphanumeric characters or hyphens.</li> <li>First
/// character must be a letter.</li> <li>Cannot end with a hyphen or contain two consecutive
/// hyphens.</li> </ul>
/// <para>
/// Example: <code>my-cluster1</code>
/// </para>
/// </summary>
public string DBClusterIdentifier
{
get { return this._dbClusterIdentifier; }
set { this._dbClusterIdentifier = value; }
}
// Check to see if DBClusterIdentifier property is set
internal bool IsSetDBClusterIdentifier()
{
return this._dbClusterIdentifier != null;
}
/// <summary>
/// Gets and sets the property DBClusterParameterGroupName.
/// <para>
/// The name of the DB cluster parameter group to associate with this DB cluster. If
/// this argument is omitted, <code>default.aurora5.6</code> for the specified engine
/// will be used.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be 1 to 255 alphanumeric characters</li> <li>First character must be
/// a letter</li> <li>Cannot end with a hyphen or contain two consecutive hyphens</li>
/// </ul>
/// </summary>
public string DBClusterParameterGroupName
{
get { return this._dbClusterParameterGroupName; }
set { this._dbClusterParameterGroupName = value; }
}
// Check to see if DBClusterParameterGroupName property is set
internal bool IsSetDBClusterParameterGroupName()
{
return this._dbClusterParameterGroupName != null;
}
/// <summary>
/// Gets and sets the property DBSubnetGroupName.
/// <para>
/// A DB subnet group to associate with this DB cluster.
/// </para>
/// </summary>
public string DBSubnetGroupName
{
get { return this._dbSubnetGroupName; }
set { this._dbSubnetGroupName = value; }
}
// Check to see if DBSubnetGroupName property is set
internal bool IsSetDBSubnetGroupName()
{
return this._dbSubnetGroupName != null;
}
/// <summary>
/// Gets and sets the property Engine.
/// <para>
/// The name of the database engine to be used for this DB cluster.
/// </para>
///
/// <para>
/// Valid Values: <code>MySQL</code>
/// </para>
/// </summary>
public string Engine
{
get { return this._engine; }
set { this._engine = value; }
}
// Check to see if Engine property is set
internal bool IsSetEngine()
{
return this._engine != null;
}
/// <summary>
/// Gets and sets the property EngineVersion.
/// <para>
/// The version number of the database engine to use.
/// </para>
///
/// <para>
/// <b>Aurora</b>
/// </para>
///
/// <para>
/// Example: <code>5.6.0</code>
/// </para>
/// </summary>
public string EngineVersion
{
get { return this._engineVersion; }
set { this._engineVersion = value; }
}
// Check to see if EngineVersion property is set
internal bool IsSetEngineVersion()
{
return this._engineVersion != null;
}
/// <summary>
/// Gets and sets the property MasterUsername.
/// <para>
/// The name of the master user for the client DB cluster.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be 1 to 16 alphanumeric characters.</li> <li>First character must be
/// a letter.</li> <li>Cannot be a reserved word for the chosen database engine.</li>
/// </ul>
/// </summary>
public string MasterUsername
{
get { return this._masterUsername; }
set { this._masterUsername = value; }
}
// Check to see if MasterUsername property is set
internal bool IsSetMasterUsername()
{
return this._masterUsername != null;
}
/// <summary>
/// Gets and sets the property MasterUserPassword.
/// <para>
/// The password for the master database user. This password can contain any printable
/// ASCII character except "/", """, or "@".
/// </para>
///
/// <para>
/// Constraints: Must contain from 8 to 41 characters.
/// </para>
/// </summary>
public string MasterUserPassword
{
get { return this._masterUserPassword; }
set { this._masterUserPassword = value; }
}
// Check to see if MasterUserPassword property is set
internal bool IsSetMasterUserPassword()
{
return this._masterUserPassword != null;
}
/// <summary>
/// Gets and sets the property OptionGroupName.
/// <para>
/// A value that indicates that the DB cluster should be associated with the specified
/// option group.
/// </para>
///
/// <para>
/// Permanent options cannot be removed from an option group. The option group cannot
/// be removed from a DB cluster once it is associated with a DB cluster.
/// </para>
/// </summary>
public string OptionGroupName
{
get { return this._optionGroupName; }
set { this._optionGroupName = value; }
}
// Check to see if OptionGroupName property is set
internal bool IsSetOptionGroupName()
{
return this._optionGroupName != null;
}
/// <summary>
/// Gets and sets the property Port.
/// <para>
/// The port number on which the instances in the DB cluster accept connections.
/// </para>
///
/// <para>
/// Default: <code>3306</code>
/// </para>
/// </summary>
public int Port
{
get { return this._port.GetValueOrDefault(); }
set { this._port = value; }
}
// Check to see if Port property is set
internal bool IsSetPort()
{
return this._port.HasValue;
}
/// <summary>
/// Gets and sets the property PreferredBackupWindow.
/// <para>
/// The daily time range during which automated backups are created if automated backups
/// are enabled using the <code>BackupRetentionPeriod</code> parameter.
/// </para>
///
/// <para>
/// Default: A 30-minute window selected at random from an 8-hour block of time per region.
/// To see the time blocks available, see <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/AdjustingTheMaintenanceWindow.html">
/// Adjusting the Preferred Maintenance Window</a> in the <i>Amazon RDS User Guide.</i>
///
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be in the format <code>hh24:mi-hh24:mi</code>.</li> <li>Times should
/// be in Universal Coordinated Time (UTC).</li> <li>Must not conflict with the preferred
/// maintenance window.</li> <li>Must be at least 30 minutes.</li> </ul>
/// </summary>
public string PreferredBackupWindow
{
get { return this._preferredBackupWindow; }
set { this._preferredBackupWindow = value; }
}
// Check to see if PreferredBackupWindow property is set
internal bool IsSetPreferredBackupWindow()
{
return this._preferredBackupWindow != null;
}
/// <summary>
/// Gets and sets the property PreferredMaintenanceWindow.
/// <para>
/// The weekly time range during which system maintenance can occur, in Universal Coordinated
/// Time (UTC).
/// </para>
///
/// <para>
/// Format: <code>ddd:hh24:mi-ddd:hh24:mi</code>
/// </para>
///
/// <para>
/// Default: A 30-minute window selected at random from an 8-hour block of time per region,
/// occurring on a random day of the week. To see the time blocks available, see <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/AdjustingTheMaintenanceWindow.html">
/// Adjusting the Preferred Maintenance Window</a> in the <i>Amazon RDS User Guide.</i>
///
/// </para>
///
/// <para>
/// Valid Days: Mon, Tue, Wed, Thu, Fri, Sat, Sun
/// </para>
///
/// <para>
/// Constraints: Minimum 30-minute window.
/// </para>
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this._preferredMaintenanceWindow; }
set { this._preferredMaintenanceWindow = value; }
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this._preferredMaintenanceWindow != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property VpcSecurityGroupIds.
/// <para>
/// A list of EC2 VPC security groups to associate with this DB cluster.
/// </para>
/// </summary>
public List<string> VpcSecurityGroupIds
{
get { return this._vpcSecurityGroupIds; }
set { this._vpcSecurityGroupIds = value; }
}
// Check to see if VpcSecurityGroupIds property is set
internal bool IsSetVpcSecurityGroupIds()
{
return this._vpcSecurityGroupIds != null && this._vpcSecurityGroupIds.Count > 0;
}
}
}
| |
// 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.Collections;
using System.Collections.Generic;
using TestSupport.Common_TestSupport;
using Xunit;
namespace TestSupport
{
/// <summary>
/// The expected range an enumerator will enumerate.
/// </summary>
[Flags]
public enum ExpectedEnumeratorRange { None = 0, Start = 1, End = 2 };
/// <summary>
/// The methods to use for verification
/// </summary>
[Flags]
public enum VerificationMethod { None = 0, Item = 1, Contains = 2, IndexOf = 4, ICollection = 8 };
/// <summary>
/// The verification level
/// </summary>
public enum VerificationLevel { None, Normal, Extensive };
/// <summary>
/// This specifies how the collection is ordered.
/// Sequential specifies that Add places items at the end of the collection and Remove will remove the first item found.
/// Reverse specifies that Add places items at the begining of the collection and Remove will remove the first item found.
/// Unspecified specifies that Add and Remove do not specify where items are added or removed.
/// </summary>
public enum CollectionOrder { Sequential, Unspecified };// TODO: Support ordeered collections
namespace Common_TestSupport
{ /// <summary>
/// Modifies the given collection
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection">The collection to modify</param>
/// <param name="expectedItems">The current items in the collection</param>
/// <returns>The items in the collection after it has been modified.</returns>
public delegate T[] ModifyUnderlyingCollection_T<T>(System.Collections.Generic.IEnumerable<T> collection, T[] expectedItems);
/// <summary>
/// Modifies the given collection
/// </summary>
/// <param name="collection">The collection to modify</param>
/// <param name="expectedItems">The current items in the collection</param>
/// <returns>The items in the collection after it has been modified.</returns>
public delegate Object[] ModifyUnderlyingCollection(IEnumerable collection, Object[] expectedItems);
/// <summary>
/// Creates a new ICollection
/// </summary>
/// <returns></returns>
public delegate ICollection CreateNewICollection();
/// <summary>
/// Generates a new unique item
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>A new unique item.</returns>
public delegate T GenerateItem<T>();
/// <summary>
/// Compares x and y
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>true if x and y are equal else false.</returns>
public delegate bool ItemEquals_T<T>(T x, T y);
/// <summary>
/// Compares x and y
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>true if x and y are equal else false.</returns>
public delegate bool ItemEquals(Object x, Object y);
/// <summary>
/// An action to perform on a Multidimentional array
/// </summary>
/// <param name="array">The array to perform the action on</param>
/// <param name="indicies">The current indicies of the array</param>
public delegate void MultiDimArrayAction(Array array, int[] indicies);
public delegate void ModifyCollection();
/// <summary>
/// Geneartes an exception
/// </summary>
public delegate void ExceptionGenerator();
/// <summary>
/// Test Scenario to run
/// </summary>
/// <returns>true if the test scenario passed else false</returns>
public delegate bool TestScenario();
public class Test
{
/// <summary>
/// The default exit code to use if the test failed
/// </summary>
public const int DEFAULT_FAIL_EXITCODE = 50;
/// <summary>
/// The default exit code to use if the test passed
/// </summary>
public const int PASS_EXITCODE = 100;
private int m_numErrors = 0;
private int m_numTestcaseFailures = 0;
private int m_numTestcases = 0;
private int m_failExitCode = DEFAULT_FAIL_EXITCODE;
private bool m_failExitCodeSet = false;
private bool m_suppressStackOutput = false;
private bool m_outputExceptionMessages = false;
private List<Scenario> m_scenarioDescriptions = new List<Scenario>();
private System.IO.TextWriter m_outputWriter = Console.Out;
private class Scenario
{
public String Description;
public bool DescriptionPrinted;
public Scenario(string description)
{
Description = description;
DescriptionPrinted = false;
}
}
public void InitScenario(string scenarioDescription)
{
m_scenarioDescriptions.Clear();
m_scenarioDescriptions.Add(new Scenario(scenarioDescription));
}
public void PushScenario(string scenarioDescription)
{
m_scenarioDescriptions.Add(new Scenario(scenarioDescription));
}
public void PushScenario(string scenarioDescription, int maxScenarioDepth)
{
while (maxScenarioDepth < m_scenarioDescriptions.Count)
{
m_scenarioDescriptions.RemoveAt(m_scenarioDescriptions.Count - 1);
}
m_scenarioDescriptions.Add(new Scenario(scenarioDescription));
}
public int ScenarioDepth
{
get
{
return m_scenarioDescriptions.Count;
}
}
public void PopScenario()
{
if (0 < m_scenarioDescriptions.Count)
{
m_scenarioDescriptions.RemoveAt(m_scenarioDescriptions.Count - 1);
}
}
public void OutputDebugInfo(string debugInfo)
{
OutputMessage(debugInfo);
}
public void OutputDebugInfo(string format, params object[] args)
{
OutputDebugInfo(String.Format(format, args));
}
private void OutputMessage(string message)
{
if (0 < m_scenarioDescriptions.Count)
{
Scenario currentScenario = m_scenarioDescriptions[m_scenarioDescriptions.Count - 1];
if (!currentScenario.DescriptionPrinted)
{
m_outputWriter.WriteLine();
m_outputWriter.WriteLine();
m_outputWriter.WriteLine("**********************************************************************");
m_outputWriter.WriteLine("** {0,-64} **", "SCENARIO:");
for (int i = 0; i < m_scenarioDescriptions.Count; ++i)
{
m_outputWriter.WriteLine(m_scenarioDescriptions[i].Description);
}
m_outputWriter.WriteLine("**********************************************************************");
currentScenario.DescriptionPrinted = true;
}
}
m_outputWriter.WriteLine(message);
}
/// <summary>
/// If the expression is false writes the message to the console and increments the error count.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="message">The message to print to the console if the expression is false.</param>
/// <returns>true if expression is true else false.</returns>
public bool Eval(bool expression, string message)
{
if (!expression)
{
OutputMessage(message);
++m_numErrors;
Assert.True(expression, message);
m_outputWriter.WriteLine();
}
return true;
}
/// <summary>
/// If the expression is false outputs the formatted message(String.Format(format, args)
/// and increments the error count.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if expression is true else false.</returns>
public bool Eval(bool expression, String format, params object[] args)
{
if (!expression)
{
return Eval(expression, String.Format(format, args));
}
return true;
}
/// <summary>
/// Compares expected and actual if expected and actual are differnet outputs
/// and increments the error count.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="errorMsg">The message to output.
/// Uses String.Format(errorMsg, expected, actual)</param>
/// <returns>true if expected and actual are equal else false.</returns>
public bool EvalFormatted<T>(T expected, T actual, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, String.Format(errorMsg, expected, actual));
return true;
}
/// <summary>
/// Compares expected and actual if expected and actual are differnet outputs the
/// error message and increments the error count.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="errorMsg">The message to output.</param>
/// <returns>true if expected and actual are equal else false.</returns>
public bool Eval<T>(T expected, T actual, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
public bool Eval<T>(IEqualityComparer<T> comparer, T expected, T actual, String errorMsg)
{
bool retValue = comparer.Equals(expected, actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
public bool Eval<T>(IComparer<T> comparer, T expected, T actual, String errorMsg)
{
bool retValue = 0 == comparer.Compare(expected, actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
/// <summary>
/// Compares expected and actual if expected and actual are differnet outputs the
/// error message and increments the error count.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if expected and actual are equal else false.</returns>
public bool Eval<T>(T expected, T actual, String format, params object[] args)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, String.Format(format, args) +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
/// <summary>
/// Runs a test scenario.
/// </summary>
/// <param name="test">The test testscenario to run.</param>
/// <returns>true if the test passed else false.</returns>
public bool RunTestScenario(TestScenario test)
{
bool retValue;
if (test())
{
m_numTestcases++;
retValue = true;
}
else
{
m_numTestcaseFailures++;
retValue = false;
}
m_outputWriter.WriteLine("");
return retValue;
}
/// <summary>
/// The number of failed test cases.
/// </summary>
/// <value>The number of failed test cases.</value>
public int NumberOfFailedTestcases
{
get
{
return m_numTestcaseFailures;
}
}
/// <summary>
/// The number of test cases.
/// </summary>
/// <value>The number of test cases.</value>
public int NumberOfTestcases
{
get
{
return m_numTestcases;
}
}
/// <summary>
/// The number of errors.
/// </summary>
/// <value>The number of errors.</value>
public int NumberOfErrors
{
get
{
return m_numErrors;
}
}
/// <summary>
/// The exit code to use if the test failed.
/// </summary>
/// <value>The exit code to use if the test failed.</value>
public int FailExitCode
{
get
{
return m_failExitCode;
}
set
{
m_failExitCodeSet = true;
m_failExitCode = value;
}
}
/// <summary>
/// The exit code to use.
/// </summary>
/// <value></value>
public int ExitCode
{
get
{
if (Pass)
return PASS_EXITCODE;
return m_failExitCode;
}
}
/// <summary>
/// If the fail exit code was set.
/// </summary>
/// <value>If the fail exit code was set.</value>
public bool IsFailExitCodeSet
{
get
{
return m_failExitCodeSet;
}
}
/// <summary>
/// Returns true if all test cases passed else false.
/// </summary>
/// <value>If all test cases passed else false.</value>
public bool Pass
{
get
{
return 0 == m_numErrors && 0 == m_numTestcaseFailures;
}
}
/// <summary>
/// Determines if the stack is inlcluded with the output
/// </summary>
/// <value>False to output the stack with every failure else true to suppress the stack output</value>
public bool SuppressStackOutput
{
get
{
return m_suppressStackOutput;
}
set
{
m_suppressStackOutput = value;
}
}
public bool OutputExceptionMessages
{
get
{
return m_outputExceptionMessages;
}
set
{
m_outputExceptionMessages = value;
}
}
public System.IO.TextWriter OutputWriter
{
get
{
return m_outputWriter;
}
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
m_outputWriter = value;
}
}
/// <summary>
/// Resets all of the counters.
/// </summary>
public void Reset()
{
m_numErrors = 0;
m_numTestcaseFailures = 0;
m_numTestcases = 0;
m_failExitCodeSet = false;
m_failExitCode = DEFAULT_FAIL_EXITCODE;
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type T.
/// </summary>
/// <typeparam name="T">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <returns>true if exceptionGenerator through an exception of type T else false.</returns>
public bool VerifyException<T>(ExceptionGenerator exceptionGenerator) where T : Exception
{
return VerifyException(typeof(T), exceptionGenerator);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type T.
/// </summary>
/// <typeparam name="T">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <param name="message">The message to output if the verification fails.</param>
/// <returns>true if exceptionGenerator through an exception of type T else false.</returns>
public bool VerifyException<T>(ExceptionGenerator exceptionGenerator, string message) where T : Exception
{
return VerifyException(typeof(T), exceptionGenerator, message);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type T.
/// </summary>
/// <typeparam name="T">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if exceptionGenerator through an exception of type T else false.</returns>
public bool VerifyException<T>(ExceptionGenerator exceptionGenerator, String format, params object[] args) where T : Exception
{
return VerifyException(typeof(T), exceptionGenerator, String.Format(format, args));
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType.
/// </summary>
/// <param name="expectedExceptionType"></param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of
/// type expectedExceptionType.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType else false.</returns>
public bool VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator)
{
return VerifyException(expectedExceptionType, exceptionGenerator, String.Empty);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType.
/// </summary>
/// <param name="expectedExceptionType">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType else false.</returns>
public bool VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator, String format, params object[] args)
{
return VerifyException(expectedExceptionType, exceptionGenerator, String.Format(format, args));
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType.
/// </summary>
/// <param name="expectedExceptionType"></param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of
/// type expectedExceptionType.</param>
/// <param name="message">The message to output if the verification fails.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType else false.</returns>
public bool VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator, string message)
{
bool retValue = true;
try
{
exceptionGenerator();
retValue &= Eval(false, (String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_05940iedz Expected exception of the type {0} to be thrown and nothing was thrown",
expectedExceptionType);
}
catch (Exception exception)
{
retValue &= Eval<Type>(expectedExceptionType, exception.GetType(),
(String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_38223oipwj Expected exception and actual exception differ. Expected {0}, got \n{1}", expectedExceptionType, exception);
if (retValue && m_outputExceptionMessages)
{
OutputDebugInfo("{0} message: {1}" + Environment.NewLine, expectedExceptionType, exception.Message);
}
}
return retValue;
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType1
/// or expectedExceptionType2.
/// </summary>
/// <param name="expectedExceptionType1">The first exception type exceptionGenerator may throw.</param>
/// <param name="expectedExceptionType2">The second exception type exceptionGenerator may throw.</param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type
/// expectedExceptionType1 or expectedExceptionType2.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType1
/// of expectedExceptionType2 else false.</returns>
public bool VerifyException(Type expectedExceptionType1, Type expectedExceptionType2, ExceptionGenerator exceptionGenerator)
{
return VerifyException(new Type[] { expectedExceptionType1, expectedExceptionType2 }, exceptionGenerator);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType1
/// or expectedExceptionType2 or expectedExceptionType3.
/// </summary>
/// <param name="expectedExceptionType1">The first exception type exceptionGenerator may throw.</param>
/// <param name="expectedExceptionType2">The second exception type exceptionGenerator may throw.</param>
/// <param name="expectedExceptionType3">The third exception type exceptionGenerator may throw.</param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type
/// expectedExceptionType1 or expectedExceptionType2 or expectedExceptionType3.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType1
/// or expectedExceptionType2 or expectedExceptionType3 else false.</returns>
public bool VerifyException(Type expectedExceptionType1, Type expectedExceptionType2,
Type expectedExceptionType3, ExceptionGenerator exceptionGenerator)
{
return VerifyException(new Type[] { expectedExceptionType1, expectedExceptionType2, expectedExceptionType3 }, exceptionGenerator);
}
public bool VerifyException(Type[] expectedExceptionTypes, ExceptionGenerator exceptionGenerator)
{
return VerifyException(expectedExceptionTypes, exceptionGenerator, string.Empty);
}
public bool VerifyException(Type[] expectedExceptionTypes, ExceptionGenerator exceptionGenerator, String format, params object[] args)
{
return VerifyException(expectedExceptionTypes, exceptionGenerator, String.Format(format, args));
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of one of types in expectedExceptionTypes.
/// </summary>
/// <param name="expectedExceptionTypes">An array of the expected exception type that exceptionGenerator may throw.</param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of
/// one of the types in expectedExceptionTypes.</param>
/// <returns>true if exceptionGenerator through an exception of one of types in
/// expectedExceptionTypes else false.</returns>
public bool VerifyException(Type[] expectedExceptionTypes, ExceptionGenerator exceptionGenerator, string message)
{
bool retValue = true;
bool exceptionNotThrown = false;
bool exceptionTypeInvalid = true;
Type exceptionType = null;
Exception exceptionInstance = null;
try
{
exceptionGenerator();
exceptionNotThrown = true;
}
catch (Exception exception)
{
exceptionType = exception.GetType();
exceptionInstance = exception;
for (int i = 0; i < expectedExceptionTypes.Length; ++i)
{
if (null != expectedExceptionTypes[i] && exceptionType == expectedExceptionTypes[i]) //null is not a valid exception type
exceptionTypeInvalid = false;
}
}
if (exceptionNotThrown || exceptionTypeInvalid)
{
System.Text.StringBuilder exceptionTypeNames = new System.Text.StringBuilder();
for (int i = 0; i < expectedExceptionTypes.Length; ++i)
{
if (null != expectedExceptionTypes[i])
{
exceptionTypeNames.Append(expectedExceptionTypes[i].ToString());
exceptionTypeNames.Append(" ");
}
}
if (exceptionNotThrown)
{
retValue &= Eval(false, (String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_51584ajied Expected exception of one of the following types to be thrown: {0} and nothing was thrown",
exceptionTypeNames.ToString());
}
else if (exceptionTypeInvalid)
{
retValue &= Eval(false, (String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_51584ajied Expected exception of one of the following types to be thrown: {0} and the following was thrown:\n {1}",
exceptionTypeNames.ToString(), exceptionInstance.ToString());
}
}
return retValue;
}
[Obsolete]
public bool VerifyException(ExceptionGenerator exceptionGenerator, Type expectedExceptionType)
{
bool retValue = true;
try
{
exceptionGenerator();
retValue &= Eval(false, "Err_05940iedz Expected exception of the type {0} to be thrown and nothing was thrown",
expectedExceptionType);
}
catch (Exception exception)
{
retValue &= Eval<Type>(expectedExceptionType, exception.GetType(), "Err_38223oipwj Expected exception and actual exception differ");
}
return retValue;
}
}
public class ArrayUtils
{
/// <summary>
/// Creates array of the parameters.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array">The paramaters to create array from.</param>
/// <returns>An array of the parameters.</returns>
public static T[] Create<T>(params T[] array)
{
return array;
}
/// <summary>
/// Creates and sub array from array
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to create the sub array from.</param>
/// <param name="length">The length of the sub array.</param>
/// <returns>A sub array from array starting at 0 with a length of length.</returns>
public static V[] SubArray<V>(V[] array, int length)
{
return SubArray(array, 0, length);
}
/// <summary>
/// Creates and sub array from array
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to create the sub array from.</param>
/// <param name="startIndex">The start index of the sub array.</param>
/// <param name="length">The length of the sub array.</param>
/// <returns></returns>
public static V[] SubArray<V>(V[] array, int startIndex, int length)
{
V[] tempArray = new V[length];
Array.Copy(array, startIndex, tempArray, 0, length);
return tempArray;
}
/// <summary>
/// Remove item from array.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to remove the item from.</param>
/// <param name="item">The item to remove from the array.</param>
/// <returns>The array with the item removed.</returns>
public static V[] RemoveItem<V>(V[] array, V item)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i].Equals(item))
{
return RemoveAt(array, i);
}
}
return array;
}
/// <summary>
/// Remove item at index from array.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to remove the item from.</param>
/// <param name="index">The index of the item to remove from the array.</param>
/// <returns></returns>
public static V[] RemoveAt<V>(V[] array, int index)
{
V[] tempArray = new V[array.Length - 1];
Array.Copy(array, 0, tempArray, 0, index);
Array.Copy(array, index + 1, tempArray, index, array.Length - index - 1);
return tempArray;
}
public static V[] RemoveRange<V>(V[] array, int startIndex, int count)
{
V[] tempArray = new V[array.Length - count];
Array.Copy(array, 0, tempArray, 0, startIndex);
Array.Copy(array, startIndex + count, tempArray, startIndex, tempArray.Length - startIndex);
return tempArray;
}
public static V[] CopyRanges<V>(V[] array, int startIndex1, int count1, int startIndex2, int count2)
{
V[] tempArray = new V[count1 + count2];
Array.Copy(array, startIndex1, tempArray, 0, count1);
Array.Copy(array, startIndex2, tempArray, count1, count2);
return tempArray;
}
/// <summary>
/// Concatenates of of the items to the end of array1.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array1">The array to concatenate.</param>
/// <param name="array2">The items to concatonate to the end of array1.</param>
/// <returns>An array with all of the items from array1 followed by all of
/// the items from array2.</returns>
public static V[] Concat<V>(V[] array1, params V[] array2)
{
if (array1.Length == 0)
return array2;
if (array2.Length == 0)
return array1;
V[] tempArray = new V[array1.Length + array2.Length];
Array.Copy(array1, 0, tempArray, 0, array1.Length);
Array.Copy(array2, 0, tempArray, array1.Length, array2.Length);
return tempArray;
}
/// <summary>
/// Concatenates of of the items to the begining of array1.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array1">The array to concatenate.</param>
/// <param name="array2">The items to concatonate to the begining of array1.</param>
/// <returns>An array with all of the items from array2 followed by all of
/// the items from array1.</returns>
public static V[] Prepend<V>(V[] array1, params V[] array2)
{
if (array1.Length == 0)
return array2;
if (array2.Length == 0)
return array1;
V[] tempArray = new V[array1.Length + array2.Length];
Array.Copy(array2, 0, tempArray, 0, array2.Length);
Array.Copy(array1, 0, tempArray, array2.Length, array1.Length);
return tempArray;
}
/// <summary>
/// Rverses array.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to revers.</param>
/// <returns>A copy of array with the items reversed.</returns>
public static V[] Reverse<V>(V[] array)
{
return Reverse(array, 0, array.Length);
}
/// <summary>
/// Rverses length items in array starting at index.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to reverse.</param>
/// <param name="index">The index to start reversing items at.</param>
/// <param name="length">The number of items to revers</param>
/// <returns>A copy of array with length items reversed starting at index.</returns>
public static V[] Reverse<V>(V[] array, int index, int length)
{
if (array.Length < 2)
return array;
V[] tempArray = new V[array.Length];
Array.Copy(array, 0, tempArray, 0, array.Length);
Array.Reverse(tempArray, index, length);
return tempArray;
}
/// <summary>
/// Creates an array with a length of size and fills it with the items
/// returned from generatedItem.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="size">The size of the array to create and fill.</param>
/// <param name="generateItem">Returns the items to place into the array.</param>
/// <returns>An array of length size with items returned from generateItem</returns>
public static T[] CreateAndFillArray<T>(int size, GenerateItem<T> generateItem)
{
return FillArray<T>(new T[size], generateItem);
}
/// <summary>
/// Fills array with items returned from generateItem.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array">The array to to place the items in.</param>
/// <param name="generateItem">Returns the items to place into the array.</param>
/// <returns>The array with the items in it returned from generateItem.</returns>
public static T[] FillArray<T>(T[] array, GenerateItem<T> generateItem)
{
int arrayLength = array.Length;
for (int i = 0; i < arrayLength; ++i)
array[i] = generateItem();
return array;
}
}
}
}
| |
/*
* 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 Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
//using Cairo;
namespace OpenSim.Region.CoreModules.Scripting.VectorRender
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "VectorRenderModule")]
public class VectorRenderModule : ISharedRegionModule, IDynamicTextureRender
{
// These fields exist for testing purposes, please do not remove.
// private static bool s_flipper;
// private static byte[] s_asset1Data;
// private static byte[] s_asset2Data;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_fontName = "Arial";
private Graphics m_graph;
private Scene m_scene;
private IDynamicTextureManager m_textureManager;
public VectorRenderModule()
{
}
#region IDynamicTextureRender Members
public bool AsyncConvertData(UUID id, string bodyData, string extraParams)
{
if (m_textureManager == null)
{
m_log.Warn("[VECTORRENDERMODULE]: No texture manager. Can't function");
return false;
}
// XXX: This isn't actually being done asynchronously!
m_textureManager.ReturnData(id, ConvertData(bodyData, extraParams));
return true;
}
public bool AsyncConvertUrl(UUID id, string url, string extraParams)
{
return false;
}
public IDynamicTexture ConvertData(string bodyData, string extraParams)
{
return Draw(bodyData, extraParams);
}
public IDynamicTexture ConvertUrl(string url, string extraParams)
{
return null;
}
public string GetContentType()
{
return "vector";
}
// public bool AlwaysIdenticalConversion(string bodyData, string extraParams)
// {
// string[] lines = GetLines(bodyData);
// return lines.Any((str, r) => str.StartsWith("Image"));
// }
public void GetDrawStringSize(string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
lock (this)
{
using (Font myFont = new Font(fontName, fontSize))
{
SizeF stringSize = new SizeF();
stringSize = m_graph.MeasureString(text, myFont);
xSize = stringSize.Width;
ySize = stringSize.Height;
}
}
}
public string GetName()
{
return Name;
}
public bool SupportsAsynchronous()
{
return true;
}
#endregion IDynamicTextureRender Members
#region ISharedRegionModule Members
public string Name
{
get { return "VectorRenderModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
{
m_scene = scene;
}
}
public void Close()
{
}
public void Initialise(IConfigSource config)
{
IConfig cfg = config.Configs["VectorRender"];
if (null != cfg)
{
m_fontName = cfg.GetString("font_name", m_fontName);
}
m_log.DebugFormat("[VECTORRENDERMODULE]: using font \"{0}\" for text rendering.", m_fontName);
// We won't dispose of these explicitly since this module is only removed when the entire simulator
// is shut down.
Bitmap bitmap = new Bitmap(1024, 1024, PixelFormat.Format32bppArgb);
m_graph = Graphics.FromImage(bitmap);
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
if (m_textureManager == null && m_scene == scene)
{
m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
if (m_textureManager != null)
{
m_textureManager.RegisterRender(GetContentType(), this);
}
}
}
public void RemoveRegion(Scene scene)
{
}
#endregion ISharedRegionModule Members
private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref float x, ref float y)
{
line = line.Remove(0, startLength);
string[] parts = line.Split(partsDelimiter);
if (parts.Length == 2)
{
string xVal = parts[0].Trim();
string yVal = parts[1].Trim();
x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
}
else if (parts.Length > 2)
{
string xVal = parts[0].Trim();
string yVal = parts[1].Trim();
x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
line = "";
for (int i = 2; i < parts.Length; i++)
{
line = line + parts[i].Trim();
line = line + " ";
}
}
}
private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref PointF[] points)
{
line = line.Remove(0, startLength);
string[] parts = line.Split(partsDelimiter);
if (parts.Length > 1 && parts.Length % 2 == 0)
{
points = new PointF[parts.Length / 2];
for (int i = 0; i < parts.Length; i = i + 2)
{
string xVal = parts[i].Trim();
string yVal = parts[i + 1].Trim();
float x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
float y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture);
PointF point = new PointF(x, y);
points[i / 2] = point;
// m_log.DebugFormat("[VECTOR RENDER MODULE]: Got point {0}", points[i / 2]);
}
}
}
private IDynamicTexture Draw(string data, string extraParams)
{
// We need to cater for old scripts that didnt use extraParams neatly, they use either an integer size which represents both width and height, or setalpha
// we will now support multiple comma seperated params in the form width:256,height:512,alpha:255
int width = 256;
int height = 256;
int alpha = 255; // 0 is transparent
Color bgColor = Color.White; // Default background color
char altDataDelim = ';';
char[] paramDelimiter = { ',' };
char[] nvpDelimiter = { ':' };
extraParams = extraParams.Trim();
extraParams = extraParams.ToLower();
string[] nvps = extraParams.Split(paramDelimiter);
int temp = -1;
foreach (string pair in nvps)
{
string[] nvp = pair.Split(nvpDelimiter);
string name = "";
string value = "";
if (nvp[0] != null)
{
name = nvp[0].Trim();
}
if (nvp.Length == 2)
{
value = nvp[1].Trim();
}
switch (name)
{
case "width":
temp = parseIntParam(value);
if (temp != -1)
{
if (temp < 1)
{
width = 1;
}
else if (temp > 2048)
{
width = 2048;
}
else
{
width = temp;
}
}
break;
case "height":
temp = parseIntParam(value);
if (temp != -1)
{
if (temp < 1)
{
height = 1;
}
else if (temp > 2048)
{
height = 2048;
}
else
{
height = temp;
}
}
break;
case "alpha":
temp = parseIntParam(value);
if (temp != -1)
{
if (temp < 0)
{
alpha = 0;
}
else if (temp > 255)
{
alpha = 255;
}
else
{
alpha = temp;
}
}
// Allow a bitmap w/o the alpha component to be created
else if (value.ToLower() == "false")
{
alpha = 256;
}
break;
case "bgcolor":
case "bgcolour":
int hex = 0;
if (Int32.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex))
{
bgColor = Color.FromArgb(hex);
}
else
{
bgColor = Color.FromName(value);
}
break;
case "altdatadelim":
altDataDelim = value.ToCharArray()[0];
break;
case "":
// blank string has been passed do nothing just use defaults
break;
default: // this is all for backwards compat, all a bit ugly hopfully can be removed in future
// could be either set alpha or just an int
if (name == "setalpha")
{
alpha = 0; // set the texture to have transparent background (maintains backwards compat)
}
else
{
// this function used to accept an int on its own that represented both
// width and height, this is to maintain backwards compat, could be removed
// but would break existing scripts
temp = parseIntParam(name);
if (temp != -1)
{
if (temp > 1024)
temp = 1024;
if (temp < 128)
temp = 128;
width = temp;
height = temp;
}
}
break;
}
}
Bitmap bitmap = null;
Graphics graph = null;
bool reuseable = false;
try
{
// XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously,
// the native malloc heap can become corrupted, possibly due to a double free(). This may be due to
// bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX. These problems were
// seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1. They go away if disposal is perfomed
// under lock.
lock (this)
{
if (alpha == 256)
bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
else
bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
graph = Graphics.FromImage(bitmap);
// this is really just to save people filling the
// background color in their scripts, only do when fully opaque
if (alpha >= 255)
{
using (SolidBrush bgFillBrush = new SolidBrush(bgColor))
{
graph.FillRectangle(bgFillBrush, 0, 0, width, height);
}
}
for (int w = 0; w < bitmap.Width; w++)
{
if (alpha <= 255)
{
for (int h = 0; h < bitmap.Height; h++)
{
bitmap.SetPixel(w, h, Color.FromArgb(alpha, bitmap.GetPixel(w, h)));
}
}
}
GDIDraw(data, graph, altDataDelim, out reuseable);
}
byte[] imageJ2000 = new byte[0];
// This code exists for testing purposes, please do not remove.
// if (s_flipper)
// imageJ2000 = s_asset1Data;
// else
// imageJ2000 = s_asset2Data;
//
// s_flipper = !s_flipper;
try
{
imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[VECTORRENDERMODULE]: OpenJpeg Encode Failed. Exception {0}{1}",
e.Message, e.StackTrace);
}
return new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
data, extraParams, imageJ2000, new Size(width, height), reuseable);
}
finally
{
// XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously,
// the native malloc heap can become corrupted, possibly due to a double free(). This may be due to
// bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX. These problems were
// seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1. They go away if disposal is perfomed
// under lock.
lock (this)
{
if (graph != null)
graph.Dispose();
if (bitmap != null)
bitmap.Dispose();
}
}
}
private void GDIDraw(string data, Graphics graph, char dataDelim, out bool reuseable)
{
reuseable = true;
Point startPoint = new Point(0, 0);
Point endPoint = new Point(0, 0);
Pen drawPen = null;
Font myFont = null;
SolidBrush myBrush = null;
try
{
drawPen = new Pen(Color.Black, 7);
string fontName = m_fontName;
float fontSize = 14;
myFont = new Font(fontName, fontSize);
myBrush = new SolidBrush(Color.Black);
char[] partsDelimiter = { ',' };
foreach (string line in GetLines(data, dataDelim))
{
string nextLine = line.Trim();
// m_log.DebugFormat("[VECTOR RENDER MODULE]: Processing line '{0}'", nextLine);
//replace with switch, or even better, do some proper parsing
if (nextLine.StartsWith("MoveTo"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y);
startPoint.X = (int)x;
startPoint.Y = (int)y;
}
else if (nextLine.StartsWith("LineTo"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y);
endPoint.X = (int)x;
endPoint.Y = (int)y;
graph.DrawLine(drawPen, startPoint, endPoint);
startPoint.X = endPoint.X;
startPoint.Y = endPoint.Y;
}
else if (nextLine.StartsWith("Text"))
{
nextLine = nextLine.Remove(0, 4);
nextLine = nextLine.Trim();
graph.DrawString(nextLine, myFont, myBrush, startPoint);
}
else if (nextLine.StartsWith("Image"))
{
// We cannot reuse any generated texture involving fetching an image via HTTP since that image
// can change.
reuseable = false;
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 5, ref x, ref y);
endPoint.X = (int)x;
endPoint.Y = (int)y;
using (Image image = ImageHttpRequest(nextLine))
{
if (image != null)
{
graph.DrawImage(image, (float)startPoint.X, (float)startPoint.Y, x, y);
}
else
{
using (Font errorFont = new Font(m_fontName, 6))
{
graph.DrawString("URL couldn't be resolved or is", errorFont,
myBrush, startPoint);
graph.DrawString("not an image. Please check URL.", errorFont,
myBrush, new Point(startPoint.X, 12 + startPoint.Y));
}
graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
}
}
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("Rectangle"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 9, ref x, ref y);
endPoint.X = (int)x;
endPoint.Y = (int)y;
graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("FillRectangle"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 13, ref x, ref y);
endPoint.X = (int)x;
endPoint.Y = (int)y;
graph.FillRectangle(myBrush, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("FillPolygon"))
{
PointF[] points = null;
GetParams(partsDelimiter, ref nextLine, 11, ref points);
graph.FillPolygon(myBrush, points);
}
else if (nextLine.StartsWith("Polygon"))
{
PointF[] points = null;
GetParams(partsDelimiter, ref nextLine, 7, ref points);
graph.DrawPolygon(drawPen, points);
}
else if (nextLine.StartsWith("Ellipse"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y);
endPoint.X = (int)x;
endPoint.Y = (int)y;
graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
else if (nextLine.StartsWith("FontSize"))
{
nextLine = nextLine.Remove(0, 8);
nextLine = nextLine.Trim();
fontSize = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture);
myFont.Dispose();
myFont = new Font(fontName, fontSize);
}
else if (nextLine.StartsWith("FontProp"))
{
nextLine = nextLine.Remove(0, 8);
nextLine = nextLine.Trim();
string[] fprops = nextLine.Split(partsDelimiter);
foreach (string prop in fprops)
{
switch (prop)
{
case "B":
if (!(myFont.Bold))
{
Font newFont = new Font(myFont, myFont.Style | FontStyle.Bold);
myFont.Dispose();
myFont = newFont;
}
break;
case "I":
if (!(myFont.Italic))
{
Font newFont = new Font(myFont, myFont.Style | FontStyle.Italic);
myFont.Dispose();
myFont = newFont;
}
break;
case "U":
if (!(myFont.Underline))
{
Font newFont = new Font(myFont, myFont.Style | FontStyle.Underline);
myFont.Dispose();
myFont = newFont;
}
break;
case "S":
if (!(myFont.Strikeout))
{
Font newFont = new Font(myFont, myFont.Style | FontStyle.Strikeout);
myFont.Dispose();
myFont = newFont;
}
break;
case "R":
// We need to place this newFont inside its own context so that the .NET compiler
// doesn't complain about a redefinition of an existing newFont, even though there is none
// The mono compiler doesn't produce this error.
{
Font newFont = new Font(myFont, FontStyle.Regular);
myFont.Dispose();
myFont = newFont;
}
break;
}
}
}
else if (nextLine.StartsWith("FontName"))
{
nextLine = nextLine.Remove(0, 8);
fontName = nextLine.Trim();
myFont.Dispose();
myFont = new Font(fontName, fontSize);
}
else if (nextLine.StartsWith("PenSize"))
{
nextLine = nextLine.Remove(0, 7);
nextLine = nextLine.Trim();
float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture);
drawPen.Width = size;
}
else if (nextLine.StartsWith("PenCap"))
{
bool start = true, end = true;
nextLine = nextLine.Remove(0, 6);
nextLine = nextLine.Trim();
string[] cap = nextLine.Split(partsDelimiter);
if (cap[0].ToLower() == "start")
end = false;
else if (cap[0].ToLower() == "end")
start = false;
else if (cap[0].ToLower() != "both")
return;
string type = cap[1].ToLower();
if (end)
{
switch (type)
{
case "arrow":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
break;
case "round":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
break;
case "diamond":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor;
break;
case "flat":
drawPen.EndCap = System.Drawing.Drawing2D.LineCap.Flat;
break;
}
}
if (start)
{
switch (type)
{
case "arrow":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
break;
case "round":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
break;
case "diamond":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor;
break;
case "flat":
drawPen.StartCap = System.Drawing.Drawing2D.LineCap.Flat;
break;
}
}
}
else if (nextLine.StartsWith("PenColour") || nextLine.StartsWith("PenColor"))
{
nextLine = nextLine.Remove(0, 9);
nextLine = nextLine.Trim();
int hex = 0;
Color newColor;
if (Int32.TryParse(nextLine, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex))
{
newColor = Color.FromArgb(hex);
}
else
{
// this doesn't fail, it just returns black if nothing is found
newColor = Color.FromName(nextLine);
}
myBrush.Color = newColor;
drawPen.Color = newColor;
}
}
}
finally
{
if (drawPen != null)
drawPen.Dispose();
if (myFont != null)
myFont.Dispose();
if (myBrush != null)
myBrush.Dispose();
}
}
/// <summary>
/// Split input data into discrete command lines.
/// </summary>
/// <returns></returns>
/// <param name='data'></param>
/// <param name='dataDelim'></param>
private string[] GetLines(string data, char dataDelim)
{
char[] lineDelimiter = { dataDelim };
return data.Split(lineDelimiter);
}
private Bitmap ImageHttpRequest(string url)
{
try
{
WebRequest request = HttpWebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)(request).GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream s = response.GetResponseStream())
{
Bitmap image = new Bitmap(s);
return image;
}
}
}
}
catch { }
return null;
}
private int parseIntParam(string strInt)
{
int parsed;
try
{
parsed = Convert.ToInt32(strInt);
}
catch (Exception)
{
//Ckrinke: Add a WriteLine to remove the warning about 'e' defined but not used
// m_log.Debug("Problem with Draw. Please verify parameters." + e.ToString());
parsed = -1;
}
return parsed;
}
/*
private void CairoDraw(string data, System.Drawing.Graphics graph)
{
using (Win32Surface draw = new Win32Surface(graph.GetHdc()))
{
Context contex = new Context(draw);
contex.Antialias = Antialias.None; //fastest method but low quality
contex.LineWidth = 7;
char[] lineDelimiter = { ';' };
char[] partsDelimiter = { ',' };
string[] lines = data.Split(lineDelimiter);
foreach (string line in lines)
{
string nextLine = line.Trim();
if (nextLine.StartsWith("MoveTO"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, ref x, ref y);
contex.MoveTo(x, y);
}
else if (nextLine.StartsWith("LineTo"))
{
float x = 0;
float y = 0;
GetParams(partsDelimiter, ref nextLine, ref x, ref y);
contex.LineTo(x, y);
contex.Stroke();
}
}
}
graph.ReleaseHdc();
}
*/
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
namespace UPnPAuthor
{
/// <summary>
/// Summary description for DesignComplexType.
/// </summary>
public class DesignComplexType : System.Windows.Forms.Form
{
private OpenSource.UPnP.UPnPComplexType[] complexTypeList;
public OpenSource.UPnP.UPnPComplexType ComplexType = null;
public string FieldName;
public string FieldType;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button addFieldButton;
private System.Windows.Forms.Panel itemPanel;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox customNamespaceTextBox;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TextBox complexTypeNameTextBox;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public DesignComplexType(OpenSource.UPnP.UPnPComplexType[] complexTypes)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
complexTypeList = complexTypes;
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.addFieldButton = new System.Windows.Forms.Button();
this.itemPanel = new System.Windows.Forms.Panel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.customNamespaceTextBox = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.complexTypeNameTextBox = new System.Windows.Forms.TextBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// okButton
//
this.okButton.Location = new System.Drawing.Point(8, 392);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(88, 23);
this.okButton.TabIndex = 2;
this.okButton.Text = "OK";
this.okButton.Click += new System.EventHandler(this.okButton_Click);
//
// cancelButton
//
this.cancelButton.Location = new System.Drawing.Point(8, 360);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(88, 23);
this.cancelButton.TabIndex = 3;
this.cancelButton.Text = "Cancel";
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// addFieldButton
//
this.addFieldButton.Location = new System.Drawing.Point(8, 328);
this.addFieldButton.Name = "addFieldButton";
this.addFieldButton.Size = new System.Drawing.Size(88, 23);
this.addFieldButton.TabIndex = 5;
this.addFieldButton.Text = "Add Grouping";
this.addFieldButton.Click += new System.EventHandler(this.addFieldButton_Click);
//
// itemPanel
//
this.itemPanel.AutoScroll = true;
this.itemPanel.BackColor = System.Drawing.SystemColors.AppWorkspace;
this.itemPanel.Location = new System.Drawing.Point(8, 8);
this.itemPanel.Name = "itemPanel";
this.itemPanel.Size = new System.Drawing.Size(688, 304);
this.itemPanel.TabIndex = 6;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.customNamespaceTextBox);
this.groupBox1.Location = new System.Drawing.Point(104, 320);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(592, 48);
this.groupBox1.TabIndex = 7;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Namespace";
//
// customNamespaceTextBox
//
this.customNamespaceTextBox.Location = new System.Drawing.Point(8, 16);
this.customNamespaceTextBox.Name = "customNamespaceTextBox";
this.customNamespaceTextBox.Size = new System.Drawing.Size(576, 20);
this.customNamespaceTextBox.TabIndex = 0;
this.customNamespaceTextBox.Text = "http://www.vendor.org/Schemas";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.complexTypeNameTextBox);
this.groupBox2.Location = new System.Drawing.Point(104, 369);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(592, 48);
this.groupBox2.TabIndex = 8;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Complex Type Name";
//
// complexTypeNameTextBox
//
this.complexTypeNameTextBox.Location = new System.Drawing.Point(8, 16);
this.complexTypeNameTextBox.Name = "complexTypeNameTextBox";
this.complexTypeNameTextBox.Size = new System.Drawing.Size(576, 20);
this.complexTypeNameTextBox.TabIndex = 0;
//
// DesignComplexType
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(704, 430);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.itemPanel);
this.Controls.Add(this.addFieldButton);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DesignComplexType";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Design Complex Type";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private void fieldNameTextBox_TextChanged(object sender, System.EventArgs e)
{
}
private void cancelButton_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
private void okButton_Click(object sender, System.EventArgs e)
{
if (itemPanel.Controls.Count > 0)
{
ComplexType = new OpenSource.UPnP.UPnPComplexType(complexTypeNameTextBox.Text, customNamespaceTextBox.Text);
// TODO: The following lines make no sense, this feature does not work.
foreach(Container C in itemPanel.Controls)
{
//ComplexType.AddField(C.GetFieldInfo());
OpenSource.UPnP.UPnPComplexType.GenericContainer gc = new OpenSource.UPnP.UPnPComplexType.GenericContainer();
ComplexType.AddContainer(gc);
}
}
this.DialogResult = DialogResult.OK;
}
private void addFieldButton_Click(object sender, System.EventArgs e)
{
// ComplexItem ci = new ComplexItem(this,complexTypeList);
//
// ci.Dock = DockStyle.Top;
// itemPanel.Controls.Add(ci);
Container c = new Container(this, complexTypeList);
c.Dock = DockStyle.Top;
itemPanel.Controls.Add(c);
}
public void moveUp(Control obj)
{
int pos = itemPanel.Controls.GetChildIndex(obj,false);
if(pos >= 0)
{
itemPanel.Controls.SetChildIndex(obj, pos + 1);
}
}
public void moveDown(Control obj)
{
int pos = itemPanel.Controls.GetChildIndex(obj,false);
if(pos > 0)
{
itemPanel.Controls.SetChildIndex(obj, pos - 1);
}
}
private void button1_Click(object sender, System.EventArgs e)
{
TestForm t = new TestForm();
t.ShowDialog();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// #define StressTest // set to raise the amount of time spent in concurrency tests that stress the collections
using System;
using System.Collections.Generic;
using System.Collections.Tests;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public abstract class ProducerConsumerCollectionTests : IEnumerable_Generic_Tests<int>
{
protected override IEnumerable<ModifyEnumerable> ModifyEnumerables => new List<ModifyEnumerable>();
protected override int CreateT(int seed) => new Random(seed).Next();
protected override EnumerableOrder Order => EnumerableOrder.Unspecified;
protected override IEnumerable<int> GenericIEnumerableFactory(int count) => CreateProducerConsumerCollection(count);
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection() => CreateProducerConsumerCollection<int>();
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection(int count) => CreateProducerConsumerCollection(Enumerable.Range(0, count));
protected abstract IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>();
protected abstract IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection);
protected abstract bool IsEmpty(IProducerConsumerCollection<int> pcc);
protected abstract bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result);
protected virtual IProducerConsumerCollection<int> CreateOracle() => CreateOracle(Enumerable.Empty<int>());
protected abstract IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection);
protected static TaskFactory ThreadFactory { get; } = new TaskFactory(
CancellationToken.None, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
private const double ConcurrencyTestSeconds =
#if StressTest
8.0;
#else
1.0;
#endif
[Fact]
public void Ctor_InvalidArgs_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("collection", () => CreateProducerConsumerCollection(null));
}
[Fact]
public void Ctor_NoArg_ItemsAndCountMatch()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Equal(0, c.Count);
Assert.True(IsEmpty(c));
Assert.Equal(Enumerable.Empty<int>(), c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void Ctor_Collection_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, count));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(1, count));
Assert.Equal(oracle.Count == 0, IsEmpty(c));
Assert.Equal(oracle.Count, c.Count);
Assert.Equal<int>(oracle, c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
[InlineData(1000)]
public void Ctor_InitializeFromCollection_ContainsExpectedItems(int numItems)
{
var expected = new HashSet<int>(Enumerable.Range(0, numItems));
IProducerConsumerCollection<int> pcc = CreateProducerConsumerCollection(expected);
Assert.Equal(expected.Count, pcc.Count);
int item;
var actual = new HashSet<int>();
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected.Count - i, pcc.Count);
Assert.True(pcc.TryTake(out item));
actual.Add(item);
}
Assert.False(pcc.TryTake(out item));
Assert.Equal(0, item);
AssertSetsEqual(expected, actual);
}
[Fact]
public void Add_TakeFromAnotherThread_ExpectedItemsTaken()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
const int NumItems = 100000;
Task producer = Task.Run(() => Parallel.For(1, NumItems + 1, i => Assert.True(c.TryAdd(i))));
var hs = new HashSet<int>();
while (hs.Count < NumItems)
{
int item;
if (c.TryTake(out item)) hs.Add(item);
}
producer.GetAwaiter().GetResult();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
AssertSetsEqual(new HashSet<int>(Enumerable.Range(1, NumItems)), hs);
}
[Fact]
public void AddSome_ThenInterleaveAddsAndTakes_MatchesOracle()
{
IProducerConsumerCollection<int> c = CreateOracle();
IProducerConsumerCollection<int> oracle = CreateProducerConsumerCollection();
Action take = () =>
{
int item1;
Assert.True(c.TryTake(out item1));
int item2;
Assert.True(oracle.TryTake(out item2));
Assert.Equal(item1, item2);
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
};
for (int i = 0; i < 100; i++)
{
Assert.True(oracle.TryAdd(i));
Assert.True(c.TryAdd(i));
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
// Start taking some after we've added some
if (i > 50)
{
take();
}
}
// Take the rest
while (c.Count > 0)
{
take();
}
}
[Fact]
public void AddTake_RandomChangesMatchOracle()
{
const int Iters = 1000;
var r = new Random(42);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Iters; i++)
{
if (r.NextDouble() < .5)
{
Assert.Equal(oracle.TryAdd(i), c.TryAdd(i));
}
else
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
Assert.Equal(oracle.Count, c.Count);
}
[Theory]
[InlineData(100, 1, 100, true)]
[InlineData(100, 4, 10, false)]
[InlineData(1000, 11, 100, true)]
[InlineData(100000, 2, 50000, true)]
public void Initialize_ThenTakeOrPeekInParallel_ItemsObtainedAsExpected(int numStartingItems, int threadsCount, int itemsPerThread, bool take)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, numStartingItems));
int successes = 0;
using (var b = new Barrier(threadsCount))
{
WaitAllOrAnyFailed(Enumerable.Range(0, threadsCount).Select(threadNum => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
for (int j = 0; j < itemsPerThread; j++)
{
int data;
if (take ? c.TryTake(out data) : TryPeek(c, out data))
{
Interlocked.Increment(ref successes);
Assert.NotEqual(0, data); // shouldn't be default(T)
}
}
})).ToArray());
}
Assert.Equal(
take ? numStartingItems : threadsCount * itemsPerThread,
successes);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void ToArray_AddAllItemsThenEnumerate_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < count; i++)
{
Assert.Equal(oracle.TryAdd(i + count), c.TryAdd(i + count));
}
Assert.Equal(oracle.ToArray(), c.ToArray());
if (count > 0)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Theory]
[InlineData(1, 10)]
[InlineData(2, 10)]
[InlineData(10, 10)]
[InlineData(100, 10)]
public void ToArray_AddAndTakeItemsIntermixedWithEnumeration_ItemsAndCountMatch(int initialCount, int iters)
{
IEnumerable<int> initialItems = Enumerable.Range(1, initialCount);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
for (int i = 0; i < iters; i++)
{
Assert.Equal<int>(oracle, c);
Assert.Equal(oracle.TryAdd(initialCount + i), c.TryAdd(initialCount + i));
Assert.Equal<int>(oracle, c);
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal<int>(oracle, c);
}
}
[Fact]
public void AddFromMultipleThreads_ItemsRemainAfterThreadsGoAway()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
for (int i = 0; i < 1000; i += 100)
{
// Create a thread that adds items to the collection
ThreadFactory.StartNew(() =>
{
for (int j = i; j < i + 100; j++)
{
Assert.True(c.TryAdd(j));
}
}).GetAwaiter().GetResult();
// Allow threads to be collected
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
AssertSetsEqual(new HashSet<int>(Enumerable.Range(0, 1000)), new HashSet<int>(c));
}
[Fact]
public void AddManyItems_ThenTakeOnSameThread_ItemsOutputInExpectedOrder()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 100000));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(0, 100000));
for (int i = 99999; i >= 0; --i)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
[Fact]
public void TryPeek_SucceedsOnEmptyCollectionThatWasOnceNonEmpty()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
int item;
for (int i = 0; i < 2; i++)
{
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
}
Assert.True(c.TryAdd(42));
for (int i = 0; i < 2; i++)
{
Assert.True(TryPeek(c, out item));
Assert.Equal(42, item);
}
Assert.True(c.TryTake(out item));
Assert.Equal(42, item);
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
Assert.False(c.TryTake(out item));
Assert.Equal(0, item);
}
[Fact]
public void AddTakeWithAtLeastOneElementInCollection_IsEmpty_AlwaysFalse()
{
int items = 1000;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(0)); // make sure it's never empty
var cts = new CancellationTokenSource();
// Consumer repeatedly calls IsEmpty until it's told to stop
Task consumer = Task.Run(() =>
{
while (!cts.IsCancellationRequested) Assert.False(IsEmpty(c));
});
// Producer adds/takes a bunch of items, then tells the consumer to stop
Task producer = Task.Run(() =>
{
int ignored;
for (int i = 1; i <= items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(c.TryTake(out ignored));
}
cts.Cancel();
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void CopyTo_Empty_NothingCopied()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
c.CopyTo(new int[0], 0);
c.CopyTo(new int[10], 10);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size];
c.CopyTo(actual, 0);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size];
oracle.CopyTo(expected, 0);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_NonZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size + 2];
c.CopyTo(actual, 1);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size + 2];
oracle.CopyTo(expected, 1);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Multidim rank 1 arrays not supported: https://github.com/dotnet/corert/issues/3331")]
public void CopyTo_ArrayZeroLowerBound_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
c.CopyTo(actual, 0);
ICollection oracle = CreateOracle(initialItems);
Array expected = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
oracle.CopyTo(expected, 0);
Assert.Equal(expected.Cast<int>(), actual.Cast<int>());
}
[Fact]
public void CopyTo_ArrayNonZeroLowerBound_ExpectedElementsCopied()
{
if (!PlatformDetection.IsNonZeroLowerBoundArraySupported)
return;
int[] initialItems = Enumerable.Range(1, 10).ToArray();
const int LowerBound = 1;
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { initialItems.Length }, new int[] { LowerBound });
c.CopyTo(actual, LowerBound);
ICollection oracle = CreateOracle(initialItems);
int[] expected = new int[initialItems.Length];
oracle.CopyTo(expected, 0);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual.GetValue(i + LowerBound));
}
}
[Fact]
public void CopyTo_InvalidArgs_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
int[] dest = new int[10];
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length - 2));
Assert.Throws<ArgumentException>(() => c.CopyTo(new int[7, 7], 0));
}
[Fact]
public void ICollectionCopyTo_InvalidArgs_Throws()
{
ICollection c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
Array dest = new int[10];
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length - 2));
}
[Theory]
[InlineData(100, 1, 10)]
[InlineData(4, 100000, 10)]
public void BlockingCollection_WrappingCollection_ExpectedElementsTransferred(int numThreadsPerConsumerProducer, int numItemsPerThread, int producerSpin)
{
var bc = new BlockingCollection<int>(CreateProducerConsumerCollection());
long dummy = 0;
Task[] producers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 1; i <= numItemsPerThread; i++)
{
for (int j = 0; j < producerSpin; j++) dummy *= j; // spin a little
bc.Add(i);
}
})).ToArray();
Task[] consumers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 0; i < numItemsPerThread; i++)
{
const int TimeoutMs = 100000;
int item;
Assert.True(bc.TryTake(out item, TimeoutMs), $"Couldn't get {i}th item after {TimeoutMs}ms");
Assert.NotEqual(0, item);
}
})).ToArray();
WaitAllOrAnyFailed(producers);
WaitAllOrAnyFailed(consumers);
}
[Fact]
public void GetEnumerator_NonGeneric()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IEnumerable e = c;
Assert.False(e.GetEnumerator().MoveNext());
Assert.True(c.TryAdd(42));
Assert.True(c.TryAdd(84));
var hs = new HashSet<int>(e.Cast<int>());
Assert.Equal(2, hs.Count);
Assert.Contains(42, hs);
Assert.Contains(84, hs);
}
[Fact]
public void GetEnumerator_EnumerationsAreSnapshots()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c);
using (IEnumerator<int> e1 = c.GetEnumerator())
{
Assert.True(c.TryAdd(1));
using (IEnumerator<int> e2 = c.GetEnumerator())
{
Assert.True(c.TryAdd(2));
using (IEnumerator<int> e3 = c.GetEnumerator())
{
int item;
Assert.True(c.TryTake(out item));
using (IEnumerator<int> e4 = c.GetEnumerator())
{
Assert.False(e1.MoveNext());
Assert.True(e2.MoveNext());
Assert.False(e2.MoveNext());
Assert.True(e3.MoveNext());
Assert.True(e3.MoveNext());
Assert.False(e3.MoveNext());
Assert.True(e4.MoveNext());
Assert.False(e4.MoveNext());
}
}
}
}
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(1, false)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(100, false)]
public async Task GetEnumerator_Generic_ExpectedElementsYielded(int numItems, bool consumeFromSameThread)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
using (var e = c.GetEnumerator())
{
Assert.False(e.MoveNext());
}
// Add, and validate enumeration after each item added
for (int i = 1; i <= numItems; i++)
{
Assert.True(c.TryAdd(i));
Assert.Equal(i, c.Count);
Assert.Equal(i, c.Distinct().Count());
}
// Take, and validate enumerate after each item removed.
Action consume = () =>
{
for (int i = 1; i <= numItems; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.Equal(numItems - i, c.Count);
Assert.Equal(numItems - i, c.Distinct().Count());
}
};
if (consumeFromSameThread)
{
consume();
}
else
{
await ThreadFactory.StartNew(consume);
}
}
[Fact]
public void TryAdd_TryTake_ToArray()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(42));
Assert.Equal(new[] { 42 }, c.ToArray());
Assert.True(c.TryAdd(84));
Assert.Equal(new[] { 42, 84 }, c.ToArray().OrderBy(i => i));
int item;
Assert.True(c.TryTake(out item));
int remainingItem = item == 42 ? 84 : 42;
Assert.Equal(new[] { remainingItem }, c.ToArray());
Assert.True(c.TryTake(out item));
Assert.Equal(remainingItem, item);
Assert.Empty(c.ToArray());
}
[Fact]
public void ICollection_IsSynchronized_SyncRoot()
{
ICollection c = CreateProducerConsumerCollection();
Assert.False(c.IsSynchronized);
Assert.Throws<NotSupportedException>(() => c.SyncRoot);
}
[Fact]
public void ToArray_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c.ToArray());
Assert.Equal(NumItems, hs.Count);
});
}
[Fact]
public void ToArray_AddTakeSameThread_ExpectedResultsAfterAddsAndTakes()
{
const int Items = 20;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(oracle.TryAdd(i));
Assert.Equal(oracle.ToArray(), c.ToArray());
}
for (int i = Items - 1; i >= 0; i--)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Fact]
public void GetEnumerator_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c);
Assert.Equal(NumItems, hs.Count);
});
}
[Theory]
[InlineData(1, ConcurrencyTestSeconds / 2)]
[InlineData(4, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_EnsureTrackedCountsMatchResultingCollection(int threadsPerProc, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
DateTime end = default(DateTime);
using (var b = new Barrier(Environment.ProcessorCount * threadsPerProc, _ => end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds)))
{
Task<int>[] tasks = Enumerable.Range(0, b.ParticipantCount).Select(_ => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
int count = 0;
var rand = new Random();
while (DateTime.UtcNow < end)
{
if (rand.NextDouble() < .5)
{
Assert.True(c.TryAdd(rand.Next()));
count++;
}
else
{
int item;
if (c.TryTake(out item)) count--;
}
}
return count;
})).ToArray();
Task.WaitAll(tasks);
Assert.Equal(tasks.Sum(t => t.Result), c.Count);
}
}
[Fact]
[OuterLoop]
public void ManyConcurrentAddsTakes_CollectionRemainsConsistent()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int operations = 30000;
Action addAndRemove = () =>
{
for (int i = 1; i < operations; i++)
{
int addCount = new Random(12354).Next(1, 100);
int item;
for (int j = 0; j < addCount; j++)
Assert.True(c.TryAdd(i));
for (int j = 0; j < addCount; j++)
Assert.True(c.TryTake(out item));
}
};
const int numberOfThreads = 3;
var tasks = new Task[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
tasks[i] = ThreadFactory.StartNew(addAndRemove);
// Wait for them all to finish
WaitAllOrAnyFailed(tasks);
Assert.Empty(c);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsTaking(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
total++;
}
int item;
if (TryPeek(c, out item))
{
Assert.InRange(item, 1, MaxCount);
}
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item, 1, MaxCount);
}
}
}
return total;
});
Task<long> takesFromOtherThread = ThreadFactory.StartNew(() =>
{
long total = 0;
int item;
while (DateTime.UtcNow < end)
{
if (c.TryTake(out item))
{
total++;
Assert.InRange(item, 1, MaxCount);
}
}
return total;
});
WaitAllOrAnyFailed(addsTakes, takesFromOtherThread);
long remaining = addsTakes.Result - takesFromOtherThread.Result;
Assert.InRange(remaining, 0, long.MaxValue);
Assert.Equal(remaining, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsPeeking(double seconds)
{
IProducerConsumerCollection<LargeStruct> c = CreateProducerConsumerCollection<LargeStruct>();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(new LargeStruct(i)));
total++;
}
LargeStruct item;
Assert.True(TryPeek(c, out item));
Assert.InRange(item.Value, 1, MaxCount);
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item.Value, 1, MaxCount);
}
}
}
return total;
});
Task peeksFromOtherThread = ThreadFactory.StartNew(() =>
{
LargeStruct item;
while (DateTime.UtcNow < end)
{
if (TryPeek(c, out item))
{
Assert.InRange(item.Value, 1, MaxCount);
}
}
});
WaitAllOrAnyFailed(addsTakes, peeksFromOtherThread);
Assert.Equal(0, addsTakes.Result);
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakes_ForceContentionWithToArray(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.ToArray();
Assert.InRange(arr.Length, 0, MaxCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(0, ConcurrencyTestSeconds / 2)]
[InlineData(1, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_ForceContentionWithGetEnumerator(int initialCount, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, initialCount));
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.Select(i => i).ToArray();
Assert.InRange(arr.Length, initialCount, MaxCount + initialCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(initialCount, c.Count);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributes_Success(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(count);
DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(c);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerTypeProxy_Ctor_NullArgument_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Type proxyType = DebuggerAttributes.GetProxyType(c);
var tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, new object[] { null }));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
protected static void AssertSetsEqual<T>(HashSet<T> expected, HashSet<T> actual)
{
Assert.Equal(expected.Count, actual.Count);
Assert.Subset(expected, actual);
Assert.Subset(actual, expected);
}
protected static void WaitAllOrAnyFailed(params Task[] tasks)
{
if (tasks.Length == 0)
{
return;
}
int remaining = tasks.Length;
var mres = new ManualResetEventSlim();
foreach (Task task in tasks)
{
task.ContinueWith(t =>
{
if (Interlocked.Decrement(ref remaining) == 0 || t.IsFaulted)
{
mres.Set();
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
mres.Wait();
// Either all tasks are completed or at least one failed
foreach (Task t in tasks)
{
if (t.IsFaulted)
{
t.GetAwaiter().GetResult(); // propagate for the first one that failed
}
}
}
private struct LargeStruct // used to help validate that values aren't torn while being read
{
private readonly long _a, _b, _c, _d, _e, _f, _g, _h;
public LargeStruct(long value) { _a = _b = _c = _d = _e = _f = _g = _h = value; }
public long Value
{
get
{
if (_a != _b || _a != _c || _a != _d || _a != _e || _a != _f || _a != _g || _a != _h)
{
throw new Exception($"Inconsistent {nameof(LargeStruct)}: {_a} {_b} {_c} {_d} {_e} {_f} {_g} {_h}");
}
return _a;
}
}
}
}
}
| |
using System.IO;
using Core.Library;
namespace Syntax_Analyzer {
/**
* <remarks>A character stream tokenizer.</remarks>
*/
public class SyntaxTokenizer : Tokenizer {
/**
* <summary>Creates a new tokenizer for the specified input
* stream.</summary>
*
* <param name='input'>the input stream to read</param>
*
* <exception cref='ParserCreationException'>if the tokenizer
* couldn't be initialized correctly</exception>
*/
public SyntaxTokenizer(TextReader input)
: base(input, false) {
CreatePatterns();
}
/**
* <summary>Initializes the tokenizer by creating all the token
* patterns.</summary>
*
* <exception cref='ParserCreationException'>if the tokenizer
* couldn't be initialized correctly</exception>
*/
private void CreatePatterns() {
TokenPattern pattern;
pattern = new TokenPattern((int) SyntaxConstants.TASK,
"TASK",
TokenPattern.PatternType.STRING,
"Task");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.LEAD,
"LEAD",
TokenPattern.PatternType.STRING,
"Lead");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.START,
"START",
TokenPattern.PatternType.STRING,
"Start");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.END,
"END",
TokenPattern.PatternType.STRING,
"End");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.VAR,
"VAR",
TokenPattern.PatternType.STRING,
"Var");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.ID,
"ID",
TokenPattern.PatternType.STRING,
"id");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.AS,
"AS",
TokenPattern.PatternType.STRING,
"as");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.LET,
"LET",
TokenPattern.PatternType.STRING,
"Let");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.OBJECT,
"OBJECT",
TokenPattern.PatternType.STRING,
"Object");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.OF,
"OF",
TokenPattern.PatternType.STRING,
"of");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.BY,
"BY",
TokenPattern.PatternType.STRING,
"by");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.IS,
"IS",
TokenPattern.PatternType.STRING,
"is");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.CLEAR,
"CLEAR",
TokenPattern.PatternType.STRING,
"Clear");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.READ,
"READ",
TokenPattern.PatternType.STRING,
"Read");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.SAY,
"SAY",
TokenPattern.PatternType.STRING,
"Say");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.SKIP,
"SKIP",
TokenPattern.PatternType.STRING,
"Skip");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.STOP,
"STOP",
TokenPattern.PatternType.STRING,
"Stop");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.IF,
"IF",
TokenPattern.PatternType.STRING,
"If");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.OR,
"OR",
TokenPattern.PatternType.STRING,
"Or");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.OTHERWISE,
"OTHERWISE",
TokenPattern.PatternType.STRING,
"Otherwise");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.OPTION,
"OPTION",
TokenPattern.PatternType.STRING,
"Option");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.STATE,
"STATE",
TokenPattern.PatternType.STRING,
"State");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.DEFAULT,
"DEFAULT",
TokenPattern.PatternType.STRING,
"Default");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.UNTIL,
"UNTIL",
TokenPattern.PatternType.STRING,
"Until");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.LOOP,
"LOOP",
TokenPattern.PatternType.STRING,
"Loop");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.LOOPIF,
"LOOPIF",
TokenPattern.PatternType.STRING,
"LoopIf");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.DO,
"DO",
TokenPattern.PatternType.STRING,
"Do");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.FOR,
"FOR",
TokenPattern.PatternType.STRING,
"For");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.RESPONSE,
"RESPONSE",
TokenPattern.PatternType.STRING,
"Response");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.ENDIF,
"ENDIF",
TokenPattern.PatternType.STRING,
"EndIf");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.INT,
"INT",
TokenPattern.PatternType.STRING,
"Int");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.DOUBLE,
"DOUBLE",
TokenPattern.PatternType.STRING,
"Double");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.CHAR,
"CHAR",
TokenPattern.PatternType.STRING,
"Char");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.STRING,
"STRING",
TokenPattern.PatternType.STRING,
"String");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.NULL,
"NULL",
TokenPattern.PatternType.STRING,
"Null");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.ARRAY,
"ARRAY",
TokenPattern.PatternType.STRING,
"Array");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.BOOLEAN,
"BOOLEAN",
TokenPattern.PatternType.STRING,
"Boolean");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.INTLIT,
"INTLIT",
TokenPattern.PatternType.STRING,
"intlit");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.DOUBLELIT,
"DOUBLELIT",
TokenPattern.PatternType.STRING,
"doublelit");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.CHARLIT,
"CHARLIT",
TokenPattern.PatternType.STRING,
"charlit");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.STRINGLIT,
"STRINGLIT",
TokenPattern.PatternType.STRING,
"stringlit");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.BOOLLIT,
"BOOLLIT",
TokenPattern.PatternType.STRING,
"boollit");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.COL,
"COL",
TokenPattern.PatternType.STRING,
":");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.SEM,
"SEM",
TokenPattern.PatternType.STRING,
";");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.DIE,
"DIE",
TokenPattern.PatternType.STRING,
"#");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.PER,
"PER",
TokenPattern.PatternType.STRING,
".");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.OP,
"OP",
TokenPattern.PatternType.STRING,
"(");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.CP,
"CP",
TokenPattern.PatternType.STRING,
")");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.OB,
"OB",
TokenPattern.PatternType.STRING,
"[");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.CB,
"CB",
TokenPattern.PatternType.STRING,
"]");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.ADD,
"ADD",
TokenPattern.PatternType.STRING,
"+");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.MIN,
"MIN",
TokenPattern.PatternType.STRING,
"-");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.MUL,
"MUL",
TokenPattern.PatternType.STRING,
"*");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.DIV,
"DIV",
TokenPattern.PatternType.STRING,
"/");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.MOD,
"MOD",
TokenPattern.PatternType.STRING,
"%");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.INC,
"INC",
TokenPattern.PatternType.STRING,
"++");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.DEC,
"DEC",
TokenPattern.PatternType.STRING,
"--");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.ISEQ,
"ISEQ",
TokenPattern.PatternType.STRING,
"==");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.NOTEQ,
"NOTEQ",
TokenPattern.PatternType.STRING,
"!=");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.GREAT,
"GREAT",
TokenPattern.PatternType.STRING,
">");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.LESS,
"LESS",
TokenPattern.PatternType.STRING,
"<");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.LOGAND,
"LOGAND",
TokenPattern.PatternType.STRING,
"&&");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.LOGOR,
"LOGOR",
TokenPattern.PatternType.STRING,
"||");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.NOT,
"NOT",
TokenPattern.PatternType.STRING,
"!");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.EQ,
"EQ",
TokenPattern.PatternType.STRING,
"=");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.COMMA,
"COMMA",
TokenPattern.PatternType.STRING,
",");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.AT,
"AT",
TokenPattern.PatternType.STRING,
"@");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.GEQ,
"GEQ",
TokenPattern.PatternType.STRING,
">=");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.LEQ,
"LEQ",
TokenPattern.PatternType.STRING,
"<=");
AddPattern(pattern);
pattern = new TokenPattern((int) SyntaxConstants.WHITESPACE,
"WHITESPACE",
TokenPattern.PatternType.REGEXP,
"[ \\t\\n\\r]+");
pattern.Ignore = true;
AddPattern(pattern);
}
}
}
| |
using System;
using System.Diagnostics;
namespace Amib.Threading.Internal
{
internal interface ISTPInstancePerformanceCounters : IDisposable
{
void Close();
void SampleThreads(long activeThreads, long inUseThreads);
void SampleWorkItems(long workItemsQueued, long workItemsProcessed);
void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime);
void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime);
}
#if !(WindowsCE)
internal enum STPPerformanceCounterType
{
// Fields
ActiveThreads = 0,
InUseThreads = 1,
OverheadThreads = 2,
OverheadThreadsPercent = 3,
OverheadThreadsPercentBase = 4,
WorkItems = 5,
WorkItemsInQueue = 6,
WorkItemsProcessed = 7,
WorkItemsQueuedPerSecond = 8,
WorkItemsProcessedPerSecond = 9,
AvgWorkItemWaitTime = 10,
AvgWorkItemWaitTimeBase = 11,
AvgWorkItemProcessTime = 12,
AvgWorkItemProcessTimeBase = 13,
WorkItemsGroups = 14,
LastCounter = 14,
}
/// <summary>
/// Summary description for STPPerformanceCounter.
/// </summary>
internal class STPPerformanceCounter
{
// Fields
private readonly PerformanceCounterType _pcType;
protected string _counterHelp;
protected string _counterName;
// Methods
public STPPerformanceCounter(
string counterName,
string counterHelp,
PerformanceCounterType pcType)
{
_counterName = counterName;
_counterHelp = counterHelp;
_pcType = pcType;
}
public void AddCounterToCollection(CounterCreationDataCollection counterData)
{
CounterCreationData counterCreationData = new CounterCreationData(
_counterName,
_counterHelp,
_pcType);
counterData.Add(counterCreationData);
}
// Properties
public string Name
{
get
{
return _counterName;
}
}
}
internal class STPPerformanceCounters
{
// Fields
internal STPPerformanceCounter[] _stpPerformanceCounters;
private static readonly STPPerformanceCounters _instance;
internal const string _stpCategoryHelp = "SmartThreadPool performance counters";
internal const string _stpCategoryName = "SmartThreadPool";
// Methods
static STPPerformanceCounters()
{
_instance = new STPPerformanceCounters();
}
private STPPerformanceCounters()
{
STPPerformanceCounter[] stpPerformanceCounters = new STPPerformanceCounter[]
{
new STPPerformanceCounter("Active threads", "The current number of available in the thread pool.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("In use threads", "The current number of threads that execute a work item.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Overhead threads", "The current number of threads that are active, but are not in use.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("% overhead threads", "The current number of threads that are active, but are not in use in percents.", PerformanceCounterType.RawFraction),
new STPPerformanceCounter("% overhead threads base", "The current number of threads that are active, but are not in use in percents.", PerformanceCounterType.RawBase),
new STPPerformanceCounter("Work Items", "The number of work items in the Smart Thread Pool. Both queued and processed.", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Work Items in queue", "The current number of work items in the queue", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Work Items processed", "The number of work items already processed", PerformanceCounterType.NumberOfItems32),
new STPPerformanceCounter("Work Items queued/sec", "The number of work items queued per second", PerformanceCounterType.RateOfCountsPerSecond32),
new STPPerformanceCounter("Work Items processed/sec", "The number of work items processed per second", PerformanceCounterType.RateOfCountsPerSecond32),
new STPPerformanceCounter("Avg. Work Item wait time/sec", "The average time a work item supends in the queue waiting for its turn to execute.", PerformanceCounterType.AverageCount64),
new STPPerformanceCounter("Avg. Work Item wait time base", "The average time a work item supends in the queue waiting for its turn to execute.", PerformanceCounterType.AverageBase),
new STPPerformanceCounter("Avg. Work Item process time/sec", "The average time it takes to process a work item.", PerformanceCounterType.AverageCount64),
new STPPerformanceCounter("Avg. Work Item process time base", "The average time it takes to process a work item.", PerformanceCounterType.AverageBase),
new STPPerformanceCounter("Work Items Groups", "The current number of work item groups associated with the Smart Thread Pool.", PerformanceCounterType.NumberOfItems32),
};
_stpPerformanceCounters = stpPerformanceCounters;
SetupCategory();
}
private void SetupCategory()
{
if (!PerformanceCounterCategory.Exists(_stpCategoryName))
{
CounterCreationDataCollection counters = new CounterCreationDataCollection();
for (int i = 0; i < _stpPerformanceCounters.Length; i++)
{
_stpPerformanceCounters[i].AddCounterToCollection(counters);
}
PerformanceCounterCategory.Create(
_stpCategoryName,
_stpCategoryHelp,
PerformanceCounterCategoryType.MultiInstance,
counters);
}
}
// Properties
public static STPPerformanceCounters Instance
{
get
{
return _instance;
}
}
}
internal class STPInstancePerformanceCounter : IDisposable
{
// Fields
private bool _isDisposed;
private PerformanceCounter _pcs;
// Methods
protected STPInstancePerformanceCounter()
{
_isDisposed = false;
}
public STPInstancePerformanceCounter(
string instance,
STPPerformanceCounterType spcType) : this()
{
STPPerformanceCounters counters = STPPerformanceCounters.Instance;
_pcs = new PerformanceCounter(
STPPerformanceCounters._stpCategoryName,
counters._stpPerformanceCounters[(int) spcType].Name,
instance,
false);
_pcs.RawValue = _pcs.RawValue;
}
public void Close()
{
if (_pcs != null)
{
_pcs.RemoveInstance();
_pcs.Close();
_pcs = null;
}
}
public void Dispose()
{
Dispose(true);
}
public virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
Close();
}
}
_isDisposed = true;
}
public virtual void Increment()
{
_pcs.Increment();
}
public virtual void IncrementBy(long val)
{
_pcs.IncrementBy(val);
}
public virtual void Set(long val)
{
_pcs.RawValue = val;
}
}
internal class STPInstanceNullPerformanceCounter : STPInstancePerformanceCounter
{
// Methods
public override void Increment() {}
public override void IncrementBy(long value) {}
public override void Set(long val) {}
}
internal class STPInstancePerformanceCounters : ISTPInstancePerformanceCounters
{
private bool _isDisposed;
// Fields
private STPInstancePerformanceCounter[] _pcs;
private static readonly STPInstancePerformanceCounter _stpInstanceNullPerformanceCounter;
// Methods
static STPInstancePerformanceCounters()
{
_stpInstanceNullPerformanceCounter = new STPInstanceNullPerformanceCounter();
}
public STPInstancePerformanceCounters(string instance)
{
_isDisposed = false;
_pcs = new STPInstancePerformanceCounter[(int)STPPerformanceCounterType.LastCounter];
// Call the STPPerformanceCounters.Instance so the static constructor will
// intialize the STPPerformanceCounters singleton.
STPPerformanceCounters.Instance.GetHashCode();
for (int i = 0; i < _pcs.Length; i++)
{
if (instance != null)
{
_pcs[i] = new STPInstancePerformanceCounter(
instance,
(STPPerformanceCounterType) i);
}
else
{
_pcs[i] = _stpInstanceNullPerformanceCounter;
}
}
}
public void Close()
{
if (null != _pcs)
{
for (int i = 0; i < _pcs.Length; i++)
{
if (null != _pcs[i])
{
_pcs[i].Dispose();
}
}
_pcs = null;
}
}
public void Dispose()
{
Dispose(true);
}
public virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
Close();
}
}
_isDisposed = true;
}
private STPInstancePerformanceCounter GetCounter(STPPerformanceCounterType spcType)
{
return _pcs[(int) spcType];
}
public void SampleThreads(long activeThreads, long inUseThreads)
{
GetCounter(STPPerformanceCounterType.ActiveThreads).Set(activeThreads);
GetCounter(STPPerformanceCounterType.InUseThreads).Set(inUseThreads);
GetCounter(STPPerformanceCounterType.OverheadThreads).Set(activeThreads-inUseThreads);
GetCounter(STPPerformanceCounterType.OverheadThreadsPercentBase).Set(activeThreads-inUseThreads);
GetCounter(STPPerformanceCounterType.OverheadThreadsPercent).Set(inUseThreads);
}
public void SampleWorkItems(long workItemsQueued, long workItemsProcessed)
{
GetCounter(STPPerformanceCounterType.WorkItems).Set(workItemsQueued+workItemsProcessed);
GetCounter(STPPerformanceCounterType.WorkItemsInQueue).Set(workItemsQueued);
GetCounter(STPPerformanceCounterType.WorkItemsProcessed).Set(workItemsProcessed);
GetCounter(STPPerformanceCounterType.WorkItemsQueuedPerSecond).Set(workItemsQueued);
GetCounter(STPPerformanceCounterType.WorkItemsProcessedPerSecond).Set(workItemsProcessed);
}
public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime)
{
GetCounter(STPPerformanceCounterType.AvgWorkItemWaitTime).IncrementBy((long)workItemWaitTime.TotalMilliseconds);
GetCounter(STPPerformanceCounterType.AvgWorkItemWaitTimeBase).Increment();
}
public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime)
{
GetCounter(STPPerformanceCounterType.AvgWorkItemProcessTime).IncrementBy((long)workItemProcessTime.TotalMilliseconds);
GetCounter(STPPerformanceCounterType.AvgWorkItemProcessTimeBase).Increment();
}
}
#endif
internal class NullSTPInstancePerformanceCounters : ISTPInstancePerformanceCounters
{
private static readonly NullSTPInstancePerformanceCounters _instance = new NullSTPInstancePerformanceCounters();
public static NullSTPInstancePerformanceCounters Instance
{
get { return _instance; }
}
public void Close() {}
public void Dispose() {}
public void SampleThreads(long activeThreads, long inUseThreads) {}
public void SampleWorkItems(long workItemsQueued, long workItemsProcessed) {}
public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime) {}
public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime) {}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Xml;
using Orleans.Providers;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Configuration for a particular provider instance.
/// </summary>
[Serializable]
public class ProviderConfiguration : IProviderConfiguration
{
private IDictionary<string, string> properties;
public string Type { get; private set; }
public string Name { get; private set; }
private ReadOnlyDictionary<string, string> readonlyCopyOfProperties;
/// <summary>
/// Properties of this provider.
/// </summary>
public ReadOnlyDictionary<string, string> Properties
{
get
{
if (readonlyCopyOfProperties == null)
{
readonlyCopyOfProperties = new ReadOnlyDictionary<string, string>(properties);
}
return readonlyCopyOfProperties;
}
}
internal ProviderConfiguration()
{
properties = new Dictionary<string, string>();
}
public ProviderConfiguration(IDictionary<string, string> properties, string providerType, string name)
{
this.properties = properties ?? new Dictionary<string, string>(1);
Type = providerType;
Name = name;
}
// for testing purposes
internal ProviderConfiguration(IDictionary<string, string> properties)
{
this.properties = properties ?? new Dictionary<string, string>(1);
}
// Load from an element with the format <Provider Type="..." Name="...">...</Provider>
internal void Load(XmlElement child, IDictionary<string, IProviderConfiguration> alreadyLoaded, XmlNamespaceManager nsManager)
{
readonlyCopyOfProperties = null; // cause later refresh of readonlyCopyOfProperties
if (nsManager == null)
{
nsManager = new XmlNamespaceManager(new NameTable());
nsManager.AddNamespace("orleans", "urn:orleans");
}
if (child.HasAttribute("Name"))
{
Name = child.GetAttribute("Name");
}
if (alreadyLoaded != null && alreadyLoaded.ContainsKey(Name))
{
// This is just a reference to an already defined provider
var provider = (ProviderConfiguration)alreadyLoaded[Name];
properties = provider.properties;
Type = provider.Type;
return;
}
if (child.HasAttribute("Type"))
{
Type = child.GetAttribute("Type");
}
else
{
throw new FormatException("Missing 'Type' attribute on 'Provider' element");
}
if (String.IsNullOrEmpty(Name))
{
Name = Type;
}
properties = new Dictionary<string, string>();
for (int i = 0; i < child.Attributes.Count; i++)
{
var key = child.Attributes[i].LocalName;
var val = child.Attributes[i].Value;
if ((key != "Type") && (key != "Name"))
{
properties[key] = val;
}
}
LoadProviderConfigurations(child, nsManager, alreadyLoaded, c => { });
}
internal static void LoadProviderConfigurations(XmlElement root, XmlNamespaceManager nsManager,
IDictionary<string, IProviderConfiguration> alreadyLoaded, Action<ProviderConfiguration> add)
{
var nodes = root.SelectNodes("orleans:Provider", nsManager);
foreach (var node in nodes)
{
var subElement = node as XmlElement;
if (subElement == null) continue;
var config = new ProviderConfiguration();
config.Load(subElement, alreadyLoaded, nsManager);
add(config);
}
}
public void SetProperty(string key, string val)
{
readonlyCopyOfProperties = null; // cause later refresh of readonlyCopyOfProperties
if (!properties.ContainsKey(key))
{
properties.Add(key, val);
}
else
{
// reset the property.
properties.Remove(key);
properties.Add(key, val);
}
}
public bool RemoveProperty(string key)
{
readonlyCopyOfProperties = null; // cause later refresh of readonlyCopyOfProperties
return properties.Remove(key);
}
public override string ToString()
{
// print only _properties keys, not values, to not leak application sensitive data.
var propsStr = properties == null ? "Null" : Utils.EnumerableToString(properties.Keys);
return string.Format("Name={0}, Type={1}, Properties={2}", Name, Type, propsStr);
}
}
/// <summary>
/// Provider category configuration.
/// </summary>
[Serializable]
public class ProviderCategoryConfiguration
{
public const string STORAGE_PROVIDER_CATEGORY_NAME = "Storage";
public const string STREAM_PROVIDER_CATEGORY_NAME = "Stream";
public const string LOG_CONSISTENCY_PROVIDER_CATEGORY_NAME = "LogConsistency";
public string Name { get; set; }
public IDictionary<string, IProviderConfiguration> Providers { get; set; }
public ProviderCategoryConfiguration(string name)
{
Name = name;
Providers = new Dictionary<string, IProviderConfiguration>();
}
// Load from an element with the format <NameProviders>...</NameProviders>
// that contains a sequence of Provider elements (see the ProviderConfiguration type)
internal static ProviderCategoryConfiguration Load(XmlElement child)
{
string name = child.LocalName.Substring(0, child.LocalName.Length - 9);
var category = new ProviderCategoryConfiguration(name);
var nsManager = new XmlNamespaceManager(new NameTable());
nsManager.AddNamespace("orleans", "urn:orleans");
ProviderConfiguration.LoadProviderConfigurations(
child, nsManager, category.Providers,
c => category.Providers.Add(c.Name, c));
return category;
}
internal void Merge(ProviderCategoryConfiguration other)
{
foreach (var provider in other.Providers)
{
Providers.Add(provider);
}
}
internal void SetConfiguration(string key, string val)
{
foreach (IProviderConfiguration config in Providers.Values)
{
((ProviderConfiguration)config).SetProperty(key, val);
}
}
internal static string ProviderConfigsToXmlString(IDictionary<string, ProviderCategoryConfiguration> providerConfig)
{
var sb = new StringBuilder();
foreach (string category in providerConfig.Keys)
{
var providerInfo = providerConfig[category];
string catName = providerInfo.Name;
sb.AppendFormat("<{0}Providers>", catName).AppendLine();
foreach (string provName in providerInfo.Providers.Keys)
{
var prov = (ProviderConfiguration) providerInfo.Providers[provName];
sb.AppendLine("<Provider");
sb.AppendFormat(" Name=\"{0}\"", provName).AppendLine();
sb.AppendFormat(" Type=\"{0}\"", prov.Type).AppendLine();
foreach (var propName in prov.Properties.Keys)
{
sb.AppendFormat(" {0}=\"{1}\"", propName, prov.Properties[propName]).AppendLine();
}
sb.AppendLine(" />");
}
sb.AppendFormat("</{0}Providers>", catName).AppendLine();
}
return sb.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
foreach (var kv in Providers)
{
sb.AppendFormat(" {0}", kv.Value).AppendLine();
}
return sb.ToString();
}
}
internal class ProviderConfigurationUtility
{
internal static void RegisterProvider(IDictionary<string, ProviderCategoryConfiguration> providerConfigurations, string providerCategory, string providerTypeFullName, string providerName, IDictionary<string, string> properties = null)
{
if (string.IsNullOrEmpty(providerCategory))
throw new ArgumentException("Provider Category cannot be null or empty string", "providerCategory");
if (string.IsNullOrEmpty(providerTypeFullName))
throw new ArgumentException("Provider type full name cannot be null or empty string", "providerTypeFullName");
if (string.IsNullOrEmpty(providerName))
throw new ArgumentException("Provider name cannot be null or empty string", "providerName");
ProviderCategoryConfiguration category;
if (!providerConfigurations.TryGetValue(providerCategory, out category))
{
category = new ProviderCategoryConfiguration(providerCategory);
providerConfigurations.Add(category.Name, category);
}
if (category.Providers.ContainsKey(providerName))
throw new InvalidOperationException(
string.Format("{0} provider of type {1} with name '{2}' has been already registered", providerCategory, providerTypeFullName, providerName));
var config = new ProviderConfiguration(
properties ?? new Dictionary<string, string>(),
providerTypeFullName, providerName);
category.Providers.Add(config.Name, config);
}
internal static bool TryGetProviderConfiguration(IDictionary<string, ProviderCategoryConfiguration> providerConfigurations,
string providerTypeFullName, string providerName, out IProviderConfiguration config)
{
foreach (ProviderCategoryConfiguration category in providerConfigurations.Values)
{
foreach (IProviderConfiguration providerConfig in category.Providers.Values)
{
if (providerConfig.Type.Equals(providerTypeFullName) && providerConfig.Name.Equals(providerName))
{
config = providerConfig;
return true;
}
}
}
config = null;
return false;
}
internal static IEnumerable<IProviderConfiguration> GetAllProviderConfigurations(IDictionary<string, ProviderCategoryConfiguration> providerConfigurations)
{
return providerConfigurations.Values.SelectMany(category => category.Providers.Values);
}
internal static string PrintProviderConfigurations(IDictionary<string, ProviderCategoryConfiguration> providerConfigurations)
{
var sb = new StringBuilder();
if (providerConfigurations.Keys.Count > 0)
{
foreach (string provType in providerConfigurations.Keys)
{
ProviderCategoryConfiguration provTypeConfigs = providerConfigurations[provType];
sb.AppendFormat(" {0}Providers:", provType)
.AppendLine();
sb.AppendFormat(provTypeConfigs.ToString())
.AppendLine();
}
}
else
{
sb.AppendLine(" No providers configured.");
}
return sb.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Edubase.Areas.HelpPage.ModelDescriptions;
using Edubase.Areas.HelpPage.Models;
namespace Edubase.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 media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), 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 description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <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)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.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}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Platform.Runtime;
using System.Data.Common;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Web.Services;
using System.Web.UI;
/*
* High performance automated object model
* Created by an automatic tool
* */
namespace Services.Packages
{
/// <summary>
/// Defines the contract for the LocalPackage class
/// </summary>
[ComVisible(true)]
[Guid("809b654f-9180-98fa-92b6-4984490462e4")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface ILocalPackage
{
bool Exists { get; }
System.String PackageName { get; set; }
System.Int32 Id { get; set; }
System.String VersionLabel { get; set; }
void Read(System.String __PackageName);
void Reload();
void Create();
void Update();
void Delete();
void CopyWithKeysFrom(LocalPackage _object);
void CopyWithKeysTo(LocalPackage _object);
void CopyFrom(LocalPackage _object);
void CopyTo(LocalPackage _object);
}
/// <summary>
/// Defines the contract for all the service-based types which can
/// apply servicing on Services.Packages.LocalPackage type.
/// </summary>
[ComVisible(true)]
[Guid("212760b9-5ea9-f17a-b7d5-a3526d5b8a41")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[ServiceContract(Namespace="http://services.msd.com")]
public interface ILocalPackageService
{
string Uri { get; set; }
[OperationContract]
bool Exists(LocalPackage _LocalPackage);
[OperationContract]
LocalPackage Read(System.String __PackageName);
[OperationContract]
LocalPackage Reload(LocalPackage _LocalPackage);
[OperationContract]
LocalPackage Create(System.String __PackageName);
[OperationContract]
void Delete(System.String __PackageName);
[OperationContract]
void UpdateObject(LocalPackage _LocalPackage);
[OperationContract]
void CreateObject(LocalPackage _LocalPackage);
[OperationContract]
void DeleteObject(LocalPackage _LocalPackage);
[OperationContract]
void Undo();
[OperationContract]
void Redo();
[OperationContract]
LocalPackageCollection SearchByPackageName(System.String PackageName );
[OperationContract]
LocalPackageCollection SearchByPackageNamePaged(System.String PackageName , long PagingStart, long PagingCount);
[OperationContract]
long SearchByPackageNameCount(System.String PackageName );
}
/// <summary>
/// WCF and default implementation of a service object for Services.Packages.LocalPackage type.
/// </summary>
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("8358e20d-5270-4751-3242-2005322d0b2d")]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
UseSynchronizationContext=false,
IncludeExceptionDetailInFaults = true,
AddressFilterMode=AddressFilterMode.Any,
Namespace="http://services.msd.com")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
sealed public class LocalPackageService : ILocalPackageService
{
/// <summary>
/// Not supported. Throws a NotSupportedException on get or set.
/// </summary>
public string Uri
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
[WebMethod]
public bool Exists(LocalPackage _LocalPackage)
{
return _LocalPackage.Exists;
}
[WebMethod]
public LocalPackage Read(System.String __PackageName)
{
return new LocalPackage(__PackageName);
}
[WebMethod]
public LocalPackage Reload(LocalPackage _LocalPackage)
{
_LocalPackage.Reload();
return _LocalPackage;
}
[WebMethod]
public LocalPackage Create(System.String __PackageName)
{
return LocalPackage.CreateLocalPackage(__PackageName);
}
[WebMethod]
public void Delete(System.String __PackageName)
{
LocalPackage.DeleteLocalPackage(__PackageName);
}
[WebMethod]
public void UpdateObject(LocalPackage _LocalPackage)
{
_LocalPackage.Update();
}
[WebMethod]
public void CreateObject(LocalPackage _LocalPackage)
{
_LocalPackage.Create();
}
[WebMethod]
public void DeleteObject(LocalPackage _LocalPackage)
{
_LocalPackage.Delete();
}
[WebMethod]
public void Undo()
{
LocalPackage.Undo();
}
[WebMethod]
public void Redo()
{
LocalPackage.Redo();
}
[WebMethod]
public LocalPackageCollection SearchByPackageName(System.String PackageName )
{
return LocalPackage.SearchByPackageName(PackageName );
}
[WebMethod]
public LocalPackageCollection SearchByPackageNamePaged(System.String PackageName , long PagingStart, long PagingCount)
{
return LocalPackage.SearchByPackageNamePaged(PackageName , PagingStart, PagingCount);
}
[WebMethod]
public long SearchByPackageNameCount(System.String PackageName )
{
return LocalPackage.SearchByPackageNameCount(PackageName );
}
}
/// <summary>
/// Provides the implementation of Services.Packages.LocalPackage model that acts as DAL for
/// a database table.
/// </summary>
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("647b34f0-9526-f111-eaaa-c8abeea72a36")]
[DataContract]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
[Serializable]
public class LocalPackage : ILocalPackage, IHierarchyData, global::Platform.Runtime.Data.IModelHierachyData
{
#region Servicing support
// Synchronized replication
[NonSerialized]
static List<ILocalPackageService> replicationServices = null;
// Scaling proxy objects (using 1 object you get forwarding)
[NonSerialized]
static List<ILocalPackageService> scalingServices = null;
// static IServiceSelectionAlgorithm serviceSelectionAlgorithm = null;
// Failover scenario
[NonSerialized]
static List<ILocalPackageService> failoverServices = null;
#endregion
#region Connection provider and DbConnection selection support
[NonSerialized]
static string classConnectionString = null;
[NonSerialized]
string instanceConnectionString = null;
[System.Xml.Serialization.XmlIgnoreAttribute]
public static string ClassConnectionString
{
get
{
if (!String.IsNullOrEmpty(classConnectionString))
return classConnectionString;
if (global::System.Configuration.ConfigurationManager.ConnectionStrings["Services.Packages.LocalPackage"] != null)
classConnectionString = global::System.Configuration.ConfigurationManager.ConnectionStrings["Services.Packages.LocalPackage"].ConnectionString;
if (!String.IsNullOrEmpty(classConnectionString))
return classConnectionString;
if (!String.IsNullOrEmpty(Platform.Module.Packages.ConnectionString))
return Platform.Module.Packages.ConnectionString;
throw new InvalidOperationException("The sql connection string has not been set up in any level");
}
set
{
classConnectionString = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute]
public string ConnectionString
{
get
{
if (!String.IsNullOrEmpty(instanceConnectionString))
return instanceConnectionString;
return ClassConnectionString;
}
set
{
instanceConnectionString = value;
}
}
[NonSerialized]
static global::Platform.Runtime.SqlProviderType classSqlProviderType = global::Platform.Runtime.SqlProviderType.NotSpecified;
[NonSerialized]
global::Platform.Runtime.SqlProviderType instanceSqlProviderType = global::Platform.Runtime.SqlProviderType.NotSpecified;
[System.Xml.Serialization.XmlIgnoreAttribute]
public static global::Platform.Runtime.SqlProviderType ClassSqlProviderType
{
get
{
if (classSqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified)
return classSqlProviderType;
classSqlProviderType = global::Platform.Runtime.Sql.GetProviderConfiguration("Services.Packages.LocalPackage.ProviderType");
if (classSqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified)
return classSqlProviderType;
if (global::Platform.Module.Packages.SqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified)
return Platform.Module.Packages.SqlProviderType;
throw new InvalidOperationException("The sql provider type has not been set up in any level");
}
set
{
classSqlProviderType = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute]
public global::Platform.Runtime.SqlProviderType InstanceSqlProviderType
{
get
{
if (instanceSqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified)
return instanceSqlProviderType;
return ClassSqlProviderType;
}
set
{
instanceSqlProviderType = value;
}
}
[NonSerialized]
private static global::Platform.Runtime.IConnectionProvider instanceConnectionProvider;
[NonSerialized]
private static global::Platform.Runtime.IConnectionProvider classConnectionProvider;
[System.Xml.Serialization.XmlIgnoreAttribute]
public global::Platform.Runtime.IConnectionProvider InstanceConnectionProvider {
get
{
if (String.IsNullOrEmpty(ConnectionString)
|| InstanceSqlProviderType == Platform.Runtime.SqlProviderType.NotSpecified)
return ClassConnectionProvider;
if (instanceConnectionProvider == null)
{
instanceConnectionProvider = Platform.Runtime.Sql.CreateProvider(InstanceSqlProviderType, ConnectionString);
}
return instanceConnectionProvider;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute]
public static global::Platform.Runtime.IConnectionProvider ClassConnectionProvider {
get
{
if (String.IsNullOrEmpty(ClassConnectionString)
|| ClassSqlProviderType == Platform.Runtime.SqlProviderType.NotSpecified)
return Platform.Module.Packages.ConnectionProvider;
if (classConnectionProvider == null)
{
classConnectionProvider = Platform.Runtime.Sql.CreateProvider(ClassSqlProviderType, ClassConnectionString);
}
return classConnectionProvider;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute]
public global::Platform.Runtime.IConnectionProvider ConnectionProvider {
get
{
if (InstanceConnectionProvider != null)
return InstanceConnectionProvider;
return ClassConnectionProvider;
}
}
#endregion
#region Data row consistency and state
RowState __databaseState = RowState.Empty;
bool __hasBeenReadOnce = false;
#endregion
#region Main implementation - Properties, Relations, CRUD
System.String _PackageName;
// Key member
[DataMember]
[global::System.ComponentModel.Bindable(true)]
public System.String PackageName
{
get
{
return _PackageName;
}
set
{
if (_PackageName != value)
__hasBeenReadOnce = false;
_PackageName = value;
}
}
System.Int32 _Id;
[DataMember]
[global::System.ComponentModel.Bindable(true)]
public System.Int32 Id
{
get
{
return _Id;
}
set
{
_Id = value;
}
}
System.String _VersionLabel;
[DataMember]
[global::System.ComponentModel.Bindable(true)]
public System.String VersionLabel
{
get
{
return _VersionLabel;
}
set
{
_VersionLabel = value;
}
}
public static LocalPackageCollection SearchByPackageName(System.String _PackageName)
{
LocalPackageCollection _LocalPackageCollection = new LocalPackageCollection();
// sql read
using (DbConnection dbconn = ClassConnectionProvider.GetDatabaseConnection(ClassConnectionString))
{
dbconn.Open();
DbCommand command = ClassConnectionProvider.GetDatabaseCommand("LoPaSeByPaNa", dbconn);
command.CommandType = global::System.Data.CommandType.StoredProcedure;
_PackageName = ClassConnectionProvider.Escape(_PackageName);
DbParameter param_PackageName = ClassConnectionProvider.GetDatabaseParameter("PackageName", typeof(System.String), -1);
param_PackageName.Value = ClassConnectionProvider.FromValueToSqlModelType(_PackageName);
command.Parameters.Add(param_PackageName);
ClassConnectionProvider.OnBeforeExecuted(command);
DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection);
while (dr.Read())
{
LocalPackage o = new LocalPackage();
o.__databaseState = RowState.Initialized;
o._PackageName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["PackageName"], typeof(System.String));
o._Id = (System.Int32) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int32));
o._VersionLabel = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["VersionLabel"], typeof(System.String));
_LocalPackageCollection.Add(o);
}
dr.Close();
}
return _LocalPackageCollection;
}
public static LocalPackageCollection SearchByPackageNamePaged(System.String _PackageName, long PagingStart, long PagingCount)
{
LocalPackageCollection _LocalPackageCollection = new LocalPackageCollection();
// sql read
using (DbConnection dbconn = ClassConnectionProvider.GetDatabaseConnection(ClassConnectionString))
{
dbconn.Open();
DbCommand command = ClassConnectionProvider.GetDatabaseCommand("LoPaSeByPaNaPaged", dbconn);
command.CommandType = global::System.Data.CommandType.StoredProcedure;
_PackageName = ClassConnectionProvider.Escape(_PackageName);
DbParameter param_PackageName = ClassConnectionProvider.GetDatabaseParameter("PackageName", typeof(System.String), -1);
param_PackageName.Value = ClassConnectionProvider.FromValueToSqlModelType(_PackageName);
command.Parameters.Add(param_PackageName);
DbParameter __param_PagingStart = ClassConnectionProvider.GetDatabaseParameter("PagingStart", PagingStart);
command.Parameters.Add(__param_PagingStart);
DbParameter __param_PagingCount = ClassConnectionProvider.GetDatabaseParameter("PagingCount", PagingCount);
command.Parameters.Add(__param_PagingCount);
ClassConnectionProvider.OnBeforeExecuted(command);
DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection);
if (ClassSqlProviderType == global::Platform.Runtime.SqlProviderType.SqlServer)
{
while (PagingStart > 0 && dr.Read())
--PagingStart;
}
while (PagingCount > 0 && dr.Read())
{
LocalPackage o = new LocalPackage();
o.__databaseState = RowState.Initialized;
o._PackageName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["PackageName"], typeof(System.String));
o._Id = (System.Int32) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int32));
o._VersionLabel = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["VersionLabel"], typeof(System.String));
_LocalPackageCollection.Add(o);
--PagingCount;
}
dr.Close();
}
return _LocalPackageCollection;
}
public static long SearchByPackageNameCount(System.String _PackageName)
{
long count = 0;
// sql read
using (DbConnection dbconn = ClassConnectionProvider.GetDatabaseConnection(ClassConnectionString))
{
dbconn.Open();
DbCommand command = ClassConnectionProvider.GetDatabaseCommand("LoPaSeByPaNaCount", dbconn);
command.CommandType = global::System.Data.CommandType.StoredProcedure;
_PackageName = ClassConnectionProvider.Escape(_PackageName);
DbParameter param_PackageName = ClassConnectionProvider.GetDatabaseParameter("PackageName", typeof(System.String), -1);
param_PackageName.Value = ClassConnectionProvider.FromValueToSqlModelType(_PackageName);
command.Parameters.Add(param_PackageName);
ClassConnectionProvider.OnBeforeExecuted(command);
count = (int)command.ExecuteScalar();
if (count < 0) count = 0;
}
return count;
}
public bool Exists
{
get {
if (!__hasBeenReadOnce)
Exist();
return __databaseState == RowState.Initialized;
}
}
public LocalPackage() {}
public LocalPackage(System.String __PackageName)
{
Read(__PackageName);
}
#region CRUD
void Exist()
{
// sql read - should be changed to specific exist implementation
using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString))
{
dbconn.Open();
DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("LoPaRead", dbconn);
command.CommandType = global::System.Data.CommandType.StoredProcedure;
DbParameter param_PackageName = ClassConnectionProvider.GetDatabaseParameter("PackageName", typeof(System.String), 1024);
param_PackageName.Value = ClassConnectionProvider.FromValueToSqlModelType(_PackageName);
command.Parameters.Add(param_PackageName);
InstanceConnectionProvider.OnBeforeExecuted(command);
DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection);
if (dr.Read())
{
__databaseState = RowState.Initialized;
}
else
{
__databaseState = RowState.Empty;
}
__hasBeenReadOnce = true;
dr.Close();
}
}
public void Read(System.String __PackageName)
{
if (scalingServices != null)
{
// Forwarding can be used in any scenario (read & write)
if (scalingServices.Count == 1)
{
scalingServices[0].Read(__PackageName);
return;
}
// Get a service via an algorithm
// int nextIndex = serviceSelectionAlgorithm.Pick(scalingServices, "LoPa");
// Perfect for read operations, but not for write
// scalingServices[nextIndex].Read(__PackageName);
// return;
throw new NotImplementedException();
}
try
{
// sql read
using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString))
{
dbconn.Open();
DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("LoPaRead", dbconn);
command.CommandType = global::System.Data.CommandType.StoredProcedure;
_PackageName = __PackageName;
DbParameter param_PackageName = ClassConnectionProvider.GetDatabaseParameter("PackageName", typeof(System.String), 1024);
param_PackageName.Value = ClassConnectionProvider.FromValueToSqlModelType(__PackageName);
command.Parameters.Add(param_PackageName);
InstanceConnectionProvider.OnBeforeExecuted(command);
DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection);
if (dr.Read())
{
_PackageName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["PackageName"], typeof(System.String));
_Id = (System.Int32) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int32));
_VersionLabel = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["VersionLabel"], typeof(System.String));
__databaseState = RowState.Initialized;
}
else
{
__databaseState = RowState.Empty;
}
__hasBeenReadOnce = true;
dr.Close();
}
}
catch (Exception ex)
{
if (failoverServices != null)
{
bool foundFailsafe = false;
for (int n = 0; n < failoverServices.Count; ++n)
{
try
{
failoverServices[n].Read(__PackageName);
foundFailsafe = true;
break;
}
catch
{
// Do not request again from failed services
failoverServices.RemoveAt(n);
--n;
}
}
if (failoverServices.Count == 0)
failoverServices = null;
if (!foundFailsafe)
throw ex;
}
else throw ex;
}
}
public void Reload()
{
if (scalingServices != null)
{
// Forwarding can be used in any scenario (read & write)
if (scalingServices.Count == 1)
{
scalingServices[0].Reload(this);
return;
}
// Get a service via an algorithm
// int nextIndex = serviceSelectionAlgorithm.GetNext(scalingServices, "LoPa");
// Perfect for read operations, but not for write
// return scalingServices[nextIndex].Reload();
throw new NotImplementedException();
}
try
{
// sql read
using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString))
{
dbconn.Open();
DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("LoPaRead", dbconn);
command.CommandType = global::System.Data.CommandType.StoredProcedure;
DbParameter param_PackageName = ClassConnectionProvider.GetDatabaseParameter("PackageName", typeof(System.String), 1024);
param_PackageName.Value = ClassConnectionProvider.FromValueToSqlModelType(_PackageName);
command.Parameters.Add(param_PackageName);
InstanceConnectionProvider.OnBeforeExecuted(command);
DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection);
if (dr.Read())
{
_PackageName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["PackageName"], typeof(System.String));
_Id = (System.Int32) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int32));
_VersionLabel = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["VersionLabel"], typeof(System.String));
__databaseState = RowState.Initialized;
}
else
{
__databaseState = RowState.Empty;
}
__hasBeenReadOnce = true;
dr.Close();
}
}
catch (Exception ex)
{
if (failoverServices != null)
{
bool foundFailsafe = false;
for (int n = 0; n < failoverServices.Count; ++n)
{
try
{
failoverServices[n].Reload(this);
foundFailsafe = true;
break;
}
catch
{
// Do not request again from failed services
failoverServices.RemoveAt(n);
--n;
}
}
if (failoverServices.Count == 0)
failoverServices = null;
if (!foundFailsafe)
throw ex;
}
else throw ex;
}
}
public void Create()
{
if (scalingServices != null)
{
// Forwarding can be used in any scenario (read & write)
if (scalingServices.Count == 1)
{
scalingServices[0].CreateObject(this);
return;
}
// Create/Update/Delete supports scaling only by synchronizing
// scalingServices[0].CreateObject(this);
// scalingServices[0].SynchronizeTo(scalingServices);
throw new NotImplementedException();
}
try
{
if (!Exists)
{
// Mark undo if possible
/*
if (IsUndoRedoSupported) MarkUndo(this, true, false, false);
//*/
// sql create
using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString))
{
dbconn.Open();
DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("LoPaCreate", dbconn);
command.CommandType = global::System.Data.CommandType.StoredProcedure;
DbParameter param_PackageName = ClassConnectionProvider.GetDatabaseParameter("PackageName", typeof(System.String), 1024);
param_PackageName.Value = ClassConnectionProvider.FromValueToSqlModelType(_PackageName);
command.Parameters.Add(param_PackageName);
DbParameter param_Id = ClassConnectionProvider.GetDatabaseParameter("Id", typeof(System.Int32), -1);
param_Id.Value = ClassConnectionProvider.FromValueToSqlModelType(_Id);
command.Parameters.Add(param_Id);
DbParameter param_VersionLabel = ClassConnectionProvider.GetDatabaseParameter("VersionLabel", typeof(System.String), 1024);
param_VersionLabel.Value = ClassConnectionProvider.FromValueToSqlModelType(_VersionLabel);
command.Parameters.Add(param_VersionLabel);
InstanceConnectionProvider.OnBeforeExecuted(command);
DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection);
if (dr.Read())
{
_PackageName = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["PackageName"], typeof(System.String));
_Id = (System.Int32) global::Platform.Runtime.Utilities.FromSqlToValue(dr["Id"], typeof(System.Int32));
_VersionLabel = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["VersionLabel"], typeof(System.String));
}
__databaseState = RowState.Initialized;
}
}
else Update();
}
catch (Exception)
{
// Failsafe scenarios cannot be used for create/update/delete
// Must be handled as an error
throw;
}
// Everything went ok; now replicate in a synchronous way
if (replicationServices != null)
{
// this is only for write/delete operations
for (int n = 0; n < replicationServices.Count; ++n)
{
try
{
replicationServices[n].CreateObject(this);
}
catch
{
// Do not request again from failed services
replicationServices.RemoveAt(n);
--n;
}
}
if (replicationServices.Count == 0)
replicationServices = null;
}
}
static public LocalPackage CreateLocalPackage(System.String __PackageName)
{
LocalPackage o = new LocalPackage(__PackageName);
if (!o.Exists) o.Create();
return o;
}
public void Update()
{
if (scalingServices != null)
{
// Forwarding can be used in any scenario (read & write)
if (scalingServices.Count == 1)
{
scalingServices[0].UpdateObject(this);
return;
}
// Create/Update/Delete supports scaling only by synchronizing
// scalingServices[0].UpdateObject(this);
throw new NotImplementedException();
}
try
{
if (!Exists)
{
this.Create();
return;
}
// Mark undo if possible
/*
if (IsUndoRedoSupported) MarkUndo(this, false, false, true);
//*/
// sql update
using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString))
{
dbconn.Open();
DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("LoPaUpdate", dbconn);
command.CommandType = global::System.Data.CommandType.StoredProcedure;
DbParameter param_PackageName = ClassConnectionProvider.GetDatabaseParameter("PackageName", typeof(System.String), 1024);
param_PackageName.Value = ClassConnectionProvider.FromValueToSqlModelType(_PackageName);
command.Parameters.Add(param_PackageName);
DbParameter param_Id = ClassConnectionProvider.GetDatabaseParameter("Id", typeof(System.Int32), -1);
param_Id.Value = ClassConnectionProvider.FromValueToSqlModelType(_Id);
command.Parameters.Add(param_Id);
DbParameter param_VersionLabel = ClassConnectionProvider.GetDatabaseParameter("VersionLabel", typeof(System.String), 1024);
param_VersionLabel.Value = ClassConnectionProvider.FromValueToSqlModelType(_VersionLabel);
command.Parameters.Add(param_VersionLabel);
command.ExecuteNonQuery();
}
}
catch (Exception)
{
// Failsafe scenarios cannot be used for create/update/delete
// Must be handled as an error
throw;
}
// Everything went ok; now replicate in a synchronous way
if (replicationServices != null)
{
// this is only for write/delete operations
for (int n = 0; n < replicationServices.Count; ++n)
{
try
{
replicationServices[n].UpdateObject(this);
}
catch
{
// Do not request again from failed services
replicationServices.RemoveAt(n);
--n;
}
}
if (replicationServices.Count == 0)
replicationServices = null;
}
}
public void Delete()
{
if (scalingServices != null)
{
// Forwarding can be used in any scenario (read & write)
if (scalingServices.Count == 1)
{
scalingServices[0].DeleteObject(this);
return;
}
// Create/Update/Delete supports scaling only by synchronizing
// scalingServices[0].DeleteObject(this);
throw new NotImplementedException();
}
try
{
if (!Exists)
return;
// Mark undo if possible
/*
if (IsUndoRedoSupported) MarkUndo(this, false, true, false);
//*/
// sql-delete
using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString))
{
dbconn.Open();
DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("LoPaDelete", dbconn);
command.CommandType = global::System.Data.CommandType.StoredProcedure;
DbParameter param_PackageName = ClassConnectionProvider.GetDatabaseParameter("PackageName", typeof(System.String), 1024);
param_PackageName.Value = ClassConnectionProvider.FromValueToSqlModelType(_PackageName);
command.Parameters.Add(param_PackageName);
command.ExecuteNonQuery();
__databaseState = RowState.Empty;
}
}
catch (Exception)
{
// Failsafe scenarios cannot be used for create/update/delete
// Must be handled as an error
throw;
}
// Everything went ok; now replicate in a synchronous way
if (replicationServices != null)
{
// this is only for write/delete operations
for (int n = 0; n < replicationServices.Count; ++n)
{
try
{
replicationServices[n].DeleteObject(this);
}
catch
{
// Do not request again from failed services
replicationServices.RemoveAt(n);
--n;
}
}
if (replicationServices.Count == 0)
replicationServices = null;
}
}
static public void DeleteLocalPackage(System.String __PackageName)
{
LocalPackage o = new LocalPackage(__PackageName);
if (o.Exists) o.Delete();
}
#endregion
#region Copying instances
public void CopyWithKeysFrom(LocalPackage _object)
{
_PackageName = _object._PackageName;
_Id = _object._Id;
_VersionLabel = _object._VersionLabel;
}
public void CopyWithKeysTo(LocalPackage _object)
{
_object._PackageName = _PackageName;
_object._Id = _Id;
_object._VersionLabel = _VersionLabel;
}
static public void CopyWithKeysObject(LocalPackage _objectFrom, LocalPackage _objectTo)
{
_objectFrom.CopyWithKeysTo(_objectTo);
}
public void CopyFrom(LocalPackage _object)
{
_Id = _object._Id;
_VersionLabel = _object._VersionLabel;
}
public void CopyTo(LocalPackage _object)
{
_object._Id = _Id;
_object._VersionLabel = _VersionLabel;
}
static public void CopyObject(LocalPackage _objectFrom, LocalPackage _objectTo)
{
_objectFrom.CopyTo(_objectTo);
}
#endregion
#region Undo / Redo functionality
/*
private static bool isUndoRedoSupported = false;
private static bool isUndoRedoSupportedHasBeenLoaded = false;
private static long undoRedoMaximumObjects = -1;
public static bool IsUndoRedoSupported
{
get {
if (!isUndoRedoSupportedHasBeenLoaded) {
// Load options undo entity once
isUndoRedoSupportedHasBeenLoaded = true;
Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions options = new Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions(typeof(LocalPackage).FullName);
if (!options.Exists)
{
undoRedoMaximumObjects = options.ItemsAllowed = 1000;
options.IsEnabled = true;
options.Create();
isUndoRedoSupported = true;
}
else
{
isUndoRedoSupported = options.IsEnabled;
undoRedoMaximumObjects = options.ItemsAllowed;
}
}
return isUndoRedoSupported;
}
set {
isUndoRedoSupportedHasBeenLoaded = true;
isUndoRedoSupported = value;
Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions options = new Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions(typeof(LocalPackage).FullName);
if (!options.Exists)
{
undoRedoMaximumObjects = options.ItemsAllowed = 1000;
}
options.IsEnabled = isUndoRedoSupported;
options.Update();
}
}
static void MarkUndo(LocalPackage _object, bool IsCreatedUndoDeletes, bool IsDeletedUndoCreates, bool IsUpdatedUndoUpdates)
{
// Delete already undone entries (steps that have been undone but not redone)
LocalPackageUndoRedoCollection allUndidAndNotRedoneEntries = LocalPackageUndoRedo.GetAllFilterByIsUndone(true);
for(int n = 0; n < allUndidAndNotRedoneEntries.Count; ++n)
allUndidAndNotRedoneEntries[n].Delete();
// Create one undo entry
LocalPackageUndoRedo _urobject = new LocalPackageUndoRedo();
// Enumerate all properties and add them to the UndoRedo object
_urobject.PackageName = _object._PackageName;
_urobject.Id = _object._Id;
_urobject.VersionLabel = _object._VersionLabel;
_urobject.IsCreatedUndoDeletes = IsCreatedUndoDeletes;
_urobject.IsDeletedUndoCreates = IsDeletedUndoCreates;
_urobject.IsUpdatedUndoUpdates = IsUpdatedUndoUpdates;
_urobject.Create();
// Add this to all groups if needed
Platform.Module.UndoRedo.Services.Packages.Grouping.GroupEntry(typeof(LocalPackage).FullName, _urobject.UndoRedoId);
// Check if we have too many - if yes delete the oldest entry
long count = LocalPackageUndoRedo.GetAllWithNoFilterCount(true) - undoRedoMaximumObjects;
if (count > 0)
{
LocalPackageUndoRedoCollection allOldUndoEntries = LocalPackageUndoRedo.GetAllWithNoFilterOppositeSortingPaged(true, 0, count);
for(int n = 0; n < allOldUndoEntries.Count; ++n)
allOldUndoEntries[n].Delete();
}
}
static public void Undo()
{
// Load the last undo, and execute it
LocalPackageUndoRedoCollection firstUndoEntries = LocalPackageUndoRedo.GetAllFilterByIsUndonePaged(false, 0, 1);
if (firstUndoEntries.Count < 1)
return;
LocalPackageUndoRedo _urobject = firstUndoEntries[0];
LocalPackage _object = new LocalPackage();
_object._PackageName = _urobject.PackageName;
_object._Id = _urobject.Id;
_object._VersionLabel = _urobject.VersionLabel;
_urobject.IsUndone = true;
_urobject.Update();
// Do the opposite action
if (_urobject.IsDeletedUndoCreates || _urobject.IsUpdatedUndoUpdates)
_object.Create(); // Create or update store
else if (_urobject.IsCreatedUndoDeletes)
_object.Delete(); // Delete
}
static public void Redo()
{
// Get the last already undone and load it
LocalPackageUndoRedoCollection firstEntryToRedoEntries = LocalPackageUndoRedo.GetAllFilterByIsUndoneOppositeOrderPaged(true, 0, 1);
if (firstEntryToRedoEntries.Count < 1)
return;
LocalPackageUndoRedo _urobject = firstEntryToRedoEntries[0];
LocalPackage _object = new LocalPackage();
_object._PackageName = _urobject.PackageName;
_object._Id = _urobject.Id;
_object._VersionLabel = _urobject.VersionLabel;
_urobject.IsUndone = false;
_urobject.Update();
// Do the opposite action
if (_urobject.IsDeletedUndoCreates)
_object.Delete(); // Delete again
else if (_urobject.IsCreatedUndoDeletes || _urobject.IsUpdatedUndoUpdates)
_object.Create(); // Create or update again
}
//*/ // Undo redo enabled
//*
static public void Undo()
{
throw new NotImplementedException("This feature is not implemented in this class.");
}
static public void Redo()
{
throw new NotImplementedException("This feature is not implemented in this class.");
}
//*/ // Undo redo disabled
#endregion
#endregion
#region IHierarchyData Members
IHierarchicalEnumerable IHierarchyData.GetChildren()
{
string selectedProperty = (__level < __childProperties.Length ? __childProperties[__level] : __childProperties[__childProperties.Length - 1]);
global::System.Reflection.PropertyInfo pi = this.GetType().GetProperty(selectedProperty);
if (pi == null)
throw new NullReferenceException("Property '" + selectedProperty + "' does not exist in type " + this.GetType().FullName);
IHierarchicalEnumerable dataSource = pi.GetValue(this, null) as IHierarchicalEnumerable;
foreach (IHierarchyData ihd in dataSource)
{
global::Platform.Runtime.Data.IModelHierachyData imhd = ihd as global::Platform.Runtime.Data.IModelHierachyData;
if (imhd != null)
{
imhd.Level = __level + 1;
imhd.ParentProperties = __parentProperties;
imhd.ChildProperties = __childProperties;
}
}
return dataSource;
}
IHierarchyData IHierarchyData.GetParent()
{
string selectedProperty = (__level < __parentProperties.Length ? __parentProperties[__level] : __parentProperties[__parentProperties.Length - 1]);
global::System.Reflection.PropertyInfo pi = this.GetType().GetProperty(selectedProperty);
if (pi == null)
throw new NullReferenceException("Property '" + selectedProperty + "' does not exist in type " + this.GetType().FullName);
IHierarchyData data = pi.GetValue(this, null) as IHierarchyData;
global::Platform.Runtime.Data.IModelHierachyData imhd = data as global::Platform.Runtime.Data.IModelHierachyData;
if (imhd != null)
{
imhd.Level = __level - 1;
imhd.ParentProperties = __parentProperties;
imhd.ChildProperties = __childProperties;
}
return data;
}
bool IHierarchyData.HasChildren
{
get
{
string selectedProperty = (__level < __childProperties.Length ? __childProperties[__level] : __childProperties[__childProperties.Length - 1]);
global::System.Reflection.PropertyInfo pi = this.GetType().GetProperty(selectedProperty);
if (pi == null)
throw new NullReferenceException("Property '" + selectedProperty + "' does not exist in type " + this.GetType().FullName);
IHierarchicalEnumerable value = pi.GetValue(this, null) as IHierarchicalEnumerable;
bool exists = false;
foreach(IHierarchyData ihd in value)
{
exists = true;
break;
}
return exists;
}
}
object IHierarchyData.Item
{
get { return this; }
}
string IHierarchyData.Path
{
get { return ""; }
}
string IHierarchyData.Type
{
get { return this.GetType().FullName; }
}
#endregion
#region Platform.Runtime.Data.IHierarchyData explicit Members
[NonSerialized]
string[] __childProperties = null;
[NonSerialized]
string[] __parentProperties = null;
[NonSerialized]
int __level = -1;
string[] Platform.Runtime.Data.IModelHierachyData.ChildProperties
{
get
{
return __childProperties;
}
set
{
__childProperties = value;
}
}
string[] Platform.Runtime.Data.IModelHierachyData.ParentProperties
{
get
{
return __parentProperties;
}
set
{
__parentProperties = value;
}
}
int Platform.Runtime.Data.IModelHierachyData.Level
{
get
{
return __level;
}
set
{
__level = value;
}
}
#endregion
}
/// <summary>
/// Defines the contract for the LocalPackageCollection class
/// </summary>
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[Guid("6676072b-deac-6673-0edf-ef663d75bf8a")]
public interface ILocalPackageCollection : IEnumerable<LocalPackage>
{
int IndexOf(LocalPackage item);
void Insert(int index, LocalPackage item);
void RemoveAt(int index);
LocalPackage this[int index] { get; set; }
void Add(LocalPackage item);
void Clear();
bool Contains(LocalPackage item);
void CopyTo(LocalPackage[] array, int arrayIndex);
int Count { get; }
bool IsReadOnly { get; }
bool Remove(LocalPackage item);
}
/// <summary>
/// Provides the implementation of the class that represents a list of Services.Packages.LocalPackage
/// </summary>
[ClassInterface(ClassInterfaceType.None)]
[Guid("396175c9-26df-781a-d166-98c689a6598a")]
[DataContract]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
[Serializable]
public class LocalPackageCollection : ILocalPackageCollection, IList<LocalPackage>, IHierarchicalEnumerable
{
List<LocalPackage> _list = new List<LocalPackage>();
public static implicit operator List<LocalPackage>(LocalPackageCollection collection)
{
return collection._list;
}
#region IList<LocalPackage> Members
public int IndexOf(LocalPackage item)
{
return _list.IndexOf(item);
}
public void Insert(int index, LocalPackage item)
{
_list.Insert(index, item);
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
public LocalPackage this[int index]
{
get
{
return _list[index];
}
set
{
_list[index] = value;
}
}
#endregion
#region ICollection<LocalPackage> Members
public void Add(LocalPackage item)
{
_list.Add(item);
}
public void Clear()
{
_list.Clear();
}
public bool Contains(LocalPackage item)
{
return _list.Contains(item);
}
public void CopyTo(LocalPackage[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _list.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(LocalPackage item)
{
return _list.Remove(item);
}
#endregion
#region IEnumerable<LocalPackage> Members
public IEnumerator<LocalPackage> GetEnumerator()
{
return _list.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)_list).GetEnumerator();
}
#endregion
#region IHierarchicalEnumerable Members
public IHierarchyData GetHierarchyData(object enumeratedItem)
{
return enumeratedItem as IHierarchyData;
}
#endregion
}
namespace Web
{
/// <summary>
/// The WebService service provider that allows to create web services
/// that share Services.Packages.LocalPackage objects.
/// </summary>
/// <example>
/// You can use that in the header of an asmx file like this:
/// <%@ WebService Language="C#" Class="Services.Packages.Web.LocalPackageWebService" %>
/// </example>
[WebService(Namespace="http://services.msd.com")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
[ComVisible(false)]
sealed public class LocalPackageWebService : WebService, ILocalPackageService
{
/// <summary>
/// Gets the Uri if the service. Setting property is not supported.
/// </summary>
public string Uri
{
get { return "http://services.msd.com"; }
set { throw new NotSupportedException(); }
}
[WebMethod]
public bool Exists(LocalPackage _LocalPackage)
{
return _LocalPackage.Exists;
}
[WebMethod]
public LocalPackage Read(System.String __PackageName)
{
return new LocalPackage(__PackageName);
}
[WebMethod]
public LocalPackage Reload(LocalPackage _LocalPackage)
{
_LocalPackage.Reload();
return _LocalPackage;
}
[WebMethod]
public LocalPackage Create(System.String __PackageName)
{
return LocalPackage.CreateLocalPackage(__PackageName);
}
[WebMethod]
public void Delete(System.String __PackageName)
{
LocalPackage.DeleteLocalPackage(__PackageName);
}
[WebMethod]
public void UpdateObject(LocalPackage _LocalPackage)
{
_LocalPackage.Update();
}
[WebMethod]
public void CreateObject(LocalPackage _LocalPackage)
{
_LocalPackage.Create();
}
[WebMethod]
public void DeleteObject(LocalPackage _LocalPackage)
{
_LocalPackage.Delete();
}
[WebMethod]
public void Undo()
{
LocalPackage.Undo();
}
[WebMethod]
public void Redo()
{
LocalPackage.Redo();
}
[WebMethod]
public LocalPackageCollection SearchByPackageName(System.String PackageName )
{
return LocalPackage.SearchByPackageName(PackageName );
}
[WebMethod]
public LocalPackageCollection SearchByPackageNamePaged(System.String PackageName , long PagingStart, long PagingCount)
{
return LocalPackage.SearchByPackageNamePaged(PackageName , PagingStart, PagingCount);
}
[WebMethod]
public long SearchByPackageNameCount(System.String PackageName )
{
return LocalPackage.SearchByPackageNameCount(PackageName );
}
}
/// <summary>
/// The WebService client service
/// </summary>
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalPackageWebServiceSoap", Namespace="http://services.msd.com")]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(MarshalByRefObject))]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("2ad9ea17-a5b7-1281-c015-5547a6aab375")]
sealed public class LocalPackageWebServiceClient : System.Web.Services.Protocols.SoapHttpClientProtocol, ILocalPackageService
{
static string globalUrl;
/// <summary>
/// By setting this value, all the subsequent clients that using the default
/// constructor will point to the service that this url points to.
/// </summary>
static public string GlobalUrl
{
get { return globalUrl; }
set { globalUrl = value; }
}
/// <summary>
/// Initializes a web service client using the url as the service endpoint.
/// </summary>
/// <param name="url">The service url that the object will point to</param>
public LocalPackageWebServiceClient(string url)
{
this.Url = url;
}
/// <summary>
/// Initializes a web service client without a specific service url.
/// If the GlobalUrl value is set, is been used as the Url.
/// </summary>
public LocalPackageWebServiceClient()
{
if (!String.IsNullOrEmpty(globalUrl))
this.Url = globalUrl;
}
/// <summary>
/// Allows the service to set the Uri for COM compatibility. Is the same with Url property.
/// </summary>
public string Uri
{
get { return this.Url; }
set { this.Url = value; }
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Exists", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public bool Exists(LocalPackage _LocalPackage)
{
object[] results = this.Invoke("Exists", new object[] {_LocalPackage});
return ((bool)(results[0]));
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Read", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public LocalPackage Read(System.String __PackageName)
{
object[] results = this.Invoke("Read", new object[] {__PackageName});
return ((LocalPackage)(results[0]));
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Reload", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public LocalPackage Reload(LocalPackage _LocalPackage)
{
object[] results = this.Invoke("Reload", new object[] {_LocalPackage});
return ((LocalPackage)(results[0]));
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Create", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public LocalPackage Create(System.String __PackageName)
{
object[] results = this.Invoke("Create", new object[] {__PackageName});
return ((LocalPackage)(results[0]));
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Delete", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void Delete(System.String __PackageName)
{
this.Invoke("Delete", new object[] {__PackageName});
return;
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/UpdateObject", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void UpdateObject(LocalPackage _LocalPackage)
{
this.Invoke("UpdateObject", new object[] {_LocalPackage});
return;
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/CreateObject", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void CreateObject(LocalPackage _LocalPackage)
{
this.Invoke("CreateObject", new object[] {_LocalPackage});
return;
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/DeleteObject", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void DeleteObject(LocalPackage _LocalPackage)
{
this.Invoke("DeleteObject", new object[] {_LocalPackage});
return;
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Undo", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void Undo()
{
this.Invoke("Undo", new object[] {});
return;
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Redo", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void Redo()
{
this.Invoke("Redo", new object[] {});
return;
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/SearchByPackageName", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public LocalPackageCollection SearchByPackageName(System.String PackageName ) {
object[] results = this.Invoke("SearchByPackageName", new object[] {PackageName});
return ((LocalPackageCollection)(results[0]));
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/SearchByPackageNamePaged", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public LocalPackageCollection SearchByPackageNamePaged(System.String PackageName , long PagingStart, long PagingCount) {
object[] results = this.Invoke("SearchByPackageNamePaged", new object[] {PackageName,PagingStart,PagingCount});
return ((LocalPackageCollection)(results[0]));
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/SearchByPackageNameCount", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public long SearchByPackageNameCount(System.String PackageName ) {
object[] results = this.Invoke("SearchByPackageNameCount", new object[] {PackageName});
return ((long)(results[0]));
}
}
} // namespace Web
} // namespace Services.Packages
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml.Serialization;
using System.Text;
using System.Xml.Linq;
// Verify that jit test project files specify DebugType properly.
// Returns error status (-1) if any project files are in error.
internal class ScanProjectFiles
{
private static bool s_showNeedsFixOnly = true;
private static bool s_tryAndFix = true;
private static int s_projCount = 0;
private static int s_needsFixCount = 0;
private static int s_deferredFixCount = 0;
private static int s_fixedCount = 0;
private static int Main(string[] args)
{
// If invoked w/o args, locate jit test project dir from
// CORE_ROOT, and scan only.
//
// If invoked w args, locate and try to fix project files.
string projectRoot = null;
if (args.Length == 0)
{
s_tryAndFix = false;
// CORE_ROOT should be something like
// c:\repos\coreclr\bin\tests\Windows_NT.x64.Checked\Tests\Core_Root
// or
// D:\j\workspace\x64_release_w---0575cb46\bin\tests\Windows_NT.x64.Release\Tests\Core_Root
// We want
// c:\repos\coreclr\tests\src\JIT
string coreRoot = System.Environment.GetEnvironmentVariable("CORE_ROOT");
if (coreRoot == null)
{
Console.WriteLine("CORE_ROOT must be set");
return -1;
}
int binIndex = coreRoot.IndexOf("bin");
if (binIndex < 0)
{
Console.WriteLine("No bin directory found in CORE_ROOT path `{0}`," +
" so no checking will be performed.", coreRoot);
return 100;
}
string repoRoot = coreRoot.Substring(0, binIndex);
projectRoot = Path.Combine(repoRoot, "tests", "src", "JIT");
}
else if (args.Length != 1)
{
Console.WriteLine("Usage: CheckProjects [<dir>]");
Console.WriteLine("If optional <dir> is specified,"
+ " all project files under <dir> will be scanned and updates will be attempted.");
return -1;
}
else
{
projectRoot = args[0];
}
Console.WriteLine("Scanning{0}projects under {1}",
s_tryAndFix ? " and attempting to update " : " ", projectRoot);
if (!Directory.Exists(projectRoot))
{
Console.WriteLine("Project directory does not exist, so no checking will be performed.");
return 100;
}
DirectoryInfo projectRootDir = new DirectoryInfo(projectRoot);
foreach (FileInfo f in projectRootDir.GetFiles("*.*proj", SearchOption.AllDirectories))
{
if (!f.FullName.Contains("JIT\\config") && !f.FullName.Contains("JIT/config"))
{
ParseAndUpdateProj(f.FullName, s_tryAndFix);
}
}
Console.WriteLine("{0} projects, {1} needed fixes, {2} fixes deferred, {3} were fixed",
s_projCount, s_needsFixCount, s_deferredFixCount, s_fixedCount);
// Return error status if there are unfixed projects
return (s_needsFixCount == 0 ? 100 : -1);
}
// Load up a project file and look for key attributes.
// Optionally try and update. Return true if modified.
private static bool ParseAndUpdateProj(string projFile, bool tryUpdate)
{
s_projCount++;
// Guess at expected settings by looking for suffixes...
string projFileBase = Path.GetFileNameWithoutExtension(projFile);
bool isDebugTypeTest = projFileBase.EndsWith("_d") || projFileBase.EndsWith("_do") || projFileBase.EndsWith("_dbg");
bool isRelTypeTest = projFileBase.EndsWith("_r") || projFileBase.EndsWith("_ro") || projFileBase.EndsWith("_rel");
bool isNotOptTypeTest = projFileBase.EndsWith("_r") || projFileBase.EndsWith("_d");
bool isOptTypeTest = projFileBase.EndsWith("_ro") || projFileBase.EndsWith("_do") || projFileBase.EndsWith("_opt");
bool isSpecificTest = isDebugTypeTest || isRelTypeTest;
bool updated = false;
try
{
XElement root = XElement.Load(projFile);
string nn = "{" + root.Name.NamespaceName + "}";
IEnumerable<XElement> props = from el in root.Descendants(nn + "PropertyGroup") select el;
bool hasReleaseCondition = false;
bool hasDebugCondition = false;
string oddness = null;
string debugVal = null;
bool needsFix = false;
XElement bestPropertyGroupNode = null;
XElement lastPropertyGroupNode = null;
List<XElement> debugTypePropertyGroupNodes = new List<XElement>();
foreach (XElement prop in props)
{
lastPropertyGroupNode = prop;
XAttribute condition = prop.Attribute("Condition");
bool isReleaseCondition = false;
bool isDebugCondition = false;
if (condition != null)
{
isReleaseCondition = condition.Value.Contains("Release");
isDebugCondition = condition.Value.Contains("Debug");
if (isReleaseCondition || isDebugCondition)
{
bestPropertyGroupNode = prop;
}
}
XElement debugType = prop.Element(nn + "DebugType");
if (debugType != null)
{
debugTypePropertyGroupNodes.Add(prop);
// If <DebugType> appears multiple times, all should agree.
string newDebugVal = debugType.Value;
if (newDebugVal.Equals(""))
{
newDebugVal = "blank";
}
if (debugVal != null)
{
if (!debugType.Value.Equals(newDebugVal))
{
oddness = "ConflictingDebugType";
}
}
debugVal = newDebugVal;
if (condition != null)
{
if (isReleaseCondition == isDebugCondition)
{
oddness = "RelDebugDisagree";
}
hasReleaseCondition |= isReleaseCondition;
hasDebugCondition |= isDebugCondition;
}
else
{
if (hasReleaseCondition || hasDebugCondition)
{
oddness = "CondAndUncond";
}
}
}
}
if (oddness == null)
{
if (hasReleaseCondition && !hasDebugCondition)
{
oddness = "RelButNotDbg";
}
else if (!hasReleaseCondition && hasDebugCondition)
{
oddness = "DbgButNotRel";
}
}
bool hasDebugType = debugTypePropertyGroupNodes.Count > 0;
// Analyze suffix convention mismatches
string suffixNote = "SuffixNone";
if (isSpecificTest)
{
if (!hasDebugType || oddness != null || hasReleaseCondition || hasDebugCondition)
{
suffixNote = "SuffixProblem";
needsFix = true;
}
else
{
if (isRelTypeTest)
{
if (debugVal.Equals("pdbonly", StringComparison.OrdinalIgnoreCase)
|| debugVal.Equals("none", StringComparison.OrdinalIgnoreCase)
|| debugVal.Equals("blank", StringComparison.OrdinalIgnoreCase))
{
suffixNote = "SuffixRelOk";
}
else
{
suffixNote = "SuffixRelTestNot";
needsFix = true;
}
}
else if (isDebugTypeTest)
{
if (debugVal.Equals("full", StringComparison.OrdinalIgnoreCase))
{
suffixNote = "SuffixDbgOk";
}
else
{
suffixNote = "SuffixDbgTestNot";
needsFix = true;
}
}
}
}
if (!hasDebugType)
{
needsFix = true;
}
if (oddness != null)
{
needsFix = true;
}
// If there is no debug type at all, we generally want to
// turn this into a release/optimize test. However for the
// CodeGenBringUpTests we want to introduce the full spectrum
// of flavors. We'll skip them for now.
bool isBringUp = projFile.Contains("CodeGenBringUpTests");
if (needsFix)
{
if (!isBringUp)
{
s_needsFixCount++;
}
else
{
s_deferredFixCount++;
}
}
if (needsFix || !s_showNeedsFixOnly)
{
if (!hasDebugType)
{
Console.WriteLine("{0} DebugType-n/a-{1}", projFile, suffixNote);
}
else if (oddness != null)
{
Console.WriteLine("{0} DebugType-Odd-{1}-{2}", projFile, oddness, suffixNote);
}
else if (hasReleaseCondition || hasDebugCondition)
{
Console.WriteLine("{0} DebugType-{1}-Conditional-{2}", projFile, debugVal, suffixNote);
}
else
{
Console.WriteLine("{0} DebugType-{1}-Unconditional-{2}", projFile, debugVal, suffixNote);
}
}
// If a fix is needed, give it a shot!
if (!needsFix || !tryUpdate)
{
return false;
}
// Add new elements just after the conditional rel/debug
// property group entries, if possible.
if (bestPropertyGroupNode == null)
{
bestPropertyGroupNode = lastPropertyGroupNode;
}
if (bestPropertyGroupNode == null)
{
Console.WriteLine(".... no prop group, can't fix");
return false;
}
if (isBringUp)
{
Console.WriteLine("Bring up test, deferring fix");
return false;
}
if (debugTypePropertyGroupNodes.Count == 0)
{
// Fix projects that don't mention debug type at all.
Console.WriteLine(".... no DebugType, attempting fix ....");
XElement newPropGroup = new XElement(nn + "PropertyGroup",
new XElement(nn + "DebugType", isDebugTypeTest ? "Full" : "PdbOnly"),
new XElement(nn + "Optimize", isNotOptTypeTest ? "False" : "True"));
bestPropertyGroupNode.AddAfterSelf(newPropGroup);
// Write out updated project file
using (StreamWriter outFile = File.CreateText(projFile))
{
root.Save(outFile);
updated = true;
s_fixedCount++;
}
}
else if (debugTypePropertyGroupNodes.Count == 1)
{
// Fix projects with just one mention of debug type.
Console.WriteLine(".... one DebugType, attempting fix ....");
XElement prop = debugTypePropertyGroupNodes.First();
XAttribute condition = prop.Attribute("Condition");
// If there is no condition then this is likely a suffix mismatch
if ((condition == null) && suffixNote.Equals("SuffixDbgTestNot"))
{
Console.WriteLine("Unconditional debug test w/ suffix issue");
// Do case analysis of suffix and debugType/Opt, then update.
XElement debugType = prop.Element(nn + "DebugType");
XElement optimize = prop.Element(nn + "Optimize");
// We know DebugType is set, but Optimize may not be.
if (optimize == null)
{
optimize = new XElement(nn + "Optimize");
prop.Add(optimize);
}
bool modified = false;
if (isDebugTypeTest && !isOptTypeTest)
{
// "d" suffix --
debugType.Value = "full";
optimize.Value = "False";
modified = true;
}
else if (isDebugTypeTest && isOptTypeTest)
{
// "do" suffix --
debugType.Value = "full";
optimize.Value = "True";
modified = true;
}
if (modified)
{
// Write out updated project file
using (StreamWriter outFile = File.CreateText(projFile))
{
root.Save(outFile);
updated = true;
s_fixedCount++;
}
}
}
else
{
XElement newPropGroup = new XElement(prop);
newPropGroup.RemoveAttributes();
prop.RemoveNodes();
bestPropertyGroupNode.AddAfterSelf(newPropGroup);
// Write out updated project file
using (StreamWriter outFile = File.CreateText(projFile))
{
root.Save(outFile);
updated = true;
s_fixedCount++;
}
}
}
else
{
// Multiple property groups specifying DebugType. Remove any that are conditional.
Console.WriteLine(".... multiple DebugTypes, attempting fix ....");
bool modified = false;
foreach (XElement prop in debugTypePropertyGroupNodes)
{
XAttribute condition = prop.Attribute("Condition");
if (condition != null)
{
prop.RemoveNodes();
modified = true;
}
}
if (modified)
{
// Write out updated project file
using (StreamWriter outFile = File.CreateText(projFile))
{
root.Save(outFile);
updated = true;
s_fixedCount++;
}
}
}
}
catch (Exception e)
{
Console.WriteLine("{0} DebugType-fail {1}", projFile, e.Message);
}
return updated;
}
}
| |
namespace AutoMapper
{
using System;
using System.ComponentModel;
using System.Linq.Expressions;
/// <summary>
/// Mapping configuration options for non-generic maps
/// </summary>
public interface IMappingExpression
{
/// <summary>
/// Customize configuration for individual constructor parameter
/// </summary>
/// <param name="ctorParamName">Constructor parameter name</param>
/// <param name="paramOptions">Options</param>
/// <returns>Itself</returns>
IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions);
/// <summary>
/// Create a type mapping from the destination to the source type, using the destination members as validation.
/// </summary>
/// <returns>Itself</returns>
IMappingExpression ReverseMap();
/// <summary>
/// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types.
/// The returned source object will be mapped instead of what was supplied in the original source object.
/// </summary>
/// <param name="substituteFunc">Substitution function</param>
/// <returns>New source object to map.</returns>
IMappingExpression Substitute(Func<object, object> substituteFunc);
/// <summary>
/// Construct the destination object using the service locator
/// </summary>
/// <returns>Itself</returns>
IMappingExpression ConstructUsingServiceLocator();
/// <summary>
/// For self-referential types, limit recurse depth
/// </summary>
/// <param name="depth">Number of levels to limit to</param>
/// <returns>Itself</returns>
IMappingExpression MaxDepth(int depth);
/// <summary>
/// Supply a custom instantiation expression for the destination type for LINQ projection
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression ConstructProjectionUsing(LambdaExpression ctor);
/// <summary>
/// Supply a custom instantiation function for the destination type, based on the entire resolution context
/// </summary>
/// <param name="ctor">Callback to create the destination type given the current resolution context</param>
/// <returns>Itself</returns>
IMappingExpression ConstructUsing(Func<ResolutionContext, object> ctor);
/// <summary>
/// Supply a custom instantiation function for the destination type
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression ConstructUsing(Func<object, object> ctor);
/// <summary>
/// Skip member mapping and use a custom expression during LINQ projection
/// </summary>
/// <param name="projectionExpression">Projection expression</param>
void ProjectUsing(Expression<Func<object, object>> projectionExpression);
/// <summary>
/// Customize configuration for all members
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions);
/// <summary>
/// Customize configuration for an individual source member
/// </summary>
/// <param name="sourceMemberName">Source member name</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping
/// </summary>
/// <typeparam name="TTypeConverter">Type converter type</typeparam>
void ConvertUsing<TTypeConverter>();
/// <summary>
/// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping
/// Use this method if you need to specify the converter type at runtime
/// </summary>
/// <param name="typeConverterType">Type converter type</param>
void ConvertUsing(Type typeConverterType);
/// <summary>
/// Override the destination type mapping for looking up configuration and instantiation
/// </summary>
/// <param name="typeOverride"></param>
void As(Type typeOverride);
/// <summary>
/// Customize individual members
/// </summary>
/// <param name="name">Name of the member</param>
/// <param name="memberOptions">Callback for configuring member</param>
/// <returns>Itself</returns>
IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions);
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <param name="derivedSourceType">Derived source type</param>
/// <param name="derivedDestinationType">Derived destination type</param>
/// <returns>Itself</returns>
IMappingExpression Include(Type derivedSourceType, Type derivedDestinationType);
/// <summary>
/// Ignores all destination properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter();
/// <summary>
/// When using ReverseMap, ignores all source properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: destination properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
/// <summary>
/// Include the base type map's configuration in this map
/// </summary>
/// <param name="sourceBase">Base source type</param>
/// <param name="destinationBase">Base destination type</param>
/// <returns></returns>
IMappingExpression IncludeBase(Type sourceBase, Type destinationBase);
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression BeforeMap(Action<object, object> beforeFunction);
/// <summary>
/// Execute a custom mapping action before member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression BeforeMap<TMappingAction>()
where TMappingAction : IMappingAction<object, object>;
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression AfterMap(Action<object, object> afterFunction);
/// <summary>
/// Execute a custom mapping action after member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression AfterMap<TMappingAction>()
where TMappingAction : IMappingAction<object, object>;
}
/// <summary>
/// Mapping configuration options
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
public interface IMappingExpression<TSource, TDestination>
{
/// <summary>
/// Customize configuration for individual member
/// </summary>
/// <param name="destinationMember">Expression to the top-level destination member. This must be a member on the <typeparamref name="TDestination"/>TDestination</param> type
/// <param name="memberOptions">Callback for member options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForMember(Expression<Func<TDestination, object>> destinationMember,
Action<IMemberConfigurationExpression<TSource>> memberOptions);
/// <summary>
/// Customize configuration for individual member. Used when the name isn't known at compile-time
/// </summary>
/// <param name="name">Destination member name</param>
/// <param name="memberOptions">Callback for member options</param>
/// <returns></returns>
IMappingExpression<TSource, TDestination> ForMember(string name,
Action<IMemberConfigurationExpression<TSource>> memberOptions);
/// <summary>
/// Customize configuration for all members
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllMembers(Action<IMemberConfigurationExpression<TSource>> memberOptions);
/// <summary>
/// Ignores all <typeparamref name="TDestination"/> properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter();
/// <summary>
/// When using ReverseMap, ignores all <typeparamref name="TSource"/> properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: <typeparamref name="TDestination"/> properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <typeparam name="TOtherSource">Derived source type</typeparam>
/// <typeparam name="TOtherDestination">Derived destination type</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
where TOtherSource : TSource
where TOtherDestination : TDestination;
/// <summary>
/// Include the base type map's configuration in this map
/// </summary>
/// <typeparam name="TSourceBase">Base source type</typeparam>
/// <typeparam name="TDestinationBase">Base destination type</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>();
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <param name="derivedSourceType">Derived source type</param>
/// <param name="derivedDestinationType">Derived destination type</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> Include(Type derivedSourceType, Type derivedDestinationType);
/// <summary>
/// Skip member mapping and use a custom expression during LINQ projection
/// </summary>
/// <param name="projectionExpression">Projection expression</param>
void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <param name="mappingFunction">Callback to convert from source type to destination type</param>
void ConvertUsing(Func<TSource, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <param name="mappingFunction">Callback to convert from source type to destination type</param>
void ConvertUsing(Func<ResolutionContext, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <param name="mappingFunction">Callback to convert from source type to destination type</param>
void ConvertUsing(Func<ResolutionContext, TSource, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom type converter instance to convert to the destination type
/// </summary>
/// <param name="converter">Type converter instance</param>
void ConvertUsing(ITypeConverter<TSource, TDestination> converter);
/// <summary>
/// Skip member mapping and use a custom type converter instance to convert to the destination type
/// </summary>
/// <typeparam name="TTypeConverter">Type converter type</typeparam>
void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>;
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction);
/// <summary>
/// Execute a custom mapping action before member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>()
where TMappingAction : IMappingAction<TSource, TDestination>;
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction);
/// <summary>
/// Execute a custom mapping action after member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>()
where TMappingAction : IMappingAction<TSource, TDestination>;
/// <summary>
/// Supply a custom instantiation function for the destination type
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor);
/// <summary>
/// Supply a custom instantiation expression for the destination type for LINQ projection
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor);
/// <summary>
/// Supply a custom instantiation function for the destination type, based on the entire resolution context
/// </summary>
/// <param name="ctor">Callback to create the destination type given the current resolution context</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor);
/// <summary>
/// Override the destination type mapping for looking up configuration and instantiation
/// </summary>
/// <typeparam name="T">Destination type to use</typeparam>
void As<T>();
/// <summary>
/// For self-referential types, limit recurse depth
/// </summary>
/// <param name="depth">Number of levels to limit to</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> MaxDepth(int depth);
/// <summary>
/// Construct the destination object using the service locator
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator();
/// <summary>
/// Create a type mapping from the destination to the source type, using the <typeparamref name="TDestination"/> members as validation
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TDestination, TSource> ReverseMap();
/// <summary>
/// Customize configuration for an individual source member
/// </summary>
/// <param name="sourceMember">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember,
Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Customize configuration for an individual source member. Member name not known until runtime
/// </summary>
/// <param name="sourceMemberName">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName,
Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types.
/// The returned source object will be mapped instead of what was supplied in the original source object.
/// </summary>
/// <param name="substituteFunc">Substitution function</param>
/// <returns>New source object to map.</returns>
IMappingExpression<TSource, TDestination> Substitute(Func<TSource, object> substituteFunc);
/// <summary>
/// Customize configuration for individual constructor parameter
/// </summary>
/// <param name="ctorParamName">Constructor parameter name</param>
/// <param name="paramOptions">Options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace MVC_APP.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using System.Transactions.Configuration;
namespace System.Transactions
{
/// <summary>
/// Summary description for TransactionException.
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class TransactionException : SystemException
{
internal static bool IncludeDistributedTxId(Guid distributedTxId)
{
return (distributedTxId != Guid.Empty && AppSettings.IncludeDistributedTxIdInExceptionMessage);
}
internal static TransactionException Create(string message, Exception innerException)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionException(message, innerException);
}
internal static TransactionException Create(TraceSourceType traceSource, string message, Exception innerException)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionException(message, innerException);
}
internal static TransactionException CreateTransactionStateException(Exception innerException)
{
return Create(SR.TransactionStateException, innerException);
}
internal static Exception CreateEnlistmentStateException(Exception innerException, Guid distributedTxId)
{
string messagewithTxId = SR.EnlistmentStateException;
if (IncludeDistributedTxId(distributedTxId))
messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TransactionExceptionType.InvalidOperationException, messagewithTxId, innerException == null ? string.Empty : innerException.ToString());
}
return new InvalidOperationException(messagewithTxId, innerException);
}
internal static Exception CreateInvalidOperationException(TraceSourceType traceSource, string message, Exception innerException)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(traceSource, TransactionExceptionType.InvalidOperationException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new InvalidOperationException(message, innerException);
}
/// <summary>
///
/// </summary>
public TransactionException()
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public TransactionException(string message) : base(message)
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TransactionException(string message, Exception innerException) : base(message, innerException)
{
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected TransactionException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
internal static TransactionException Create(string message, Guid distributedTxId)
{
if (IncludeDistributedTxId(distributedTxId))
{
return new TransactionException(SR.Format(SR.DistributedTxIDInTransactionException, message, distributedTxId));
}
return new TransactionException(message);
}
internal static TransactionException Create(string message, Exception innerException, Guid distributedTxId)
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return Create(messagewithTxId, innerException);
}
internal static TransactionException Create(TraceSourceType traceSource, string message, Exception innerException, Guid distributedTxId)
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return Create(traceSource, messagewithTxId, innerException);
}
internal static TransactionException Create(TraceSourceType traceSource, string message, Guid distributedTxId)
{
if (IncludeDistributedTxId(distributedTxId))
{
return new TransactionException(SR.Format(SR.DistributedTxIDInTransactionException, message, distributedTxId));
}
return new TransactionException(message);
}
internal static TransactionException CreateTransactionStateException(Exception innerException, Guid distributedTxId)
{
return Create(SR.TransactionStateException, innerException, distributedTxId);
}
internal static Exception CreateTransactionCompletedException(Guid distributedTxId)
{
string messagewithTxId = SR.TransactionAlreadyCompleted;
if (IncludeDistributedTxId(distributedTxId))
messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TransactionExceptionType.InvalidOperationException, messagewithTxId, string.Empty);
}
return new InvalidOperationException(messagewithTxId);
}
internal static Exception CreateInvalidOperationException(TraceSourceType traceSource, string message, Exception innerException, Guid distributedTxId)
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return CreateInvalidOperationException(traceSource, messagewithTxId, innerException);
}
}
/// <summary>
/// Summary description for TransactionAbortedException.
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class TransactionAbortedException : TransactionException
{
internal static new TransactionAbortedException Create(string message, Exception innerException, Guid distributedTxId)
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return TransactionAbortedException.Create(messagewithTxId, innerException);
}
internal static new TransactionAbortedException Create(string message, Exception innerException)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionAbortedException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionAbortedException(message, innerException);
}
/// <summary>
///
/// </summary>
public TransactionAbortedException() : base(SR.TransactionAborted)
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public TransactionAbortedException(string message) : base(message)
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TransactionAbortedException(string message, Exception innerException) : base(message, innerException)
{
}
/// <summary>
///
/// </summary>
/// <param name="innerException"></param>
internal TransactionAbortedException(Exception innerException) : base(SR.TransactionAborted, innerException)
{
}
internal TransactionAbortedException(Exception innerException, Guid distributedTxId) :
base(IncludeDistributedTxId(distributedTxId) ?
SR.Format(SR.DistributedTxIDInTransactionException, SR.TransactionAborted, distributedTxId)
: SR.TransactionAborted, innerException)
{
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected TransactionAbortedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
/// <summary>
/// Summary description for TransactionInDoubtException.
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class TransactionInDoubtException : TransactionException
{
internal static new TransactionInDoubtException Create(TraceSourceType traceSource, string message, Exception innerException, Guid distributedTxId)
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return TransactionInDoubtException.Create(traceSource, messagewithTxId, innerException);
}
internal static new TransactionInDoubtException Create(TraceSourceType traceSource, string message, Exception innerException)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(traceSource, TransactionExceptionType.TransactionInDoubtException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionInDoubtException(message, innerException);
}
/// <summary>
///
/// </summary>
public TransactionInDoubtException() : base(SR.TransactionIndoubt)
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public TransactionInDoubtException(string message) : base(message)
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TransactionInDoubtException(string message, Exception innerException) : base(message, innerException)
{
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected TransactionInDoubtException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
/// <summary>
/// Summary description for TransactionManagerCommunicationException.
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class TransactionManagerCommunicationException : TransactionException
{
internal static new TransactionManagerCommunicationException Create(string message, Exception innerException)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionManagerCommunicationException, message, innerException == null ? string.Empty : innerException.ToString());
}
return new TransactionManagerCommunicationException(message, innerException);
}
internal static TransactionManagerCommunicationException Create(Exception innerException)
{
return Create(SR.TransactionManagerCommunicationException, innerException);
}
/// <summary>
///
/// </summary>
public TransactionManagerCommunicationException() : base(SR.TransactionManagerCommunicationException)
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public TransactionManagerCommunicationException(string message) : base(message)
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TransactionManagerCommunicationException(
string message,
Exception innerException
) : base(message, innerException)
{
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected TransactionManagerCommunicationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class TransactionPromotionException : TransactionException
{
/// <summary>
///
/// </summary>
public TransactionPromotionException() : this(SR.PromotionFailed)
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public TransactionPromotionException(string message) : base(message)
{
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TransactionPromotionException(string message, Exception innerException) : base(message, innerException)
{
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected TransactionPromotionException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
| |
using UnityEngine;
using System;
namespace UnityStandardAssets.CinematicEffects
{
//Improvement ideas:
// Use rgba8 buffer in ldr / in some pass in hdr (in correlation to previous point and remapping coc from -1/0/1 to 0/0.5/1)
// Use temporal stabilisation
// Add a mode to do bokeh texture in quarter res as well
// Support different near and far blur for the bokeh texture
// Try distance field for the bokeh texture
// Try to separate the output of the blur pass to two rendertarget near+far, see the gain in quality vs loss in performance
// Try swirl effect on the samples of the circle blur
//References :
// This DOF implementation use ideas from public sources, a big thank to them :
// http://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare
// http://www.crytek.com/download/Sousa_Graphics_Gems_CryENGINE3.pdf
// http://graphics.cs.williams.edu/papers/MedianShaderX6/
// http://http.developer.nvidia.com/GPUGems/gpugems_ch24.html
// http://vec3.ca/bicubic-filtering-in-fewer-taps/
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Cinematic/Depth Of Field")]
[RequireComponent(typeof(Camera))]
public class DepthOfField : MonoBehaviour
{
private const float kMaxBlur = 40.0f;
#region Render passes
private enum Passes
{
BlurAlphaWeighted,
BoxBlur,
DilateFgCocFromColor,
DilateFgCoc,
CaptureCocExplicit,
VisualizeCocExplicit,
CocPrefilter,
CircleBlur,
CircleBlurWithDilatedFg,
CircleBlurLowQuality,
CircleBlowLowQualityWithDilatedFg,
MergeExplicit,
ShapeLowQuality,
ShapeLowQualityDilateFg,
ShapeLowQualityMerge,
ShapeLowQualityMergeDilateFg,
ShapeMediumQuality,
ShapeMediumQualityDilateFg,
ShapeMediumQualityMerge,
ShapeMediumQualityMergeDilateFg,
ShapeHighQuality,
ShapeHighQualityDilateFg,
ShapeHighQualityMerge,
ShapeHighQualityMergeDilateFg
}
private enum MedianPasses
{
Median3,
Median3X3
}
private enum BokehTexturesPasses
{
Apply,
Collect
}
#endregion
public enum TweakMode
{
Range,
Explicit
}
public enum ApertureShape
{
Circular,
Hexagonal,
Octogonal
}
public enum QualityPreset
{
Low,
Medium,
High
}
public enum FilterQuality
{
None,
Normal,
High
}
#region Settings
[Serializable]
public struct GlobalSettings
{
[Tooltip("Allows to view where the blur will be applied. Yellow for near blur, blue for far blur.")]
public bool visualizeFocus;
[Tooltip("Setup mode. Use \"Advanced\" if you need more control on blur settings and/or want to use a bokeh texture. \"Explicit\" is the same as \"Advanced\" but makes use of \"Near Plane\" and \"Far Plane\" values instead of \"F-Stop\".")]
public TweakMode tweakMode;
[Tooltip("Quality presets. Use \"Custom\" for more advanced settings.")]
public QualityPreset filteringQuality;
[Tooltip("\"Circular\" is the fastest, followed by \"Hexagonal\" and \"Octogonal\".")]
public ApertureShape apertureShape;
[Range(0f, 179f), Tooltip("Rotates the aperture when working with \"Hexagonal\" and \"Ortogonal\".")]
public float apertureOrientation;
public static GlobalSettings defaultSettings
{
get
{
return new GlobalSettings
{
visualizeFocus = false,
tweakMode = TweakMode.Range,
filteringQuality = QualityPreset.High,
apertureShape = ApertureShape.Circular,
apertureOrientation = 0f
};
}
}
}
[Serializable]
public struct QualitySettings
{
[Tooltip("Enable this to get smooth bokeh.")]
public bool prefilterBlur;
[Tooltip("Applies a median filter for even smoother bokeh.")]
public FilterQuality medianFilter;
[Tooltip("Dilates near blur over in focus area.")]
public bool dilateNearBlur;
public static QualitySettings[] presetQualitySettings =
{
// Low
new QualitySettings
{
prefilterBlur = false,
medianFilter = FilterQuality.None,
dilateNearBlur = false
},
// Medium
new QualitySettings
{
prefilterBlur = true,
medianFilter = FilterQuality.Normal,
dilateNearBlur = false
},
// High
new QualitySettings
{
prefilterBlur = true,
medianFilter = FilterQuality.High,
dilateNearBlur = true
}
};
}
[Serializable]
public struct FocusSettings
{
[Tooltip("Auto-focus on a selected transform.")]
public Transform transform;
[Min(0f), Tooltip("Focus distance (in world units).")]
public float focusPlane;
[Min(0.1f), Tooltip("Focus range (in world units). The focus plane is located in the center of the range.")]
public float range;
[Min(0f), Tooltip("Near focus distance (in world units).")]
public float nearPlane;
[Min(0f), Tooltip("Near blur falloff (in world units).")]
public float nearFalloff;
[Min(0f), Tooltip("Far focus distance (in world units).")]
public float farPlane;
[Min(0f), Tooltip("Far blur falloff (in world units).")]
public float farFalloff;
[Range(0f, kMaxBlur), Tooltip("Maximum blur radius for the near plane.")]
public float nearBlurRadius;
[Range(0f, kMaxBlur), Tooltip("Maximum blur radius for the far plane.")]
public float farBlurRadius;
public static FocusSettings defaultSettings
{
get
{
return new FocusSettings
{
transform = null,
focusPlane = 20f,
range = 35f,
nearPlane = 2.5f,
nearFalloff = 15f,
farPlane = 37.5f,
farFalloff = 50f,
nearBlurRadius = 15f,
farBlurRadius = 20f
};
}
}
}
[Serializable]
public struct BokehTextureSettings
{
[Tooltip("Adding a texture to this field will enable the use of \"Bokeh Textures\". Use with care. This feature is only available on Shader Model 5 compatible-hardware and performance scale with the amount of bokeh.")]
public Texture2D texture;
[Range(0.01f, 10f), Tooltip("Maximum size of bokeh textures on screen.")]
public float scale;
[Range(0.01f, 100f), Tooltip("Bokeh brightness.")]
public float intensity;
[Range(0.01f, 5f), Tooltip("Controls the amount of bokeh textures. Lower values mean more bokeh splats.")]
public float threshold;
[Range(0.01f, 1f), Tooltip("Controls the spawn conditions. Lower values mean more visible bokeh.")]
public float spawnHeuristic;
public static BokehTextureSettings defaultSettings
{
get
{
return new BokehTextureSettings
{
texture = null,
scale = 1f,
intensity = 50f,
threshold = 2f,
spawnHeuristic = 0.15f
};
}
}
}
#endregion
public GlobalSettings settings = GlobalSettings.defaultSettings;
public FocusSettings focus = FocusSettings.defaultSettings;
public BokehTextureSettings bokehTexture = BokehTextureSettings.defaultSettings;
[SerializeField]
private Shader m_FilmicDepthOfFieldShader;
public Shader filmicDepthOfFieldShader
{
get
{
if (m_FilmicDepthOfFieldShader == null)
m_FilmicDepthOfFieldShader = Shader.Find("Hidden/DepthOfField/DepthOfField");
return m_FilmicDepthOfFieldShader;
}
}
[SerializeField]
private Shader m_MedianFilterShader;
public Shader medianFilterShader
{
get
{
if (m_MedianFilterShader == null)
m_MedianFilterShader = Shader.Find("Hidden/DepthOfField/MedianFilter");
return m_MedianFilterShader;
}
}
[SerializeField]
private Shader m_TextureBokehShader;
public Shader textureBokehShader
{
get
{
if (m_TextureBokehShader == null)
m_TextureBokehShader = Shader.Find("Hidden/DepthOfField/BokehSplatting");
return m_TextureBokehShader;
}
}
private RenderTextureUtility m_RTU = new RenderTextureUtility();
private Material m_FilmicDepthOfFieldMaterial;
public Material filmicDepthOfFieldMaterial
{
get
{
if (m_FilmicDepthOfFieldMaterial == null)
m_FilmicDepthOfFieldMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(filmicDepthOfFieldShader);
return m_FilmicDepthOfFieldMaterial;
}
}
private Material m_MedianFilterMaterial;
public Material medianFilterMaterial
{
get
{
if (m_MedianFilterMaterial == null)
m_MedianFilterMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(medianFilterShader);
return m_MedianFilterMaterial;
}
}
private Material m_TextureBokehMaterial;
public Material textureBokehMaterial
{
get
{
if (m_TextureBokehMaterial == null)
m_TextureBokehMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(textureBokehShader);
return m_TextureBokehMaterial;
}
}
private ComputeBuffer m_ComputeBufferDrawArgs;
public ComputeBuffer computeBufferDrawArgs
{
get
{
if (m_ComputeBufferDrawArgs == null)
{
#if UNITY_5_4_OR_NEWER
m_ComputeBufferDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.IndirectArguments);
#else
m_ComputeBufferDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.DrawIndirect);
#endif
m_ComputeBufferDrawArgs.SetData(new[] {0, 1, 0, 0});
}
return m_ComputeBufferDrawArgs;
}
}
private ComputeBuffer m_ComputeBufferPoints;
public ComputeBuffer computeBufferPoints
{
get
{
if (m_ComputeBufferPoints == null)
m_ComputeBufferPoints = new ComputeBuffer(90000, 12 + 16, ComputeBufferType.Append);
return m_ComputeBufferPoints;
}
}
private QualitySettings m_CurrentQualitySettings;
private float m_LastApertureOrientation;
private Vector4 m_OctogonalBokehDirection1;
private Vector4 m_OctogonalBokehDirection2;
private Vector4 m_OctogonalBokehDirection3;
private Vector4 m_OctogonalBokehDirection4;
private Vector4 m_HexagonalBokehDirection1;
private Vector4 m_HexagonalBokehDirection2;
private Vector4 m_HexagonalBokehDirection3;
private int m_BlurParams;
private int m_BlurCoe;
private int m_Offsets;
private int m_BlurredColor;
private int m_SpawnHeuristic;
private int m_BokehParams;
private int m_Convolved_TexelSize;
private int m_SecondTex;
private int m_ThirdTex;
private int m_MainTex;
private int m_Screen;
private void Awake()
{
m_BlurParams = Shader.PropertyToID("_BlurParams");
m_BlurCoe = Shader.PropertyToID("_BlurCoe");
m_Offsets = Shader.PropertyToID("_Offsets");
m_BlurredColor = Shader.PropertyToID("_BlurredColor");
m_SpawnHeuristic = Shader.PropertyToID("_SpawnHeuristic");
m_BokehParams = Shader.PropertyToID("_BokehParams");
m_Convolved_TexelSize = Shader.PropertyToID("_Convolved_TexelSize");
m_SecondTex = Shader.PropertyToID("_SecondTex");
m_ThirdTex = Shader.PropertyToID("_ThirdTex");
m_MainTex = Shader.PropertyToID("_MainTex");
m_Screen = Shader.PropertyToID("_Screen");
}
private void OnEnable()
{
if (!ImageEffectHelper.IsSupported(filmicDepthOfFieldShader, true, true, this) || !ImageEffectHelper.IsSupported(medianFilterShader, true, true, this))
{
enabled = false;
return;
}
if (ImageEffectHelper.supportsDX11 && !ImageEffectHelper.IsSupported(textureBokehShader, true, true, this))
{
enabled = false;
return;
}
ComputeBlurDirections(true);
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
private void OnDisable()
{
ReleaseComputeResources();
if (m_FilmicDepthOfFieldMaterial != null)
DestroyImmediate(m_FilmicDepthOfFieldMaterial);
if (m_TextureBokehMaterial != null)
DestroyImmediate(m_TextureBokehMaterial);
if (m_MedianFilterMaterial != null)
DestroyImmediate(m_MedianFilterMaterial);
m_FilmicDepthOfFieldMaterial = null;
m_TextureBokehMaterial = null;
m_MedianFilterMaterial = null;
m_RTU.ReleaseAllTemporaryRenderTextures();
}
//-------------------------------------------------------------------//
// Main entry point //
//-------------------------------------------------------------------//
[ImageEffectOpaque]
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (medianFilterMaterial == null || filmicDepthOfFieldMaterial == null)
{
Graphics.Blit(source, destination);
return;
}
if (settings.visualizeFocus)
{
Vector4 blurrinessParam;
Vector4 blurrinessCoe;
ComputeCocParameters(out blurrinessParam, out blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector(m_BlurParams, blurrinessParam);
filmicDepthOfFieldMaterial.SetVector(m_BlurCoe, blurrinessCoe);
Graphics.Blit(null, destination, filmicDepthOfFieldMaterial, (int)Passes.VisualizeCocExplicit);
}
else
{
DoDepthOfField(source, destination);
}
m_RTU.ReleaseAllTemporaryRenderTextures();
}
private void DoDepthOfField(RenderTexture source, RenderTexture destination)
{
m_CurrentQualitySettings = QualitySettings.presetQualitySettings[(int)settings.filteringQuality];
float radiusAdjustement = source.height / 720f;
float textureBokehScale = radiusAdjustement;
float textureBokehMaxRadius = Mathf.Max(focus.nearBlurRadius, focus.farBlurRadius) * textureBokehScale * 0.75f;
float nearBlurRadius = focus.nearBlurRadius * radiusAdjustement;
float farBlurRadius = focus.farBlurRadius * radiusAdjustement;
float maxBlurRadius = Mathf.Max(nearBlurRadius, farBlurRadius);
switch (settings.apertureShape)
{
case ApertureShape.Hexagonal:
maxBlurRadius *= 1.2f;
break;
case ApertureShape.Octogonal:
maxBlurRadius *= 1.15f;
break;
}
if (maxBlurRadius < 0.5f)
{
Graphics.Blit(source, destination);
return;
}
// Quarter resolution
int rtW = source.width / 2;
int rtH = source.height / 2;
var blurrinessCoe = new Vector4(nearBlurRadius * 0.5f, farBlurRadius * 0.5f, 0f, 0f);
var colorAndCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
var colorAndCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
// Downsample to Color + COC buffer
Vector4 cocParam;
Vector4 cocCoe;
ComputeCocParameters(out cocParam, out cocCoe);
filmicDepthOfFieldMaterial.SetVector(m_BlurParams, cocParam);
filmicDepthOfFieldMaterial.SetVector(m_BlurCoe, cocCoe);
Graphics.Blit(source, colorAndCoc2, filmicDepthOfFieldMaterial, (int)Passes.CaptureCocExplicit);
var src = colorAndCoc2;
var dst = colorAndCoc;
// Collect texture bokeh candidates and replace with a darker pixel
if (shouldPerformBokeh)
{
// Blur a bit so we can do a frequency check
var blurred = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
Graphics.Blit(src, blurred, filmicDepthOfFieldMaterial, (int)Passes.BoxBlur);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, new Vector4(0f, 1.5f, 0f, 1.5f));
Graphics.Blit(blurred, dst, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, new Vector4(1.5f, 0f, 0f, 1.5f));
Graphics.Blit(dst, blurred, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
// Collect texture bokeh candidates and replace with a darker pixel
textureBokehMaterial.SetTexture(m_BlurredColor, blurred);
textureBokehMaterial.SetFloat(m_SpawnHeuristic, bokehTexture.spawnHeuristic);
textureBokehMaterial.SetVector(m_BokehParams, new Vector4(bokehTexture.scale * textureBokehScale, bokehTexture.intensity, bokehTexture.threshold, textureBokehMaxRadius));
Graphics.SetRandomWriteTarget(1, computeBufferPoints);
Graphics.Blit(src, dst, textureBokehMaterial, (int)BokehTexturesPasses.Collect);
Graphics.ClearRandomWriteTargets();
SwapRenderTexture(ref src, ref dst);
m_RTU.ReleaseTemporaryRenderTexture(blurred);
}
filmicDepthOfFieldMaterial.SetVector(m_BlurParams, cocParam);
filmicDepthOfFieldMaterial.SetVector(m_BlurCoe, blurrinessCoe);
// Dilate near blur factor
RenderTexture blurredFgCoc = null;
if (m_CurrentQualitySettings.dilateNearBlur)
{
var blurredFgCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
blurredFgCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, new Vector4(0f, nearBlurRadius * 0.75f, 0f, 0f));
Graphics.Blit(src, blurredFgCoc2, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCocFromColor);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, new Vector4(nearBlurRadius * 0.75f, 0f, 0f, 0f));
Graphics.Blit(blurredFgCoc2, blurredFgCoc, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCoc);
m_RTU.ReleaseTemporaryRenderTexture(blurredFgCoc2);
blurredFgCoc.filterMode = FilterMode.Point;
}
// Blur downsampled color to fill the gap between samples
if (m_CurrentQualitySettings.prefilterBlur)
{
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, (int)Passes.CocPrefilter);
SwapRenderTexture(ref src, ref dst);
}
// Apply blur : Circle / Hexagonal or Octagonal (blur will create bokeh if bright pixel where not removed by "m_UseBokehTexture")
switch (settings.apertureShape)
{
case ApertureShape.Circular:
DoCircularBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius);
break;
case ApertureShape.Hexagonal:
DoHexagonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius);
break;
case ApertureShape.Octogonal:
DoOctogonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius);
break;
}
// Smooth result
switch (m_CurrentQualitySettings.medianFilter)
{
case FilterQuality.Normal:
{
medianFilterMaterial.SetVector(m_Offsets, new Vector4(1f, 0f, 0f, 0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
medianFilterMaterial.SetVector(m_Offsets, new Vector4(0f, 1f, 0f, 0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
break;
}
case FilterQuality.High:
{
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3X3);
SwapRenderTexture(ref src, ref dst);
break;
}
}
// Merge to full resolution (with boost) + upsampling (linear or bicubic)
filmicDepthOfFieldMaterial.SetVector(m_BlurCoe, blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector(m_Convolved_TexelSize, new Vector4(src.width, src.height, 1f / src.width, 1f / src.height));
filmicDepthOfFieldMaterial.SetTexture(m_SecondTex, src);
int mergePass = (int)Passes.MergeExplicit;
// Apply texture bokeh
if (shouldPerformBokeh)
{
var tmp = m_RTU.GetTemporaryRenderTexture(source.height, source.width, 0, source.format);
Graphics.Blit(source, tmp, filmicDepthOfFieldMaterial, mergePass);
Graphics.SetRenderTarget(tmp);
ComputeBuffer.CopyCount(computeBufferPoints, computeBufferDrawArgs, 0);
textureBokehMaterial.SetBuffer("pointBuffer", computeBufferPoints);
textureBokehMaterial.SetTexture(m_MainTex, bokehTexture.texture);
textureBokehMaterial.SetVector(m_Screen, new Vector3(1f / (1f * source.width), 1f / (1f * source.height), textureBokehMaxRadius));
textureBokehMaterial.SetPass((int)BokehTexturesPasses.Apply);
Graphics.DrawProceduralIndirect(MeshTopology.Points, computeBufferDrawArgs, 0);
Graphics.Blit(tmp, destination); // Hackaround for DX11 flipfun (OPTIMIZEME)
}
else
{
Graphics.Blit(source, destination, filmicDepthOfFieldMaterial, mergePass);
}
}
//-------------------------------------------------------------------//
// Blurs //
//-------------------------------------------------------------------//
private void DoHexagonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture(m_SecondTex, blurredFgCoc);
var tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, m_HexagonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, m_HexagonalBokehDirection2);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, m_HexagonalBokehDirection3);
filmicDepthOfFieldMaterial.SetTexture(m_ThirdTex, src);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
SwapRenderTexture(ref src, ref dst);
}
private void DoOctogonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture(m_SecondTex, blurredFgCoc);
var tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, m_OctogonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, m_OctogonalBokehDirection2);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, m_OctogonalBokehDirection3);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector(m_Offsets, m_OctogonalBokehDirection4);
filmicDepthOfFieldMaterial.SetTexture(m_ThirdTex, dst);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
}
private void DoCircularBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
int bokehPass;
if (blurredFgCoc != null)
{
filmicDepthOfFieldMaterial.SetTexture(m_SecondTex, blurredFgCoc);
bokehPass = (maxRadius > 10f) ? (int)Passes.CircleBlurWithDilatedFg : (int)Passes.CircleBlowLowQualityWithDilatedFg;
}
else
{
bokehPass = (maxRadius > 10f) ? (int)Passes.CircleBlur : (int)Passes.CircleBlurLowQuality;
}
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, bokehPass);
SwapRenderTexture(ref src, ref dst);
}
//-------------------------------------------------------------------//
// Helpers //
//-------------------------------------------------------------------//
private void ComputeCocParameters(out Vector4 blurParams, out Vector4 blurCoe)
{
var sceneCamera = GetComponent<Camera>();
float focusDistance;
float nearFalloff = focus.nearFalloff * 2f;
float farFalloff = focus.farFalloff * 2f;
float nearPlane = focus.nearPlane;
float farPlane = focus.farPlane;
if (settings.tweakMode == TweakMode.Range)
{
if (focus.transform != null)
focusDistance = sceneCamera.WorldToViewportPoint(focus.transform.position).z;
else
focusDistance = focus.focusPlane;
float s = focus.range * 0.5f;
nearPlane = focusDistance - s;
farPlane = focusDistance + s;
}
nearPlane -= (nearFalloff * 0.5f);
farPlane += (farFalloff * 0.5f);
focusDistance = (nearPlane + farPlane) * 0.5f;
float focusDistance01 = focusDistance / sceneCamera.farClipPlane;
float nearDistance01 = nearPlane / sceneCamera.farClipPlane;
float farDistance01 = farPlane / sceneCamera.farClipPlane;
var dof = farPlane - nearPlane;
var dof01 = farDistance01 - nearDistance01;
var nearFalloff01 = nearFalloff / dof;
var farFalloff01 = farFalloff / dof;
float nearFocusRange01 = (1f - nearFalloff01) * (dof01 * 0.5f);
float farFocusRange01 = (1f - farFalloff01) * (dof01 * 0.5f);
if (focusDistance01 <= nearDistance01)
focusDistance01 = nearDistance01 + 1e-6f;
if (focusDistance01 >= farDistance01)
focusDistance01 = farDistance01 - 1e-6f;
if ((focusDistance01 - nearFocusRange01) <= nearDistance01)
nearFocusRange01 = focusDistance01 - nearDistance01 - 1e-6f;
if ((focusDistance01 + farFocusRange01) >= farDistance01)
farFocusRange01 = farDistance01 - focusDistance01 - 1e-6f;
float a1 = 1f / (nearDistance01 - focusDistance01 + nearFocusRange01);
float a2 = 1f / (farDistance01 - focusDistance01 - farFocusRange01);
float b1 = 1f - a1 * nearDistance01;
float b2 = 1f - a2 * farDistance01;
const float c1 = -1f;
const float c2 = 1f;
blurParams = new Vector4(c1 * a1, c1 * b1, c2 * a2, c2 * b2);
blurCoe = new Vector4(0f, 0f, (b2 - b1) / (a1 - a2), 0f);
// Save values so we can switch from one tweak mode to the other on the fly
focus.nearPlane = nearPlane + (nearFalloff * 0.5f);
focus.farPlane = farPlane - (farFalloff * 0.5f);
focus.focusPlane = (focus.nearPlane + focus.farPlane) * 0.5f;
focus.range = focus.farPlane - focus.nearPlane;
}
private void ReleaseComputeResources()
{
if (m_ComputeBufferDrawArgs != null)
m_ComputeBufferDrawArgs.Release();
if (m_ComputeBufferPoints != null)
m_ComputeBufferPoints.Release();
m_ComputeBufferDrawArgs = null;
m_ComputeBufferPoints = null;
}
private void ComputeBlurDirections(bool force)
{
if (!force && Math.Abs(m_LastApertureOrientation - settings.apertureOrientation) < float.Epsilon)
return;
m_LastApertureOrientation = settings.apertureOrientation;
float rotationRadian = settings.apertureOrientation * Mathf.Deg2Rad;
float cosinus = Mathf.Cos(rotationRadian);
float sinus = Mathf.Sin(rotationRadian);
m_OctogonalBokehDirection1 = new Vector4(0.5f, 0f, 0f, 0f);
m_OctogonalBokehDirection2 = new Vector4(0f, 0.5f, 1f, 0f);
m_OctogonalBokehDirection3 = new Vector4(-0.353553f, 0.353553f, 1f, 0f);
m_OctogonalBokehDirection4 = new Vector4(0.353553f, 0.353553f, 1f, 0f);
m_HexagonalBokehDirection1 = new Vector4(0.5f, 0f, 0f, 0f);
m_HexagonalBokehDirection2 = new Vector4(0.25f, 0.433013f, 1f, 0f);
m_HexagonalBokehDirection3 = new Vector4(0.25f, -0.433013f, 1f, 0f);
if (rotationRadian > float.Epsilon)
{
Rotate2D(ref m_OctogonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection3, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection4, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection3, cosinus, sinus);
}
}
private bool shouldPerformBokeh
{
get { return ImageEffectHelper.supportsDX11 && bokehTexture.texture != null && textureBokehMaterial; }
}
private static void Rotate2D(ref Vector4 direction, float cosinus, float sinus)
{
var source = direction;
direction.x = source.x * cosinus - source.y * sinus;
direction.y = source.x * sinus + source.y * cosinus;
}
private static void SwapRenderTexture(ref RenderTexture src, ref RenderTexture dst)
{
RenderTexture tmp = dst;
dst = src;
src = tmp;
}
private static void GetDirectionalBlurPassesFromRadius(RenderTexture blurredFgCoc, float maxRadius, out int blurPass, out int blurAndMergePass)
{
if (blurredFgCoc == null)
{
if (maxRadius > 10f)
{
blurPass = (int)Passes.ShapeHighQuality;
blurAndMergePass = (int)Passes.ShapeHighQualityMerge;
}
else if (maxRadius > 5f)
{
blurPass = (int)Passes.ShapeMediumQuality;
blurAndMergePass = (int)Passes.ShapeMediumQualityMerge;
}
else
{
blurPass = (int)Passes.ShapeLowQuality;
blurAndMergePass = (int)Passes.ShapeLowQualityMerge;
}
}
else
{
if (maxRadius > 10f)
{
blurPass = (int)Passes.ShapeHighQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeHighQualityMergeDilateFg;
}
else if (maxRadius > 5f)
{
blurPass = (int)Passes.ShapeMediumQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeMediumQualityMergeDilateFg;
}
else
{
blurPass = (int)Passes.ShapeLowQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeLowQualityMergeDilateFg;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebApiAngularJsAzureUploader.Areas.HelpPage.ModelDescriptions;
using WebApiAngularJsAzureUploader.Areas.HelpPage.Models;
namespace WebApiAngularJsAzureUploader.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 media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), 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 description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <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)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.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}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonArrayContract : JsonContainerContract
{
/// <summary>
/// Gets the <see cref="System.Type"/> of the collection items.
/// </summary>
/// <value>The <see cref="System.Type"/> of the collection items.</value>
public Type CollectionItemType { get; private set; }
/// <summary>
/// Gets a value indicating whether the collection type is a multidimensional array.
/// </summary>
/// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value>
public bool IsMultidimensionalArray { get; private set; }
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private ObjectConstructor<object> _genericWrapperCreator;
private Func<object> _genericTemporaryCollectionCreator;
internal bool IsArray { get; private set; }
internal bool ShouldCreateWrapper { get; private set; }
internal bool CanDeserialize { get; private set; }
private readonly ConstructorInfo _parameterizedConstructor;
private ObjectConstructor<object> _parameterizedCreator;
private ObjectConstructor<object> _overrideCreator;
internal ObjectConstructor<object> ParameterizedCreator
{
get
{
if (_parameterizedCreator == null)
{
_parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor);
}
return _parameterizedCreator;
}
}
/// <summary>
/// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>.
/// </summary>
/// <value>The function used to create the object.</value>
public ObjectConstructor<object> OverrideCreator
{
get { return _overrideCreator; }
set
{
_overrideCreator = value;
// hacky
CanDeserialize = true;
}
}
/// <summary>
/// Gets a value indicating whether the creator has a parameter with the collection values.
/// </summary>
/// <value><c>true</c> if the creator has a parameter with the collection values; otherwise, <c>false</c>.</value>
public bool HasParameterizedCreator { get; set; }
internal bool HasParameterizedCreatorInternal
{
get { return (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonArrayContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Array;
IsArray = CreatedType.IsArray;
bool canDeserialize;
Type tempCollectionType;
if (IsArray)
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType);
IsReadOnlyOrFixedSize = true;
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
canDeserialize = true;
IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1);
}
else if (typeof(IList).IsAssignableFrom(underlyingType))
{
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
}
else
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType);
}
if (underlyingType == typeof(IList))
{
CreatedType = typeof(List<object>);
}
if (CollectionItemType != null)
{
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
}
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>));
canDeserialize = true;
}
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>)))
{
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
}
#if !(NET20 || NET35 || PORTABLE40)
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>)))
{
CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType);
}
#endif
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
canDeserialize = true;
ShouldCreateWrapper = true;
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>)))
{
CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType);
}
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType);
IsReadOnlyOrFixedSize = true;
canDeserialize = HasParameterizedCreatorInternal;
}
#endif
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>)))
{
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
}
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
#if !(NET35 || NET20)
if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName)
{
FSharpUtils.EnsureInitialized(underlyingType.Assembly());
_parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType);
}
#endif
if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
_genericCollectionDefinitionType = tempCollectionType;
IsReadOnlyOrFixedSize = false;
ShouldCreateWrapper = false;
canDeserialize = true;
}
else
{
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
IsReadOnlyOrFixedSize = true;
ShouldCreateWrapper = true;
canDeserialize = HasParameterizedCreatorInternal;
}
}
else
{
// types that implement IEnumerable and nothing else
canDeserialize = false;
ShouldCreateWrapper = true;
}
CanDeserialize = canDeserialize;
#if (NET20 || NET35)
if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType))
{
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (IsArray && !IsMultidimensionalArray))
{
ShouldCreateWrapper = true;
}
}
#endif
#if !(NET20 || NET35 || NET40)
Type immutableCreatedType;
ObjectConstructor<object> immutableParameterizedCreator;
if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator;
IsReadOnlyOrFixedSize = true;
CanDeserialize = true;
}
#endif
}
internal IWrappedCollection CreateWrapper(object list)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType);
Type constructorArgument;
if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>))
|| _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType);
}
else
{
constructorArgument = _genericCollectionDefinitionType;
}
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor);
}
return (IWrappedCollection)_genericWrapperCreator(list);
}
internal IList CreateTemporaryCollection()
{
if (_genericTemporaryCollectionCreator == null)
{
// multidimensional array will also have array instances in it
Type collectionItemType = (IsMultidimensionalArray || CollectionItemType == null)
? typeof(object)
: CollectionItemType;
Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType);
_genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType);
}
return (IList)_genericTemporaryCollectionCreator();
}
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Data.Core;
using Avalonia.Utilities;
#nullable enable
namespace Avalonia.Markup.Parsers
{
#if !BUILDTASK
public
#endif
class PropertyPathGrammar
{
private enum State
{
Start,
Next,
AfterProperty,
End
}
public static IEnumerable<ISyntax> Parse(string s)
{
var r = new CharacterReader(s.AsSpan());
return Parse(ref r);
}
private static IEnumerable<ISyntax> Parse(ref CharacterReader r)
{
var state = State.Start;
var parsed = new List<ISyntax>();
while (state != State.End)
{
ISyntax? syntax = null;
if (state == State.Start)
(state, syntax) = ParseStart(ref r);
else if (state == State.Next)
(state, syntax) = ParseNext(ref r);
else if (state == State.AfterProperty)
(state, syntax) = ParseAfterProperty(ref r);
if (syntax != null)
{
parsed.Add(syntax);
}
}
if (state != State.End && r.End)
{
throw new ExpressionParseException(r.Position, "Unexpected end of property path");
}
return parsed;
}
private static (State, ISyntax?) ParseNext(ref CharacterReader r)
{
r.SkipWhitespace();
if (r.End)
return (State.End, null);
return ParseStart(ref r);
}
private static (State, ISyntax) ParseStart(ref CharacterReader r)
{
if (TryParseCasts(ref r, out var rv))
return rv;
r.SkipWhitespace();
if (r.TakeIf('('))
return ParseTypeQualifiedProperty(ref r);
return ParseProperty(ref r);
}
private static (State, ISyntax) ParseTypeQualifiedProperty(ref CharacterReader r)
{
r.SkipWhitespace();
const string error =
"Unable to parse qualified property name, expected `(ns:TypeName.PropertyName)` or `(TypeName.PropertyName)` after `(`";
var typeName = ParseXamlIdentifier(ref r);
if (!r.TakeIf('.'))
throw new ExpressionParseException(r.Position, error);
var propertyName = r.ParseIdentifier();
if (propertyName.IsEmpty)
throw new ExpressionParseException(r.Position, error);
r.SkipWhitespace();
if (!r.TakeIf(')'))
throw new ExpressionParseException(r.Position,
"Expected ')' after qualified property name "
+ typeName.ns + ':' + typeName.name +
"." + propertyName.ToString());
return (State.AfterProperty,
new TypeQualifiedPropertySyntax
{
Name = propertyName.ToString(),
TypeName = typeName.name,
TypeNamespace = typeName.ns
});
}
static (string? ns, string name) ParseXamlIdentifier(ref CharacterReader r)
{
var ident = r.ParseIdentifier();
if (ident.IsEmpty)
throw new ExpressionParseException(r.Position, "Expected identifier");
if (r.TakeIf(':'))
{
var part2 = r.ParseIdentifier();
if (part2.IsEmpty)
throw new ExpressionParseException(r.Position,
"Expected the rest of the identifier after " + ident.ToString() + ":");
return (ident.ToString(), part2.ToString());
}
return (null, ident.ToString());
}
private static (State, ISyntax) ParseProperty(ref CharacterReader r)
{
r.SkipWhitespace();
var prop = r.ParseIdentifier();
if (prop.IsEmpty)
throw new ExpressionParseException(r.Position, "Unable to parse property name");
return (State.AfterProperty, new PropertySyntax {Name = prop.ToString()});
}
private static bool TryParseCasts(ref CharacterReader r, out (State, ISyntax) rv)
{
if (r.TakeIfKeyword(":="))
rv = ParseEnsureType(ref r);
else if (r.TakeIfKeyword(":>") || r.TakeIfKeyword("as "))
rv = ParseCastType(ref r);
else
{
rv = default;
return false;
}
return true;
}
private static (State, ISyntax?) ParseAfterProperty(ref CharacterReader r)
{
if (TryParseCasts(ref r, out var rv))
return rv;
r.SkipWhitespace();
if (r.End)
return (State.End, null);
if (r.TakeIf('.'))
return (State.Next, ChildTraversalSyntax.Instance);
throw new ExpressionParseException(r.Position, "Unexpected character " + r.Peek + " after property name");
}
private static (State, ISyntax) ParseEnsureType(ref CharacterReader r)
{
r.SkipWhitespace();
var type = ParseXamlIdentifier(ref r);
return (State.AfterProperty, new EnsureTypeSyntax {TypeName = type.name, TypeNamespace = type.ns});
}
private static (State, ISyntax) ParseCastType(ref CharacterReader r)
{
r.SkipWhitespace();
var type = ParseXamlIdentifier(ref r);
return (State.AfterProperty, new CastTypeSyntax {TypeName = type.name, TypeNamespace = type.ns});
}
public interface ISyntax
{
}
public class PropertySyntax : ISyntax
{
public string Name { get; set; } = string.Empty;
public override bool Equals(object? obj)
=> obj is PropertySyntax other
&& other.Name == Name;
}
public class TypeQualifiedPropertySyntax : ISyntax
{
public string Name { get; set; } = string.Empty;
public string TypeName { get; set; } = string.Empty;
public string? TypeNamespace { get; set; }
public override bool Equals(object? obj)
=> obj is TypeQualifiedPropertySyntax other
&& other.Name == Name
&& other.TypeName == TypeName
&& other.TypeNamespace == TypeNamespace;
}
public class ChildTraversalSyntax : ISyntax
{
public static ChildTraversalSyntax Instance { get; } = new ChildTraversalSyntax();
public override bool Equals(object? obj) => obj is ChildTraversalSyntax;
}
public class EnsureTypeSyntax : ISyntax
{
public string TypeName { get; set; } = string.Empty;
public string? TypeNamespace { get; set; }
public override bool Equals(object? obj)
=> obj is EnsureTypeSyntax other
&& other.TypeName == TypeName
&& other.TypeNamespace == TypeNamespace;
}
public class CastTypeSyntax : ISyntax
{
public string TypeName { get; set; } = string.Empty;
public string? TypeNamespace { get; set; }
public override bool Equals(object? obj)
=> obj is CastTypeSyntax other
&& other.TypeName == TypeName
&& other.TypeNamespace == TypeNamespace;
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityBase.EntityFramework.Stores
{
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityBase.EntityFramework.Interfaces;
using IdentityBase.EntityFramework.Mappers;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
/// <summary>
/// Implementation of IPersistedGrantStore thats uses EF.
/// </summary>
/// <seealso cref="IdentityServer4.Stores.IPersistedGrantStore" />
public class PersistedGrantStore : IPersistedGrantStore
{
private readonly IPersistedGrantDbContext _context;
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="PersistedGrantStore"/>
/// class.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="logger">The logger.</param>
public PersistedGrantStore(
IPersistedGrantDbContext context,
ILogger<PersistedGrantStore> logger)
{
this._context = context;
this._logger = logger;
}
/// <summary>
/// Stores the asynchronous.
/// </summary>
/// <param name="token">The token.</param>
/// <returns></returns>
public Task StoreAsync(PersistedGrant token)
{
Entities.PersistedGrant existing = this._context.PersistedGrants
.SingleOrDefault(x => x.Key == token.Key);
if (existing == null)
{
this._logger.LogDebug(
"{persistedGrantKey} not found in database",
token.Key);
var persistedGrant = token.ToEntity();
this._context.PersistedGrants.Add(persistedGrant);
}
else
{
this._logger.LogDebug(
"{persistedGrantKey} found in database",
token.Key);
token.UpdateEntity(existing);
}
try
{
this._context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
this._logger.LogWarning(
"exception updating {persistedGrantKey} persisted grant in database: {error}",
token.Key, ex.Message);
}
return Task.FromResult(0);
}
/// <summary>
/// Gets the grant.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public Task<PersistedGrant> GetAsync(string key)
{
var persistedGrant = this._context.PersistedGrants
.FirstOrDefault(x => x.Key == key);
var model = persistedGrant?.ToModel();
this._logger.LogDebug(
"{persistedGrantKey} found in database: {persistedGrantKeyFound}",
key, model != null);
return Task.FromResult(model);
}
/// <summary>
/// Gets all grants for a given subject id.
/// </summary>
/// <param name="subjectId">The subject identifier.</param>
/// <returns></returns>
public Task<IEnumerable<PersistedGrant>> GetAllAsync(string subjectId)
{
var persistedGrants = this._context.PersistedGrants
.Where(x => x.SubjectId == subjectId).ToList();
var model = persistedGrants.Select(x => x.ToModel());
this._logger.LogDebug(
"{persistedGrantCount} persisted grants found for {subjectId}",
persistedGrants.Count,
subjectId);
return Task.FromResult(model);
}
/// <summary>
/// Removes the grant by key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public Task RemoveAsync(string key)
{
var persistedGrant = this._context.PersistedGrants
.FirstOrDefault(x => x.Key == key);
if (persistedGrant != null)
{
this._logger.LogDebug(
"removing {persistedGrantKey} persisted grant from database",
key);
this._context.PersistedGrants.Remove(persistedGrant);
try
{
this._context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
this._logger.LogInformation(
"exception removing {persistedGrantKey} persisted grant from database: {error}",
key,
ex.Message);
}
}
else
{
this._logger.LogDebug(
"no {persistedGrantKey} persisted grant found in database",
key);
}
return Task.FromResult(0);
}
/// <summary>
/// Removes all grants for a given subject id and client id combination.
/// </summary>
/// <param name="subjectId">The subject identifier.</param>
/// <param name="clientId">The client identifier.</param>
/// <returns></returns>
public Task RemoveAllAsync(string subjectId, string clientId)
{
var persistedGrants = this._context.PersistedGrants
.Where(x => x.SubjectId == subjectId &&
x.ClientId == clientId).ToList();
this._logger.LogDebug(
"removing {persistedGrantCount} persisted grants from database for subject {subjectId}, clientId {clientId}",
persistedGrants.Count,
subjectId,
clientId);
this._context.PersistedGrants.RemoveRange(persistedGrants);
try
{
this._context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
this._logger.LogInformation(
"removing {persistedGrantCount} persisted grants from database for subject {subjectId}, clientId {clientId}: {error}",
persistedGrants.Count,
subjectId,
clientId,
ex.Message);
}
return Task.FromResult(0);
}
/// <summary>
/// Removes all grants of a give type for a given subject id and client
/// id combination.
/// </summary>
/// <param name="subjectId">The subject identifier.</param>
/// <param name="clientId">The client identifier.</param>
/// <param name="type">The type.</param>
/// <returns></returns>
public Task RemoveAllAsync(
string subjectId,
string clientId,
string type)
{
var persistedGrants = this._context.PersistedGrants.Where(x =>
x.SubjectId == subjectId &&
x.ClientId == clientId &&
x.Type == type).ToList();
this._logger.LogDebug(
"removing {persistedGrantCount} persisted grants from database for subject {subjectId}, clientId {clientId}, grantType {persistedGrantType}",
persistedGrants.Count,
subjectId,
clientId,
type);
this._context.PersistedGrants.RemoveRange(persistedGrants);
try
{
this._context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
this._logger.LogInformation(
"exception removing {persistedGrantCount} persisted grants from database for subject {subjectId}, clientId {clientId}, grantType {persistedGrantType}: {error}",
persistedGrants.Count,
subjectId,
clientId,
type,
ex.Message);
}
return Task.FromResult(0);
}
}
}
| |
// ImageListView - A listview control for image files
// Copyright (C) 2009 Ozgur Ozcitak
//
// 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.
//
// Ozgur Ozcitak (ozcitak@yahoo.com)
//
// Theme support coded by Robby
using System.ComponentModel;
using System.Drawing;
using System;
using System.Reflection;
using System.Collections.Generic;
namespace Manina.Windows.Forms
{
/// <summary>
/// Represents the color palette of the image list view.
/// </summary>
[TypeConverter(typeof(ImageListViewColorTypeConverter))]
public class ImageListViewColor
{
#region Member Variables
// control background color
Color mControlBackColor;
Color mDisabledBackColor;
// item colors
Color mBackColor;
Color mBorderColor;
Color mUnFocusedColor1;
Color mUnFocusedColor2;
Color mUnFocusedBorderColor;
Color mUnFocusedForeColor;
Color mForeColor;
Color mHoverColor1;
Color mHoverColor2;
Color mHoverBorderColor;
Color mInsertionCaretColor;
Color mSelectedColor1;
Color mSelectedColor2;
Color mSelectedBorderColor;
Color mSelectedForeColor;
Color mDisabledColor1;
Color mDisabledColor2;
Color mDisabledBorderColor;
Color mDisabledForeColor;
// thumbnail & pane
Color mImageInnerBorderColor;
Color mImageOuterBorderColor;
// details view
Color mCellForeColor;
Color mColumnHeaderBackColor1;
Color mColumnHeaderBackColor2;
Color mColumnHeaderForeColor;
Color mColumnHeaderHoverColor1;
Color mColumnHeaderHoverColor2;
Color mColumnSelectColor;
Color mColumnSeparatorColor;
Color mAlternateBackColor;
Color mAlternateCellForeColor;
// pane
Color mPaneBackColor;
Color mPaneSeparatorColor;
Color mPaneLabelColor;
// selection rectangle
Color mSelectionRectangleColor1;
Color mSelectionRectangleColor2;
Color mSelectionRectangleBorderColor;
#endregion
#region Properties
/// <summary>
/// Gets or sets the background color of the ImageListView control.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color of the ImageListView control.")]
[DefaultValue(typeof(Color), "Window")]
public Color ControlBackColor
{
get { return mControlBackColor; }
set { mControlBackColor = value; }
}
/// <summary>
/// Gets or sets the background color of the ImageListView control in its disabled state.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color of the ImageListView control in its disabled state.")]
[DefaultValue(typeof(Color), "Control")]
public Color DisabledBackColor
{
get { return mDisabledBackColor; }
set { mDisabledBackColor = value; }
}
/// <summary>
/// Gets or sets the background color of the ImageListViewItem.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color of the ImageListViewItem.")]
[DefaultValue(typeof(Color), "Window")]
public Color BackColor
{
get { return mBackColor; }
set { mBackColor = value; }
}
/// <summary>
/// Gets or sets the background color of alternating cells in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the background color of alternating cells in Details View.")]
[DefaultValue(typeof(Color), "Window")]
public Color AlternateBackColor
{
get { return mAlternateBackColor; }
set { mAlternateBackColor = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem.")]
[DefaultValue(typeof(Color), "64, 128, 128, 128")]
public Color BorderColor
{
get { return mBorderColor; }
set { mBorderColor = value; }
}
/// <summary>
/// Gets or sets the foreground color of the ImageListViewItem.
/// </summary>
[Category("Appearance"), Description("Gets or sets the foreground color of the ImageListViewItem.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color ForeColor
{
get { return mForeColor; }
set { mForeColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 of the ImageListViewItem if the control is not focused.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color1 of the ImageListViewItem if the control is not focused.")]
[DefaultValue(typeof(Color), "16, 128, 128, 128")]
public Color UnFocusedColor1
{
get { return mUnFocusedColor1; }
set { mUnFocusedColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 of the ImageListViewItem if the control is not focused.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color2 of the ImageListViewItem if the control is not focused.")]
[DefaultValue(typeof(Color), "64, 128, 128, 128")]
public Color UnFocusedColor2
{
get { return mUnFocusedColor2; }
set { mUnFocusedColor2 = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem if the control is not focused.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the control is not focused.")]
[DefaultValue(typeof(Color), "128, 128, 128, 128")]
public Color UnFocusedBorderColor
{
get { return mUnFocusedBorderColor; }
set { mUnFocusedBorderColor = value; }
}
/// <summary>
/// Gets or sets the fore color of the ImageListViewItem if the control is not focused.
/// </summary>
[Category("Appearance"), Description("Gets or sets the fore color of the ImageListViewItem if the control is not focused.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color UnFocusedForeColor
{
get { return mUnFocusedForeColor; }
set { mUnFocusedForeColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 if the ImageListViewItem is hovered.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color1 if the ImageListViewItem is hovered.")]
[DefaultValue(typeof(Color), "8, 10, 36, 106")]
public Color HoverColor1
{
get { return mHoverColor1; }
set { mHoverColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 if the ImageListViewItem is hovered.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color2 if the ImageListViewItem is hovered.")]
[DefaultValue(typeof(Color), "64, 10, 36, 106")]
public Color HoverColor2
{
get { return mHoverColor2; }
set { mHoverColor2 = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem if the item is hovered.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the item is hovered.")]
[DefaultValue(typeof(Color), "64, 10, 36, 106")]
public Color HoverBorderColor
{
get { return mHoverBorderColor; }
set { mHoverBorderColor = value; }
}
/// <summary>
/// Gets or sets the color of the insertion caret.
/// </summary>
[Category("Appearance"), Description("Gets or sets the color of the insertion caret.")]
[DefaultValue(typeof(Color), "Highlight")]
public Color InsertionCaretColor
{
get { return mInsertionCaretColor; }
set { mInsertionCaretColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 if the ImageListViewItem is selected.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color1 if the ImageListViewItem is selected.")]
[DefaultValue(typeof(Color), "16, 10, 36, 106")]
public Color SelectedColor1
{
get { return mSelectedColor1; }
set { mSelectedColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 if the ImageListViewItem is selected.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color2 if the ImageListViewItem is selected.")]
[DefaultValue(typeof(Color), "128, 10, 36, 106")]
public Color SelectedColor2
{
get { return mSelectedColor2; }
set { mSelectedColor2 = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem if the item is selected.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the item is selected.")]
[DefaultValue(typeof(Color), "128, 10, 36, 106")]
public Color SelectedBorderColor
{
get { return mSelectedBorderColor; }
set { mSelectedBorderColor = value; }
}
/// <summary>
/// Gets or sets the fore color of the ImageListViewItem if the item is selected.
/// </summary>
[Category("Appearance"), Description("Gets or sets the fore color of the ImageListViewItem if the item is selected.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color SelectedForeColor
{
get { return mSelectedForeColor; }
set { mSelectedForeColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 if the ImageListViewItem is disabled.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color1 if the ImageListViewItem is disabled.")]
[DefaultValue(typeof(Color), "0, 128, 128, 128")]
public Color DisabledColor1
{
get { return mDisabledColor1; }
set { mDisabledColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 if the ImageListViewItem is disabled.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background gradient color2 if the ImageListViewItem is disabled.")]
[DefaultValue(typeof(Color), "32, 128, 128, 128")]
public Color DisabledColor2
{
get { return mDisabledColor2; }
set { mDisabledColor2 = value; }
}
/// <summary>
/// Gets or sets the border color of the ImageListViewItem if the item is disabled.
/// </summary>
[Category("Appearance"), Description("Gets or sets the border color of the ImageListViewItem if the item is disabled.")]
[DefaultValue(typeof(Color), "32, 128, 128, 128")]
public Color DisabledBorderColor
{
get { return mDisabledBorderColor; }
set { mDisabledBorderColor = value; }
}
/// <summary>
/// Gets or sets the fore color of the ImageListViewItem if the item is disabled.
/// </summary>
[Category("Appearance"), Description("Gets or sets the fore color of the ImageListViewItem if the item is disabled.")]
[DefaultValue(typeof(Color), "128, 128, 128")]
public Color DisabledForeColor
{
get { return mDisabledForeColor; }
set { mDisabledForeColor = value; }
}
/// <summary>
/// Gets or sets the background gradient color1 of the column header.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the cells background color1 of the column header.")]
[DefaultValue(typeof(Color), "32, 212, 208, 200")]
public Color ColumnHeaderBackColor1
{
get { return mColumnHeaderBackColor1; }
set { mColumnHeaderBackColor1 = value; }
}
/// <summary>
/// Gets or sets the background gradient color2 of the column header.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the cells background color2 of the column header.")]
[DefaultValue(typeof(Color), "196, 212, 208, 200")]
public Color ColumnHeaderBackColor2
{
get { return mColumnHeaderBackColor2; }
set { mColumnHeaderBackColor2 = value; }
}
/// <summary>
/// Gets or sets the background hover gradient color1 of the column header.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the background hover color1 of the column header.")]
[DefaultValue(typeof(Color), "16, 10, 36, 106")]
public Color ColumnHeaderHoverColor1
{
get { return mColumnHeaderHoverColor1; }
set { mColumnHeaderHoverColor1 = value; }
}
/// <summary>
/// Gets or sets the background hover gradient color2 of the column header.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the background hover color2 of the column header.")]
[DefaultValue(typeof(Color), "64, 10, 36, 106")]
public Color ColumnHeaderHoverColor2
{
get { return mColumnHeaderHoverColor2; }
set { mColumnHeaderHoverColor2 = value; }
}
/// <summary>
/// Gets or sets the cells foreground color of the column header text.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the cells foreground color of the column header text.")]
[DefaultValue(typeof(Color), "WindowText")]
public Color ColumnHeaderForeColor
{
get { return mColumnHeaderForeColor; }
set { mColumnHeaderForeColor = value; }
}
/// <summary>
/// Gets or sets the cells background color if column is selected in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the cells background color if column is selected in Details View.")]
[DefaultValue(typeof(Color), "16, 128, 128, 128")]
public Color ColumnSelectColor
{
get { return mColumnSelectColor; }
set { mColumnSelectColor = value; }
}
/// <summary>
/// Gets or sets the color of the separator in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the color of the separator in Details View.")]
[DefaultValue(typeof(Color), "32, 128, 128, 128")]
public Color ColumnSeparatorColor
{
get { return mColumnSeparatorColor; }
set { mColumnSeparatorColor = value; }
}
/// <summary>
/// Gets or sets the foreground color of the cell text in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the foreground color of the cell text in Details View.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color CellForeColor
{
get { return mCellForeColor; }
set { mCellForeColor = value; }
}
/// <summary>
/// Gets or sets the foreground color of alternating cells text in Details View.
/// </summary>
[Category("Appearance Details View"), Description("Gets or sets the foreground color of alternating cells text in Details View.")]
[DefaultValue(typeof(Color), "ControlText")]
public Color AlternateCellForeColor
{
get { return mAlternateCellForeColor; }
set { mAlternateCellForeColor = value; }
}
/// <summary>
/// Gets or sets the background color of the image pane.
/// </summary>
[Category("Appearance Pane View"), Description("Gets or sets the background color of the image pane.")]
[DefaultValue(typeof(Color), "16, 128, 128, 128")]
public Color PaneBackColor
{
get { return mPaneBackColor; }
set { mPaneBackColor = value; }
}
/// <summary>
/// Gets or sets the separator line color between image pane and thumbnail view.
/// </summary>
[Category("Appearance Pane View"), Description("Gets or sets the separator line color between image pane and thumbnail view.")]
[DefaultValue(typeof(Color), "128, 128, 128, 128")]
public Color PaneSeparatorColor
{
get { return mPaneSeparatorColor; }
set { mPaneSeparatorColor = value; }
}
/// <summary>
/// Gets or sets the color of labels in pane view.
/// </summary>
[Category("Appearance Pane View"), Description("Gets or sets the color of labels in pane view.")]
[DefaultValue(typeof(Color), "196, 0, 0, 0")]
public Color PaneLabelColor
{
get { return mPaneLabelColor; }
set { mPaneLabelColor = value; }
}
/// <summary>
/// Gets or sets the image inner border color for thumbnails and pane.
/// </summary>
[Category("Appearance Image"), Description("Gets or sets the image inner border color for thumbnails and pane.")]
[DefaultValue(typeof(Color), "128, 255, 255, 255")]
public Color ImageInnerBorderColor
{
get { return mImageInnerBorderColor; }
set { mImageInnerBorderColor = value; }
}
/// <summary>
/// Gets or sets the image outer border color for thumbnails and pane.
/// </summary>
[Category("Appearance Image"), Description("Gets or sets the image outer border color for thumbnails and pane.")]
[DefaultValue(typeof(Color), "128, 128, 128, 128")]
public Color ImageOuterBorderColor
{
get { return mImageOuterBorderColor; }
set { mImageOuterBorderColor = value; }
}
/// <summary>
/// Gets or sets the background color1 of the selection rectangle.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color1 of the selection rectangle.")]
[DefaultValue(typeof(Color), "128, 10, 36, 106")]
public Color SelectionRectangleColor1
{
get { return mSelectionRectangleColor1; }
set { mSelectionRectangleColor1 = value; }
}
/// <summary>
/// Gets or sets the background color2 of the selection rectangle.
/// </summary>
[Category("Appearance"), Description("Gets or sets the background color2 of the selection rectangle.")]
[DefaultValue(typeof(Color), "128, 10, 36, 106")]
public Color SelectionRectangleColor2
{
get { return mSelectionRectangleColor2; }
set { mSelectionRectangleColor2 = value; }
}
/// <summary>
/// Gets or sets the color of the selection rectangle border.
/// </summary>
[Category("Appearance"), Description("Gets or sets the color of the selection rectangle border.")]
[DefaultValue(typeof(Color), "Highlight")]
public Color SelectionRectangleBorderColor
{
get { return mSelectionRectangleBorderColor; }
set { mSelectionRectangleBorderColor = value; }
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the ImageListViewColor class.
/// </summary>
public ImageListViewColor()
{
// control
mControlBackColor = SystemColors.Window;
mDisabledBackColor = SystemColors.Control;
// item
mBackColor = SystemColors.Window;
mForeColor = SystemColors.ControlText;
mBorderColor = Color.FromArgb(64, SystemColors.GrayText);
mUnFocusedColor1 = Color.FromArgb(16, SystemColors.GrayText);
mUnFocusedColor2 = Color.FromArgb(64, SystemColors.GrayText);
mUnFocusedBorderColor = Color.FromArgb(128, SystemColors.GrayText);
mUnFocusedForeColor = SystemColors.ControlText;
mHoverColor1 = Color.FromArgb(8, SystemColors.Highlight);
mHoverColor2 = Color.FromArgb(64, SystemColors.Highlight);
mHoverBorderColor = Color.FromArgb(64, SystemColors.Highlight);
mSelectedColor1 = Color.FromArgb(16, SystemColors.Highlight);
mSelectedColor2 = Color.FromArgb(128, SystemColors.Highlight);
mSelectedBorderColor = Color.FromArgb(128, SystemColors.Highlight);
mSelectedForeColor = SystemColors.ControlText;
mDisabledColor1 = Color.FromArgb(0, SystemColors.GrayText);
mDisabledColor2 = Color.FromArgb(32, SystemColors.GrayText);
mDisabledBorderColor = Color.FromArgb(32, SystemColors.GrayText);
mDisabledForeColor = Color.FromArgb(128, 128, 128);
mInsertionCaretColor = SystemColors.Highlight;
// thumbnails
mImageInnerBorderColor = Color.FromArgb(128, Color.White);
mImageOuterBorderColor = Color.FromArgb(128, Color.Gray);
// details view
mColumnHeaderBackColor1 = Color.FromArgb(32, SystemColors.Control);
mColumnHeaderBackColor2 = Color.FromArgb(196, SystemColors.Control);
mColumnHeaderHoverColor1 = Color.FromArgb(16, SystemColors.Highlight);
mColumnHeaderHoverColor2 = Color.FromArgb(64, SystemColors.Highlight);
mColumnHeaderForeColor = SystemColors.WindowText;
mColumnSelectColor = Color.FromArgb(16, SystemColors.GrayText);
mColumnSeparatorColor = Color.FromArgb(32, SystemColors.GrayText);
mCellForeColor = SystemColors.ControlText;
mAlternateBackColor = SystemColors.Window;
mAlternateCellForeColor = SystemColors.ControlText;
// image pane
mPaneBackColor = Color.FromArgb(16, SystemColors.GrayText);
mPaneSeparatorColor = Color.FromArgb(128, SystemColors.GrayText);
mPaneLabelColor = Color.FromArgb(196, Color.Black);
// selection rectangle
mSelectionRectangleColor1 = Color.FromArgb(128, SystemColors.Highlight);
mSelectionRectangleColor2 = Color.FromArgb(128, SystemColors.Highlight);
mSelectionRectangleBorderColor = SystemColors.Highlight;
}
/// <summary>
/// Initializes a new instance of the ImageListViewColor class
/// from its string representation.
/// </summary>
/// <param name="definition">String representation of the object.</param>
public ImageListViewColor(string definition)
: this()
{
try
{
// First check if the color matches a predefined color setting
foreach (MemberInfo info in typeof(ImageListViewColor).GetMembers(BindingFlags.Static | BindingFlags.Public))
{
if (info.MemberType == MemberTypes.Property)
{
PropertyInfo propertyInfo = (PropertyInfo)info;
if (propertyInfo.PropertyType == typeof(ImageListViewColor))
{
// If the color setting is equal to a preset value
// return the preset
if (definition == string.Format("({0})", propertyInfo.Name) ||
definition == propertyInfo.Name)
{
ImageListViewColor presetValue = (ImageListViewColor)propertyInfo.GetValue(null, null);
CopyFrom(presetValue);
return;
}
}
}
}
// Convert color values
foreach (string line in definition.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
// Read the color setting
string[] pair = line.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
string name = pair[0].Trim();
Color color = Color.FromName(pair[1].Trim());
// Set the property value
PropertyInfo property = typeof(ImageListViewColor).GetProperty(name);
property.SetValue(this, color, null);
}
}
catch
{
throw new ArgumentException("Invalid string format", "definition");
}
}
#endregion
#region Instance Methods
/// <summary>
/// Copies color values from the given object.
/// </summary>
/// <param name="source">The source object.</param>
public void CopyFrom(ImageListViewColor source)
{
foreach (PropertyInfo info in typeof(ImageListViewColor).GetProperties())
{
// Walk through color properties
if (info.PropertyType == typeof(Color))
{
Color color = (Color)info.GetValue(source, null);
info.SetValue(this, color, null);
}
}
}
#endregion
#region Static Members
/// <summary>
/// Represents the default color theme.
/// </summary>
public static ImageListViewColor Default { get { return ImageListViewColor.GetDefaultTheme(); } }
/// <summary>
/// Represents the noir color theme.
/// </summary>
public static ImageListViewColor Noir { get { return ImageListViewColor.GetNoirTheme(); } }
/// <summary>
/// Represents the mandarin color theme.
/// </summary>
public static ImageListViewColor Mandarin { get { return ImageListViewColor.GetMandarinTheme(); } }
/// <summary>
/// Sets the color palette to default colors.
/// </summary>
private static ImageListViewColor GetDefaultTheme()
{
return new ImageListViewColor();
}
/// <summary>
/// Sets the color palette to mandarin colors.
/// </summary>
private static ImageListViewColor GetMandarinTheme()
{
ImageListViewColor c = new ImageListViewColor();
// control
c.ControlBackColor = Color.White;
c.DisabledBackColor = Color.FromArgb(220, 220, 220);
// item
c.BackColor = Color.White;
c.ForeColor = Color.FromArgb(60, 60, 60);
c.BorderColor = Color.FromArgb(187, 190, 183);
c.UnFocusedColor1 = Color.FromArgb(235, 235, 235);
c.UnFocusedColor2 = Color.FromArgb(217, 217, 217);
c.UnFocusedBorderColor = Color.FromArgb(168, 169, 161);
c.UnFocusedForeColor = Color.FromArgb(40, 40, 40);
c.HoverColor1 = Color.Transparent;
c.HoverColor2 = Color.Transparent;
c.HoverBorderColor = Color.Transparent;
c.SelectedColor1 = Color.FromArgb(244, 125, 77);
c.SelectedColor2 = Color.FromArgb(235, 110, 60);
c.SelectedBorderColor = Color.FromArgb(240, 119, 70);
c.SelectedForeColor = Color.White;
c.DisabledColor1 = Color.FromArgb(217, 217, 217);
c.DisabledColor2 = Color.FromArgb(197, 197, 197);
c.DisabledBorderColor = Color.FromArgb(128, 128, 128);
c.DisabledForeColor = Color.FromArgb(128, 128, 128);
c.InsertionCaretColor = Color.FromArgb(240, 119, 70);
// thumbnails & pane
c.ImageInnerBorderColor = Color.Transparent;
c.ImageOuterBorderColor = Color.White;
// details view
c.CellForeColor = Color.FromArgb(60, 60, 60);
c.ColumnHeaderBackColor1 = Color.FromArgb(247, 247, 247);
c.ColumnHeaderBackColor2 = Color.FromArgb(235, 235, 235);
c.ColumnHeaderHoverColor1 = Color.White;
c.ColumnHeaderHoverColor2 = Color.FromArgb(245, 245, 245);
c.ColumnHeaderForeColor = Color.FromArgb(60, 60, 60);
c.ColumnSelectColor = Color.FromArgb(34, 128, 128, 128);
c.ColumnSeparatorColor = Color.FromArgb(106, 128, 128, 128);
c.mAlternateBackColor = Color.FromArgb(234, 234, 234);
c.mAlternateCellForeColor = Color.FromArgb(40, 40, 40);
// image pane
c.PaneBackColor = Color.White;
c.PaneSeparatorColor = Color.FromArgb(216, 216, 216);
c.PaneLabelColor = Color.FromArgb(156, 156, 156);
// selection rectangle
c.SelectionRectangleColor1 = Color.FromArgb(64, 240, 116, 68);
c.SelectionRectangleColor2 = Color.FromArgb(64, 240, 116, 68);
c.SelectionRectangleBorderColor = Color.FromArgb(240, 119, 70);
return c;
}
/// <summary>
/// Sets the color palette to noir colors.
/// </summary>
private static ImageListViewColor GetNoirTheme()
{
ImageListViewColor c = new ImageListViewColor();
// control
c.ControlBackColor = Color.Black;
c.DisabledBackColor = Color.Black;
// item
c.BackColor = Color.FromArgb(0x31, 0x31, 0x31);
c.ForeColor = Color.LightGray;
c.BorderColor = Color.DarkGray;
c.UnFocusedColor1 = Color.FromArgb(16, SystemColors.GrayText);
c.UnFocusedColor2 = Color.FromArgb(64, SystemColors.GrayText);
c.UnFocusedBorderColor = Color.FromArgb(128, SystemColors.GrayText);
c.UnFocusedForeColor = Color.LightGray;
c.HoverColor1 = Color.FromArgb(64, Color.White);
c.HoverColor2 = Color.FromArgb(16, Color.White);
c.HoverBorderColor = Color.FromArgb(64, SystemColors.Highlight);
c.SelectedColor1 = Color.FromArgb(64, 96, 160);
c.SelectedColor2 = Color.FromArgb(64, 64, 96, 160);
c.SelectedBorderColor = Color.FromArgb(128, SystemColors.Highlight);
c.SelectedForeColor = Color.LightGray;
c.DisabledColor1 = Color.FromArgb(0, SystemColors.GrayText);
c.DisabledColor2 = Color.FromArgb(32, SystemColors.GrayText);
c.DisabledBorderColor = Color.FromArgb(96, SystemColors.GrayText);
c.DisabledForeColor = Color.LightGray;
c.InsertionCaretColor = Color.FromArgb(96, 144, 240);
// thumbnails & pane
c.ImageInnerBorderColor = Color.FromArgb(128, Color.White);
c.ImageOuterBorderColor = Color.FromArgb(128, Color.Gray);
// details view
c.CellForeColor = Color.WhiteSmoke;
c.ColumnHeaderBackColor1 = Color.FromArgb(32, 128, 128, 128);
c.ColumnHeaderBackColor2 = Color.FromArgb(196, 128, 128, 128);
c.ColumnHeaderHoverColor1 = Color.FromArgb(64, 96, 144, 240);
c.ColumnHeaderHoverColor2 = Color.FromArgb(196, 96, 144, 240);
c.ColumnHeaderForeColor = Color.White;
c.ColumnSelectColor = Color.FromArgb(96, 128, 128, 128);
c.ColumnSeparatorColor = Color.Gold;
c.AlternateBackColor = Color.FromArgb(0x31, 0x31, 0x31);
c.AlternateCellForeColor = Color.WhiteSmoke;
// image pane
c.PaneBackColor = Color.FromArgb(0x31, 0x31, 0x31);
c.PaneSeparatorColor = Color.Gold;
c.PaneLabelColor = SystemColors.GrayText;
// selection rectangke
c.SelectionRectangleColor1 = Color.FromArgb(160, 96, 144, 240);
c.SelectionRectangleColor2 = Color.FromArgb(32, 96, 144, 240);
c.SelectionRectangleBorderColor = Color.FromArgb(64, 96, 144, 240);
return c;
}
#endregion
#region System.Object Overrides
/// <summary>
/// Determines whether all color values of the specified
/// ImageListViewColor are equal to this instance.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>true if the two instances have the same color values;
/// otherwise false.</returns>
public override bool Equals(object obj)
{
if (obj == null)
throw new NullReferenceException();
ImageListViewColor other = obj as ImageListViewColor;
if (other == null) return false;
foreach (PropertyInfo info in typeof(ImageListViewColor).GetProperties())
{
// Walk through color properties
if (info.PropertyType == typeof(Color))
{
// Compare colors
Color color1 = (Color)info.GetValue(this, null);
Color color2 = (Color)info.GetValue(other, null);
if (color1 != color2) return false;
}
}
return true;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in
/// hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Returns a string that represents this instance.
/// </summary>
/// <returns>
/// A string that represents this instance.
/// </returns>
public override string ToString()
{
ImageListViewColor colors = this;
// First check if the color matches a predefined color setting
foreach (MemberInfo info in typeof(ImageListViewColor).GetMembers(BindingFlags.Static | BindingFlags.Public))
{
if (info.MemberType == MemberTypes.Property)
{
PropertyInfo propertyInfo = (PropertyInfo)info;
if (propertyInfo.PropertyType == typeof(ImageListViewColor))
{
ImageListViewColor presetValue = (ImageListViewColor)propertyInfo.GetValue(null, null);
// If the color setting is equal to a preset value
// return the name of the preset
if (colors.Equals(presetValue))
return string.Format("({0})", propertyInfo.Name);
}
}
}
// Serialize all colors which are different from the default setting
List<string> lines = new List<string>();
foreach (PropertyInfo info in typeof(ImageListViewColor).GetProperties())
{
// Walk through color properties
if (info.PropertyType == typeof(Color))
{
// Get property name
string name = info.Name;
// Get the current value
Color color = (Color)info.GetValue(colors, null);
// Find the default value atribute
Attribute[] attributes = (Attribute[])info.GetCustomAttributes(typeof(DefaultValueAttribute), false);
if (attributes.Length != 0)
{
// Get the default value
DefaultValueAttribute attribute = (DefaultValueAttribute)attributes[0];
Color defaultColor = (Color)attribute.Value;
// Serialize only if colors are different
if (color != defaultColor)
{
lines.Add(string.Format("{0} = {1}", name, color.Name));
}
}
}
}
return string.Join("; ", lines.ToArray());
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for all Text-only Readers.
** Subclasses will include StreamReader & StringReader.
**
**
===========================================================*/
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO {
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
[Serializable]
[ComVisible(true)]
#if FEATURE_REMOTING
public abstract class TextReader : MarshalByRefObject, IDisposable {
#else // FEATURE_REMOTING
public abstract class TextReader : IDisposable {
#endif // FEATURE_REMOTING
[NonSerialized]
private static Func<object, string> _ReadLineDelegate = state => ((TextReader)state).ReadLine();
[NonSerialized]
private static Func<object, int> _ReadDelegate = state =>
{
Tuple<TextReader, char[], int, int> tuple = (Tuple<TextReader, char[], int, int>)state;
return tuple.Item1.Read(tuple.Item2, tuple.Item3, tuple.Item4);
};
public static readonly TextReader Null = new NullTextReader();
protected TextReader() {}
// Closes this TextReader and releases any system resources associated with the
// TextReader. Following a call to Close, any operations on the TextReader
// may raise exceptions.
//
// This default method is empty, but descendant classes can override the
// method to provide the appropriate functionality.
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
[Pure]
public virtual int Peek()
{
Contract.Ensures(Contract.Result<int>() >= -1);
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
Contract.Ensures(Contract.Result<int>() >= -1);
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(count));
Contract.EndContractBlock();
int n = 0;
do {
int ch = Read();
if (ch == -1) break;
buffer[index + n++] = (char)ch;
} while (n < count);
return n;
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual String ReadToEnd()
{
Contract.Ensures(Contract.Result<String>() != null);
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while((len=Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock([In, Out] char[] buffer, int index, int count)
{
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
int i, n = 0;
do {
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual String ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true) {
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n') Read();
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0) return sb.ToString();
return null;
}
#region Task based Async APIs
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<String> ReadLineAsync()
{
return Task<String>.Factory.StartNew(_ReadLineDelegate, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public async virtual Task<String> ReadToEndAsync()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while((len = await ReadAsyncInternal(chars, 0, chars.Length).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return ReadAsyncInternal(buffer, index, count);
}
internal virtual Task<int> ReadAsyncInternal(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - index >= count);
Tuple<TextReader, char[], int, int> tuple = new Tuple<TextReader, char[], int, int>(this, buffer, index, count);
return Task<int>.Factory.StartNew(_ReadDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return ReadBlockAsyncInternal(buffer, index, count);
}
[HostProtection(ExternalThreading=true)]
private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - index >= count);
int i, n = 0;
do
{
i = await ReadAsyncInternal(buffer, index + n, count - n).ConfigureAwait(false);
n += i;
} while (i > 0 && n < count);
return n;
}
#endregion
[HostProtection(Synchronization=true)]
public static TextReader Synchronized(TextReader reader)
{
if (reader==null)
throw new ArgumentNullException("reader");
Contract.Ensures(Contract.Result<TextReader>() != null);
Contract.EndContractBlock();
if (reader is SyncTextReader)
return reader;
return new SyncTextReader(reader);
}
[Serializable]
private sealed class NullTextReader : TextReader
{
public NullTextReader(){}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override String ReadLine()
{
return null;
}
}
[Serializable]
internal sealed class SyncTextReader : TextReader
{
internal TextReader _in;
internal SyncTextReader(TextReader t)
{
_in = t;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Close()
{
// So that any overriden Close() gets run
_in.Close();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing)
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_in).Dispose();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Peek()
{
return _in.Peek();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Read()
{
return _in.Read();
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Read([In, Out] char[] buffer, int index, int count)
{
return _in.Read(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int ReadBlock([In, Out] char[] buffer, int index, int count)
{
return _in.ReadBlock(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override String ReadLine()
{
return _in.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override String ReadToEnd()
{
return _in.ReadToEnd();
}
//
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadLineAsync()
{
return Task.FromResult(ReadLine());
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadToEndAsync()
{
return Task.FromResult(ReadToEnd());
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return Task.FromResult(ReadBlock(buffer, index, count));
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return Task.FromResult(Read(buffer, index, count));
}
}
}
}
| |
using System;
namespace Epi.Windows.Docking.Win32
{
internal enum HitTest
{
HTERROR = -2,
HTTRANSPARENT = -1,
HTNOWHERE = 0,
HTCLIENT = 1,
HTCAPTION = 2,
HTSYSMENU = 3,
HTGROWBOX = 4,
HTSIZE = 4,
HTMENU = 5,
HTHSCROLL = 6,
HTVSCROLL = 7,
HTMINBUTTON = 8,
HTMAXBUTTON = 9,
HTLEFT = 10,
HTRIGHT = 11,
HTTOP = 12,
HTTOPLEFT = 13,
HTTOPRIGHT = 14,
HTBOTTOM = 15,
HTBOTTOMLEFT = 16,
HTBOTTOMRIGHT = 17,
HTBORDER = 18,
HTREDUCE = 8,
HTZOOM = 9 ,
HTSIZEFIRST = 10,
HTSIZELAST = 17,
HTOBJECT = 19,
HTCLOSE = 20,
HTHELP = 21
}
internal enum Msgs
{
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUIT = 0x0012,
WM_QUERYOPEN = 0x0013,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_ENDSESSION = 0x0016,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = 0x001A,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_DELETEITEM = 0x002D,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_COMMNOTIFY = 0x0044 ,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_POWER = 0x0048,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_SYNCPAINT = 0x0088,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_KEYLAST = 0x0108,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_MENURBUTTONUP = 0x0122,
WM_MENUDRAG = 0x0123,
WM_MENUGETOBJECT = 0x0124,
WM_UNINITMENUPOPUP = 0x0125,
WM_MENUCOMMAND = 0x0126,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_MOUSEWHEEL = 0x020A,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_DEVICECHANGE = 0x0219,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_REQUEST = 0x0288,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = 0x8000,
WM_USER = 0x0400
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using log4net;
namespace OpenSim.Region.ScriptEngine.DotNetEngine
{
public class AppDomainManager
{
//
// This class does AppDomain handling and loading/unloading of
// scripts in it. It is instanced in "ScriptEngine" and controlled
// from "ScriptManager"
//
// 1. Create a new AppDomain if old one is full (or doesn't exist)
// 2. Load scripts into AppDomain
// 3. Unload scripts from AppDomain (stopping them and marking
// them as inactive)
// 4. Unload AppDomain completely when all scripts in it has stopped
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private int maxScriptsPerAppDomain = 1;
// Internal list of all AppDomains
private List<AppDomainStructure> appDomains =
new List<AppDomainStructure>();
// Structure to keep track of data around AppDomain
private class AppDomainStructure
{
// The AppDomain itself
public AppDomain CurrentAppDomain;
// Number of scripts loaded into AppDomain
public int ScriptsLoaded;
// Number of dead scripts
public int ScriptsWaitingUnload;
}
// Current AppDomain
private AppDomainStructure currentAD;
private object getLock = new object(); // Mutex
private object freeLock = new object(); // Mutex
private ScriptEngine m_scriptEngine;
//public AppDomainManager(ScriptEngine scriptEngine)
public AppDomainManager(ScriptEngine scriptEngine)
{
m_scriptEngine = scriptEngine;
ReadConfig();
}
public void ReadConfig()
{
maxScriptsPerAppDomain = m_scriptEngine.ScriptConfigSource.GetInt(
"ScriptsPerAppDomain", 1);
}
// Find a free AppDomain, creating one if necessary
private AppDomainStructure GetFreeAppDomain()
{
lock (getLock)
{
// Current full?
if (currentAD != null &&
currentAD.ScriptsLoaded >= maxScriptsPerAppDomain)
{
// Add it to AppDomains list and empty current
appDomains.Add(currentAD);
currentAD = null;
}
// No current
if (currentAD == null)
{
// Create a new current AppDomain
currentAD = new AppDomainStructure();
currentAD.CurrentAppDomain = PrepareNewAppDomain();
}
return currentAD;
}
}
private int AppDomainNameCount;
// Create and prepare a new AppDomain for scripts
private AppDomain PrepareNewAppDomain()
{
// Create and prepare a new AppDomain
AppDomainNameCount++;
// TODO: Currently security match current appdomain
// Construct and initialize settings for a second AppDomain.
AppDomainSetup ads = new AppDomainSetup();
ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
ads.DisallowBindingRedirects = true;
ads.DisallowCodeDownload = true;
ads.LoaderOptimization = LoaderOptimization.MultiDomainHost;
ads.ShadowCopyFiles = "false"; // Disable shadowing
ads.ConfigurationFile =
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
AppDomain AD = AppDomain.CreateDomain("ScriptAppDomain_" +
AppDomainNameCount, null, ads);
m_log.Info("[" + m_scriptEngine.ScriptEngineName +
"]: AppDomain Loading: " +
AssemblyName.GetAssemblyName(
"OpenSim.Region.ScriptEngine.Shared.dll").ToString());
AD.Load(AssemblyName.GetAssemblyName(
"OpenSim.Region.ScriptEngine.Shared.dll"));
// Return the new AppDomain
return AD;
}
// Unload appdomains that are full and have only dead scripts
private void UnloadAppDomains()
{
lock (freeLock)
{
// Go through all
foreach (AppDomainStructure ads in new ArrayList(appDomains))
{
// Don't process current AppDomain
if (ads.CurrentAppDomain != currentAD.CurrentAppDomain)
{
// Not current AppDomain
// Is number of unloaded bigger or equal to number of loaded?
if (ads.ScriptsLoaded <= ads.ScriptsWaitingUnload)
{
// Remove from internal list
appDomains.Remove(ads);
// Unload
AppDomain.Unload(ads.CurrentAppDomain);
}
}
}
}
}
public IScript LoadScript(string FileName, out AppDomain ad)
{
// Find next available AppDomain to put it in
AppDomainStructure FreeAppDomain = GetFreeAppDomain();
IScript mbrt = (IScript)
FreeAppDomain.CurrentAppDomain.CreateInstanceFromAndUnwrap(
FileName, "SecondLife.Script");
FreeAppDomain.ScriptsLoaded++;
ad = FreeAppDomain.CurrentAppDomain;
return mbrt;
}
// Increase "dead script" counter for an AppDomain
public void StopScript(AppDomain ad)
{
lock (freeLock)
{
// Check if it is current AppDomain
if (currentAD.CurrentAppDomain == ad)
{
// Yes - increase
currentAD.ScriptsWaitingUnload++;
return;
}
// Lopp through all AppDomains
foreach (AppDomainStructure ads in new ArrayList(appDomains))
{
if (ads.CurrentAppDomain == ad)
{
// Found it
ads.ScriptsWaitingUnload++;
break;
}
}
}
UnloadAppDomains(); // Outsite lock, has its own GetLock
}
// If set to true then threads and stuff should try
// to make a graceful exit
public bool PleaseShutdown
{
get { return _PleaseShutdown; }
set { _PleaseShutdown = value; }
}
private bool _PleaseShutdown = false;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Omnius.Base;
namespace Omnius.Collections
{
public class VolatileHashDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable, ISynchronized
{
private Dictionary<TKey, Info<TValue>> _dic;
private readonly TimeSpan _survivalTime;
private readonly object _lockObject = new object();
public VolatileHashDictionary(TimeSpan survivalTime)
{
_dic = new Dictionary<TKey, Info<TValue>>();
_survivalTime = survivalTime;
}
public VolatileHashDictionary(TimeSpan survivalTime, IEqualityComparer<TKey> comparer)
{
_dic = new Dictionary<TKey, Info<TValue>>(comparer);
_survivalTime = survivalTime;
}
public TimeSpan SurvivalTime
{
get
{
return _survivalTime;
}
}
public KeyValuePair<TKey, TValue>[] ToArray()
{
lock (this.LockObject)
{
var list = new List<KeyValuePair<TKey, TValue>>(_dic.Count);
foreach (var (key, info) in _dic)
{
list.Add(new KeyValuePair<TKey, TValue>(key, info.Value));
}
return list.ToArray();
}
}
public KeyValuePair<TKey, TValue>[] ToArray(TimeSpan span)
{
var now = DateTime.UtcNow;
lock (this.LockObject)
{
var list = new List<KeyValuePair<TKey, TValue>>(_dic.Count);
foreach (var (key, info) in _dic)
{
if ((now - info.UpdateTime) < span)
{
list.Add(new KeyValuePair<TKey, TValue>(key, info.Value));
}
}
return list.ToArray();
}
}
public void Update()
{
var now = DateTime.UtcNow;
lock (this.LockObject)
{
List<TKey> list = null;
foreach (var (key, info) in _dic)
{
if ((now - info.UpdateTime) > _survivalTime)
{
if (list == null)
list = new List<TKey>();
list.Add(key);
}
}
if (list != null)
{
foreach (var key in list)
{
_dic.Remove(key);
}
}
}
}
public TimeSpan GetElapsedTime(TKey key)
{
if (!_dic.TryGetValue(key, out var info)) return _survivalTime;
var now = DateTime.UtcNow;
return (now - info.UpdateTime);
}
public VolatileKeyCollection Keys
{
get
{
lock (this.LockObject)
{
return new VolatileKeyCollection(_dic.Keys, this.LockObject);
}
}
}
public VolatileValueCollection Values
{
get
{
lock (this.LockObject)
{
return new VolatileValueCollection(_dic.Values, this.LockObject);
}
}
}
public IEqualityComparer<TKey> Comparer
{
get
{
lock (this.LockObject)
{
return _dic.Comparer;
}
}
}
public int Count
{
get
{
lock (this.LockObject)
{
return _dic.Count;
}
}
}
public TValue this[TKey key]
{
get
{
lock (this.LockObject)
{
var info = _dic[key];
info.UpdateTime = DateTime.UtcNow;
return info.Value;
}
}
set
{
lock (this.LockObject)
{
_dic[key] = new Info<TValue>() { Value = value, UpdateTime = DateTime.UtcNow };
}
}
}
public bool Add(TKey key, TValue value)
{
lock (this.LockObject)
{
int count = _dic.Count;
_dic[key] = new Info<TValue>() { Value = value, UpdateTime = DateTime.UtcNow };
return (count != _dic.Count);
}
}
public void Clear()
{
lock (this.LockObject)
{
_dic.Clear();
}
}
public bool ContainsKey(TKey key)
{
lock (this.LockObject)
{
return _dic.ContainsKey(key);
}
}
public bool ContainsValue(TValue value)
{
lock (this.LockObject)
{
return _dic.Values.Select(n => n.Value).Contains(value);
}
}
public bool Remove(TKey key)
{
lock (this.LockObject)
{
return _dic.Remove(key);
}
}
public bool TryGetValue(TKey key, out TValue value)
{
lock (this.LockObject)
{
if (_dic.TryGetValue(key, out var info))
{
info.UpdateTime = DateTime.UtcNow;
value = info.Value;
return true;
}
else
{
value = default;
return false;
}
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
lock (this.LockObject)
{
return this.Keys;
}
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
lock (this.LockObject)
{
return this.Values;
}
}
}
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
lock (this.LockObject)
{
this.Add(key, value);
}
}
bool IDictionary.IsFixedSize
{
get
{
lock (this.LockObject)
{
return false;
}
}
}
bool IDictionary.IsReadOnly
{
get
{
lock (this.LockObject)
{
return false;
}
}
}
ICollection IDictionary.Keys
{
get
{
lock (this.LockObject)
{
return (ICollection)this.Keys;
}
}
}
ICollection IDictionary.Values
{
get
{
lock (this.LockObject)
{
return (ICollection)this.Values;
}
}
}
object IDictionary.this[object key]
{
get
{
lock (this.LockObject)
{
return this[(TKey)key];
}
}
set
{
lock (this.LockObject)
{
this[(TKey)key] = (TValue)value;
}
}
}
void IDictionary.Add(object key, object value)
{
lock (this.LockObject)
{
this.Add((TKey)key, (TValue)value);
}
}
bool IDictionary.Contains(object key)
{
lock (this.LockObject)
{
return this.ContainsKey((TKey)key);
}
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
lock (this.LockObject)
{
return _dic.GetEnumerator();
}
}
void IDictionary.Remove(object key)
{
lock (this.LockObject)
{
this.Remove((TKey)key);
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get
{
lock (this.LockObject)
{
return false;
}
}
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
lock (this.LockObject)
{
this.Add(item.Key, item.Value);
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
lock (this.LockObject)
{
var keyComparer = EqualityComparer<TKey>.Default;
var valueComparer = EqualityComparer<TValue>.Default;
foreach (var (key, info) in _dic)
{
if (keyComparer.Equals(item.Key, key)
&& valueComparer.Equals(item.Value, info.Value))
{
return true;
}
}
return false;
}
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
lock (this.LockObject)
{
foreach (var (key, info) in _dic)
{
array.SetValue(new KeyValuePair<TKey, TValue>(key, info.Value), arrayIndex++);
}
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
lock (this.LockObject)
{
var keyComparer = EqualityComparer<TKey>.Default;
var valueComparer = EqualityComparer<TValue>.Default;
bool flag = false;
foreach (var (key, info) in _dic)
{
if (keyComparer.Equals(keyValuePair.Key, key)
&& valueComparer.Equals(keyValuePair.Value, info.Value))
{
_dic.Remove(key);
flag = true;
}
}
return flag;
}
}
bool ICollection.IsSynchronized
{
get
{
lock (this.LockObject)
{
return true;
}
}
}
object ICollection.SyncRoot
{
get
{
return this.LockObject;
}
}
void ICollection.CopyTo(Array array, int index)
{
lock (this.LockObject)
{
foreach (var (key, info) in _dic)
{
array.SetValue(new KeyValuePair<TKey, TValue>(key, info.Value), index++);
}
}
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
lock (this.LockObject)
{
foreach (var (key, info) in _dic)
{
yield return new KeyValuePair<TKey, TValue>(key, info.Value);
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
lock (this.LockObject)
{
return this.GetEnumerator();
}
}
internal struct Info<T>
{
public T Value { get; set; }
public DateTime UpdateTime { get; set; }
}
public sealed class VolatileKeyCollection : ICollection<TKey>, IEnumerable<TKey>, ICollection, IEnumerable, ISynchronized
{
private ICollection<TKey> _collection;
private readonly object _lockObject;
internal VolatileKeyCollection(ICollection<TKey> collection, object lockObject)
{
_collection = collection;
_lockObject = lockObject;
}
public TKey[] ToArray()
{
lock (this.LockObject)
{
var array = new TKey[_collection.Count];
_collection.CopyTo(array, 0);
return array;
}
}
public void CopyTo(TKey[] array, int arrayIndex)
{
lock (this.LockObject)
{
_collection.CopyTo(array, arrayIndex);
}
}
public int Count
{
get
{
lock (this.LockObject)
{
return _collection.Count;
}
}
}
bool ICollection<TKey>.IsReadOnly
{
get
{
lock (this.LockObject)
{
return true;
}
}
}
void ICollection<TKey>.Add(TKey item)
{
lock (this.LockObject)
{
throw new NotSupportedException();
}
}
void ICollection<TKey>.Clear()
{
lock (this.LockObject)
{
throw new NotSupportedException();
}
}
bool ICollection<TKey>.Contains(TKey item)
{
lock (this.LockObject)
{
return _collection.Contains(item);
}
}
bool ICollection<TKey>.Remove(TKey item)
{
lock (this.LockObject)
{
throw new NotSupportedException();
}
}
bool ICollection.IsSynchronized
{
get
{
lock (this.LockObject)
{
return true;
}
}
}
object ICollection.SyncRoot
{
get
{
return this.LockObject;
}
}
void ICollection.CopyTo(Array array, int index)
{
lock (this.LockObject)
{
((ICollection)_collection).CopyTo(array, index);
}
}
public IEnumerator<TKey> GetEnumerator()
{
lock (this.LockObject)
{
foreach (var item in _collection)
{
yield return item;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
lock (this.LockObject)
{
return this.GetEnumerator();
}
}
#region IThisLock
public object LockObject
{
get
{
return _lockObject;
}
}
#endregion
}
public sealed class VolatileValueCollection : ICollection<TValue>, IEnumerable<TValue>, ICollection, IEnumerable, ISynchronized
{
private ICollection<Info<TValue>> _collection;
private readonly object _lockObject;
internal VolatileValueCollection(ICollection<Info<TValue>> collection, object lockObject)
{
_collection = collection;
_lockObject = lockObject;
}
public TValue[] ToArray()
{
lock (this.LockObject)
{
return _collection.Select(n => n.Value).ToArray();
}
}
public void CopyTo(TValue[] array, int arrayIndex)
{
lock (this.LockObject)
{
foreach (var info in _collection)
{
array[arrayIndex++] = info.Value;
}
}
}
public int Count
{
get
{
lock (this.LockObject)
{
return _collection.Count;
}
}
}
bool ICollection<TValue>.IsReadOnly
{
get
{
lock (this.LockObject)
{
return true;
}
}
}
void ICollection<TValue>.Add(TValue item)
{
lock (this.LockObject)
{
throw new NotSupportedException();
}
}
void ICollection<TValue>.Clear()
{
lock (this.LockObject)
{
throw new NotSupportedException();
}
}
bool ICollection<TValue>.Contains(TValue item)
{
lock (this.LockObject)
{
return _collection.Select(n => n.Value).Contains(item);
}
}
bool ICollection<TValue>.Remove(TValue item)
{
lock (this.LockObject)
{
throw new NotSupportedException();
}
}
bool ICollection.IsSynchronized
{
get
{
lock (this.LockObject)
{
return true;
}
}
}
object ICollection.SyncRoot
{
get
{
return this.LockObject;
}
}
void ICollection.CopyTo(Array array, int index)
{
lock (this.LockObject)
{
((ICollection)_collection).CopyTo(array, index);
}
}
public IEnumerator<TValue> GetEnumerator()
{
lock (this.LockObject)
{
foreach (var info in _collection)
{
yield return info.Value;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
lock (this.LockObject)
{
return this.GetEnumerator();
}
}
#region IThisLock
public object LockObject
{
get
{
return _lockObject;
}
}
#endregion
}
#region IThisLock
public object LockObject
{
get
{
return _lockObject;
}
}
#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;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.World.Estate
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XEstate")]
public class XEstateModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected List<Scene> m_Scenes = new List<Scene>();
protected bool m_InInfoUpdate = false;
public bool InInfoUpdate
{
get { return m_InInfoUpdate; }
set { m_InInfoUpdate = value; }
}
public List<Scene> Scenes
{
get { return m_Scenes; }
}
protected EstateConnector m_EstateConnector;
public void Initialise(IConfigSource config)
{
int port = 0;
IConfig estateConfig = config.Configs["Estate"];
if (estateConfig != null)
{
port = estateConfig.GetInt("Port", 0);
}
m_EstateConnector = new EstateConnector(this);
// Instantiate the request handler
IHttpServer server = MainServer.GetHttpServer((uint)port);
server.AddStreamHandler(new EstateRequestHandler(this));
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
lock (m_Scenes)
m_Scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
}
public void RegionLoaded(Scene scene)
{
IEstateModule em = scene.RequestModuleInterface<IEstateModule>();
em.OnRegionInfoChange += OnRegionInfoChange;
em.OnEstateInfoChange += OnEstateInfoChange;
em.OnEstateMessage += OnEstateMessage;
}
public void RemoveRegion(Scene scene)
{
scene.EventManager.OnNewClient -= OnNewClient;
lock (m_Scenes)
m_Scenes.Remove(scene);
}
public string Name
{
get { return "EstateModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
private Scene FindScene(UUID RegionID)
{
foreach (Scene s in Scenes)
{
if (s.RegionInfo.RegionID == RegionID)
return s;
}
return null;
}
private void OnRegionInfoChange(UUID RegionID)
{
Scene s = FindScene(RegionID);
if (s == null)
return;
if (!m_InInfoUpdate)
m_EstateConnector.SendUpdateCovenant(s.RegionInfo.EstateSettings.EstateID, s.RegionInfo.RegionSettings.Covenant);
}
private void OnEstateInfoChange(UUID RegionID)
{
Scene s = FindScene(RegionID);
if (s == null)
return;
if (!m_InInfoUpdate)
m_EstateConnector.SendUpdateEstate(s.RegionInfo.EstateSettings.EstateID);
}
private void OnEstateMessage(UUID RegionID, UUID FromID, string FromName, string Message)
{
Scene senderScenes = FindScene(RegionID);
if (senderScenes == null)
return;
uint estateID = senderScenes.RegionInfo.EstateSettings.EstateID;
foreach (Scene s in Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == estateID)
{
IDialogModule dm = s.RequestModuleInterface<IDialogModule>();
if (dm != null)
{
dm.SendNotificationToUsersInRegion(FromID, FromName,
Message);
}
}
}
if (!m_InInfoUpdate)
m_EstateConnector.SendEstateMessage(estateID, FromID, FromName, Message);
}
private void OnNewClient(IClientAPI client)
{
client.OnEstateTeleportOneUserHomeRequest += OnEstateTeleportOneUserHomeRequest;
client.OnEstateTeleportAllUsersHomeRequest += OnEstateTeleportAllUsersHomeRequest;
}
private void OnEstateTeleportOneUserHomeRequest(IClientAPI client, UUID invoice, UUID senderID, UUID prey)
{
if (prey == UUID.Zero)
return;
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
uint estateID = scene.RegionInfo.EstateSettings.EstateID;
if (!scene.Permissions.CanIssueEstateCommand(client.AgentId, false))
return;
foreach (Scene s in Scenes)
{
if (s == scene)
continue; // Already handles by estate module
if (s.RegionInfo.EstateSettings.EstateID != estateID)
continue;
ScenePresence p = scene.GetScenePresence(prey);
if (p != null && !p.IsChildAgent)
{
p.ControllingClient.SendTeleportStart(16);
scene.TeleportClientHome(prey, p.ControllingClient);
}
}
m_EstateConnector.SendTeleportHomeOneUser(estateID, prey);
}
private void OnEstateTeleportAllUsersHomeRequest(IClientAPI client, UUID invoice, UUID senderID)
{
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
uint estateID = scene.RegionInfo.EstateSettings.EstateID;
if (!scene.Permissions.CanIssueEstateCommand(client.AgentId, false))
return;
foreach (Scene s in Scenes)
{
if (s == scene)
continue; // Already handles by estate module
if (s.RegionInfo.EstateSettings.EstateID != estateID)
continue;
scene.ForEachScenePresence(delegate(ScenePresence p) {
if (p != null && !p.IsChildAgent)
{
p.ControllingClient.SendTeleportStart(16);
scene.TeleportClientHome(p.ControllingClient.AgentId, p.ControllingClient);
}
});
}
m_EstateConnector.SendTeleportHomeAllUsers(estateID);
}
}
}
| |
//+-----------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (C) Microsoft Corporation
//
// File: TextFormatterContext.cs
//
// Contents: Implementation of TextFormatter context
//
// Created: 9-1-2001 Worachai Chaoweeraprasit (wchao)
//
//------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Threading;
using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media;
using MS.Internal;
using MS.Internal.PresentationCore;
using MS.Internal.TextFormatting;
using IndexedGlyphRun = System.Windows.Media.TextFormatting.IndexedGlyphRun;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media.TextFormatting
{
/// <summary>
/// TextFormatter context. This class encapsulates the unit of reentrancy of TextFormatter.
/// </summary>
/// <remarks>
/// We do not want to make this class finalizable because its lifetime already ties
/// to TextFormatterImp which is finalizable. It is not efficient to have too many
/// finalizable object around in the GC heap.
/// </remarks>
#if OPTIMALBREAK_API
public class TextFormatterContext
#else
[FriendAccessAllowed] // used by Framework
internal class TextFormatterContext
#endif
{
private SecurityCriticalDataForSet<IntPtr> _ploc; // Line Services context
private LineServicesCallbacks _callbacks; // object to hold all delegates for callback
private State _state; // internal state flags
private BreakStrategies _breaking; // context's breaking strategy
/// <SecurityNote>
/// Critical - as this calls the constructor for SecurityCriticalDataForSet.
/// Safe - as this just initializes it with the default value.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public TextFormatterContext()
{
_ploc = new SecurityCriticalDataForSet<IntPtr>(IntPtr.Zero);
Init();
}
/// <SecurityNote>
/// Critical - as this calls Critical functions - LoCreateContext, setter for _ploc.Value,
/// Safe - as this doesn't take any random parameters that can be passed along
/// and cause random memory to be written to.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void Init()
{
if(_ploc.Value == System.IntPtr.Zero)
{
// Initializing context
LsErr lserr = LsErr.None;
LsContextInfo contextInfo = new LsContextInfo();
LscbkRedefined lscbkRedef = new LscbkRedefined();
_callbacks = new LineServicesCallbacks();
_callbacks.PopulateContextInfo(ref contextInfo, ref lscbkRedef);
contextInfo.version = 4; // we should set this right, they might check it in the future
contextInfo.pols = IntPtr.Zero; // This will be filled in the un-managed code
contextInfo.cEstimatedCharsPerLine = TextStore.TypicalCharactersPerLine;
contextInfo.fDontReleaseRuns = 1; // dont waste time
// There are 3 justification priorities right now with one considered good
// and the other two provided for emergency expansion.
// Future development to enable international justification will likely change this.
// e.g. Kashida justification would require more than one good priorities.
contextInfo.cJustPriorityLim = 3;
// Fill up text configuration
contextInfo.wchNull = '\u0000';
contextInfo.wchUndef = '\u0001';
contextInfo.wchTab = '\u0009';
contextInfo.wchPosTab = contextInfo.wchUndef;
contextInfo.wchEndPara1 = TextStore.CharParaSeparator; // Unicode para separator
contextInfo.wchEndPara2 = contextInfo.wchUndef;
contextInfo.wchSpace = '\u0020';
contextInfo.wchHyphen = MS.Internal.Text.TextInterface.TextAnalyzer.CharHyphen; //'\x002d';
contextInfo.wchNonReqHyphen = '\u00AD';
contextInfo.wchNonBreakHyphen = '\u2011';
contextInfo.wchEnDash = '\u2013';
contextInfo.wchEmDash = '\u2014';
contextInfo.wchEnSpace = '\u2002';
contextInfo.wchEmSpace = '\u2003';
contextInfo.wchNarrowSpace = '\u2009';
contextInfo.wchJoiner = '\u200D';
contextInfo.wchNonJoiner = '\u200C';
contextInfo.wchVisiNull = '\u2050';
contextInfo.wchVisiAltEndPara = '\u2051';
contextInfo.wchVisiEndLineInPara = '\u2052';
contextInfo.wchVisiEndPara = '\u2053';
contextInfo.wchVisiSpace = '\u2054';
contextInfo.wchVisiNonBreakSpace = '\u2055';
contextInfo.wchVisiNonBreakHyphen = '\u2056';
contextInfo.wchVisiNonReqHyphen = '\u2057';
contextInfo.wchVisiTab = '\u2058';
contextInfo.wchVisiPosTab = contextInfo.wchUndef;
contextInfo.wchVisiEmSpace = '\u2059';
contextInfo.wchVisiEnSpace = '\u205A';
contextInfo.wchVisiNarrowSpace = '\u205B';
contextInfo.wchVisiOptBreak = '\u205C';
contextInfo.wchVisiNoBreak = '\u205D';
contextInfo.wchVisiFESpace = '\u205E';
contextInfo.wchFESpace = '\u3000';
contextInfo.wchEscAnmRun = TextStore.CharParaSeparator;
contextInfo.wchAltEndPara = contextInfo.wchUndef;
contextInfo.wchEndLineInPara = TextStore.CharLineSeparator;
contextInfo.wchSectionBreak = contextInfo.wchUndef;
contextInfo.wchNonBreakSpace = '\u00A0';
contextInfo.wchNoBreak = contextInfo.wchUndef;
contextInfo.wchColumnBreak = contextInfo.wchUndef;
contextInfo.wchPageBreak = contextInfo.wchUndef;
contextInfo.wchOptBreak = contextInfo.wchUndef;
contextInfo.wchToReplace = contextInfo.wchUndef;
contextInfo.wchReplace = contextInfo.wchUndef;
IntPtr ploc = IntPtr.Zero;
IntPtr ppenaltyModule = IntPtr.Zero;
lserr = UnsafeNativeMethods.LoCreateContext(
ref contextInfo,
ref lscbkRedef,
out ploc
);
if (lserr != LsErr.None)
{
ThrowExceptionFromLsError(SR.Get(SRID.CreateContextFailure, lserr), lserr);
}
_ploc.Value = ploc;
GC.KeepAlive(contextInfo);
// There is a trick here to pass in this resolution as in twips
// (1/1440 an inch).
//
// LSCreateLine assumes the max width passed in is in twips so to
// allow its client to express their width in page unit. However
// it asks client to set up the real device resolution here so
// that it can internally translate the "twips" width into client
// actual device unit.
//
// We are not device dependent anyway, so instead of following the
// rule which will cause us to validate the context every time. We
// choose to cheat LS to think that our unit is twips.
//
LsDevRes devRes;
devRes.dxpInch = devRes.dxrInch = TwipsPerInch;
devRes.dypInch = devRes.dyrInch = TwipsPerInch;
SetDoc(
true, // Yes, we will be displaying
true, // Yes, reference and presentation are the same device
ref devRes // Device resolutions
);
SetBreaking(BreakStrategies.BreakCJK);
}
}
/// <summary>
/// Client to get the text penalty module.
/// </summary>
internal TextPenaltyModule GetTextPenaltyModule()
{
Invariant.Assert(_ploc.Value != System.IntPtr.Zero);
return new TextPenaltyModule(_ploc);
}
/// <summary>
/// Unclaim the ownership of the context, release it back to the context pool
/// </summary>
/// <SecurityNote>
/// Critical - this sets exception and owner which are critical
/// </SecurityNote>
[SecurityCritical]
internal void Release()
{
this.CallbackException = null;
this.Owner = null;
}
/// <summary>
/// context's owner
/// </summary>
/// <SecurityNote>
/// Critical - Owner object is critical
/// </SecurityNote>
internal object Owner
{
[SecurityCritical]
get { return _callbacks.Owner; }
[SecurityCritical]
set { _callbacks.Owner = value; }
}
/// <summary>
/// Exception thrown during LS callback
/// </summary>
/// <SecurityNote>
/// Critical - Exception and its message are critical
/// </SecurityNote>
internal Exception CallbackException
{
[SecurityCritical]
get { return _callbacks.Exception; }
[SecurityCritical]
set { _callbacks.Exception = value; }
}
/// <summary>
/// Make min/max empty
/// </summary>
internal void EmptyBoundingBox()
{
_callbacks.EmptyBoundingBox();
}
/// <summary>
/// Bounding box of whole black of line
/// </summary>
internal Rect BoundingBox
{
get { return _callbacks.BoundingBox; }
}
/// <summary>
/// Clear the indexed glyphruns
/// </summary>
internal void ClearIndexedGlyphRuns()
{
_callbacks.ClearIndexedGlyphRuns();
}
/// <summary>
/// Indexed glyphruns of the line
/// </summary>
internal ICollection<IndexedGlyphRun> IndexedGlyphRuns
{
get { return _callbacks.IndexedGlyphRuns; }
}
/// <summary>
/// Destroy LS context
/// </summary>
/// <SecurityNote>
/// Critical - as this calls Critical function LoDestroyContext.
/// Safe - as this can't be used pass in arbitrary parameters.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal void Destroy()
{
if(_ploc.Value != System.IntPtr.Zero)
{
UnsafeNativeMethods.LoDestroyContext(_ploc.Value);
_ploc.Value = IntPtr.Zero;
}
}
/// <summary>
/// Set LS breaking strategy
/// </summary>
/// <SecurityNote>
/// Critical - as this calls LoSetBreaking which is a Crtical function.
/// Safe - as this doesn't take any parameters that are passed on without validation.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal void SetBreaking(BreakStrategies breaking)
{
if (_state == State.Uninitialized || breaking != _breaking)
{
Invariant.Assert(_ploc.Value != System.IntPtr.Zero);
LsErr lserr = UnsafeNativeMethods.LoSetBreaking(_ploc.Value, (int) breaking);
if (lserr != LsErr.None)
{
ThrowExceptionFromLsError(SR.Get(SRID.SetBreakingFailure, lserr), lserr);
}
_breaking = breaking;
}
_state = State.Initialized;
}
//
// Line Services managed API
//
//
/// <SecurityNote>
/// Critical - as this calls Critical function LoCreateLine.
/// Safe - as this can't be used to pass in arbitrary pointer parameters
/// that can be written to.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal LsErr CreateLine(
int cpFirst,
int lineLength,
int maxWidth,
LineFlags lineFlags,
IntPtr previousLineBreakRecord,
out IntPtr ploline,
out LsLInfo plslineInfo,
out int maxDepth,
out LsLineWidths lineWidths
)
{
Invariant.Assert(_ploc.Value != System.IntPtr.Zero);
return UnsafeNativeMethods.LoCreateLine(
_ploc.Value,
cpFirst,
lineLength,
maxWidth,
(uint)lineFlags, // line flags
previousLineBreakRecord,
out plslineInfo,
out ploline,
out maxDepth,
out lineWidths
);
}
/// <SecurityNote>
/// Critical - as it calls into unsafe function LoCreateBreaks
/// Safe - as this can't be used to pass in arbitrary pointer parameters
/// that can be written to.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal LsErr CreateBreaks(
int cpFirst,
IntPtr previousLineBreakRecord,
IntPtr ploparabreak,
IntPtr ptslinevariantRestriction,
ref LsBreaks lsbreaks,
out int bestFitIndex
)
{
Invariant.Assert(_ploc.Value != System.IntPtr.Zero);
return UnsafeNativeMethods.LoCreateBreaks(
_ploc.Value,
cpFirst,
previousLineBreakRecord,
ploparabreak,
ptslinevariantRestriction,
ref lsbreaks,
out bestFitIndex
);
}
/// <SecurityNote>
/// Critical - as it calls into unsafe function LoCreateParaBreakingSession
/// Safe - as this can't be used to pass in arbitrary pointer parameters
/// that can be written to.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal LsErr CreateParaBreakingSession(
int cpFirst,
int maxWidth,
IntPtr previousLineBreakRecord,
ref IntPtr ploparabreak,
ref bool penalizedAsJustified
)
{
Invariant.Assert(_ploc.Value != System.IntPtr.Zero);
return UnsafeNativeMethods.LoCreateParaBreakingSession(
_ploc.Value,
cpFirst,
maxWidth,
previousLineBreakRecord,
ref ploparabreak,
ref penalizedAsJustified
);
}
/// <SecurityNote>
/// Critical - as this call LoSetDoc which is a Critical function. It doesn't
/// pass any IntPtrs directly without validation.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal void SetDoc(
bool isDisplay,
bool isReferencePresentationEqual,
ref LsDevRes deviceInfo
)
{
Invariant.Assert(_ploc.Value != System.IntPtr.Zero);
LsErr lserr = UnsafeNativeMethods.LoSetDoc(
_ploc.Value,
isDisplay ? 1 : 0,
isReferencePresentationEqual ? 1 : 0,
ref deviceInfo
);
if(lserr != LsErr.None)
{
ThrowExceptionFromLsError(SR.Get(SRID.SetDocFailure, lserr), lserr);
}
}
/// <SecurityNote>
/// Critical - as this calls LoSetTabs which is a Critical function. This
/// is not safe as this takes tabStopCount parameter, a random
/// value of which could cause data to written past the array pointed
/// to by tabStops.
/// </SecurityNote>
[SecurityCritical]
internal unsafe void SetTabs(
int incrementalTab,
LsTbd* tabStops,
int tabStopCount
)
{
Invariant.Assert(_ploc.Value != System.IntPtr.Zero);
LsErr lserr = UnsafeNativeMethods.LoSetTabs(
_ploc.Value,
incrementalTab,
tabStopCount,
tabStops
);
if(lserr != LsErr.None)
{
ThrowExceptionFromLsError(SR.Get(SRID.SetTabsFailure, lserr), lserr);
}
}
static internal void ThrowExceptionFromLsError(string message, LsErr lserr)
{
if (lserr == LsErr.OutOfMemory)
throw new OutOfMemoryException (message);
throw new Exception(message);
}
#region Enumerations & constants
private enum State : byte
{
Uninitialized = 0,
Initialized
}
private const uint TwipsPerInch = 1440;
#endregion
#region Properties
/// <summary>
/// Actual LS unmanaged context
/// </summary>
internal SecurityCriticalDataForSet<IntPtr> Ploc
{
get { return _ploc; }
}
#endregion
}
internal enum BreakStrategies
{
BreakCJK,
KeepCJK,
Max
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ReadonlypropertyOperations operations.
/// </summary>
internal partial class ReadonlypropertyOperations : IServiceOperations<AzureCompositeModel>, IReadonlypropertyOperations
{
/// <summary>
/// Initializes a new instance of the ReadonlypropertyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ReadonlypropertyOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that have readonly properties
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ReadonlyObj>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ReadonlyObj>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ReadonlyObj>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that have readonly properties
/// </summary>
/// <param name='complexBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(ReadonlyObj complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/readonlyproperty/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* 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 Mono.Addins;
using OpenSim.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace OpenSim.Server.Base
{
/// <summary>
/// Command manager -
/// Wrapper for OpenSim.Framework.PluginManager to allow
/// us to add commands to the console to perform operations
/// on our repos and plugins
/// </summary>
public class CommandManager
{
public AddinRegistry PluginRegistry;
protected PluginManager PluginManager;
public CommandManager(AddinRegistry registry)
{
PluginRegistry = registry;
PluginManager = new PluginManager(PluginRegistry);
AddManagementCommands();
}
private void AddManagementCommands()
{
// add plugin
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin add", "plugin add \"plugin index\"",
"Install plugin from repository.",
HandleConsoleInstallPlugin);
// remove plugin
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin remove", "plugin remove \"plugin index\"",
"Remove plugin from repository",
HandleConsoleUnInstallPlugin);
// list installed plugins
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin list installed",
"plugin list installed", "List install plugins",
HandleConsoleListInstalledPlugin);
// list plugins available from registered repositories
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin list available",
"plugin list available", "List available plugins",
HandleConsoleListAvailablePlugin);
// List available updates
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin updates", "plugin updates", "List availble updates",
HandleConsoleListUpdates);
// Update plugin
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin update", "plugin update \"plugin index\"", "Update the plugin",
HandleConsoleUpdatePlugin);
// Add repository
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo add", "repo add \"url\"", "Add repository",
HandleConsoleAddRepo);
// Refresh repo
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo refresh", "repo refresh \"url\"", "Sync with a registered repository",
HandleConsoleGetRepo);
// Remove repository from registry
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo remove",
"repo remove \"[url | index]\"",
"Remove repository from registry",
HandleConsoleRemoveRepo);
// Enable repo
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo enable", "repo enable \"[url | index]\"",
"Enable registered repository",
HandleConsoleEnableRepo);
// Disable repo
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo disable", "repo disable\"[url | index]\"",
"Disable registered repository",
HandleConsoleDisableRepo);
// List registered repositories
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo list", "repo list",
"List registered repositories",
HandleConsoleListRepos);
// *
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin info", "plugin info \"plugin index\"", "Show detailed information for plugin",
HandleConsoleShowAddinInfo);
// Plugin disable
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin disable", "plugin disable \"plugin index\"",
"Disable a plugin",
HandleConsoleDisablePlugin);
// Enable plugin
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin enable", "plugin enable \"plugin index\"",
"Enable the selected plugin plugin",
HandleConsoleEnablePlugin);
}
#region console handlers
// Register repository
private void HandleConsoleAddRepo(string module, string[] cmd)
{
if (cmd.Length == 3)
{
PluginManager.AddRepository(cmd[2]);
}
return;
}
// Disable plugin
private void HandleConsoleDisablePlugin(string module, string[] cmd)
{
PluginManager.DisablePlugin(cmd);
return;
}
// Disable repository
private void HandleConsoleDisableRepo(string module, string[] cmd)
{
PluginManager.DisableRepository(cmd);
return;
}
// Enable plugin
private void HandleConsoleEnablePlugin(string module, string[] cmd)
{
PluginManager.EnablePlugin(cmd);
return;
}
// Enable repository
private void HandleConsoleEnableRepo(string module, string[] cmd)
{
PluginManager.EnableRepository(cmd);
return;
}
// Get repository status **not working
private void HandleConsoleGetRepo(string module, string[] cmd)
{
PluginManager.GetRepository();
return;
}
// Handle our console commands
//
// Install plugin from registered repository
/// <summary>
/// Handles the console install plugin command. Attempts to install the selected plugin
/// and
/// </summary>
/// <param name='module'>
/// Module.
/// </param>
/// <param name='cmd'>
/// Cmd.
/// </param>
private void HandleConsoleInstallPlugin(string module, string[] cmd)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (cmd.Length == 3)
{
int ndx = Convert.ToInt16(cmd[2]);
if (PluginManager.InstallPlugin(ndx, out result) == true)
{
ArrayList s = new ArrayList();
s.AddRange(result.Keys);
s.Sort();
var list = result.Keys.ToList();
list.Sort();
foreach (var k in list)
{
Dictionary<string, object> plugin = (Dictionary<string, object>)result[k];
bool enabled = (bool)plugin["enabled"];
MainConsole.Instance.OutputFormat("{0}) {1} {2} rev. {3}",
k,
enabled == true ? "[ ]" : "[X]",
plugin["name"], plugin["version"]);
}
}
}
return;
}
// List available plugins on registered repositories
private void HandleConsoleListAvailablePlugin(string module, string[] cmd)
{
Dictionary<string, object> result = new Dictionary<string, object>();
PluginManager.ListAvailable(out result);
var list = result.Keys.ToList();
list.Sort();
foreach (var k in list)
{
// name, version, repository
Dictionary<string, object> plugin = (Dictionary<string, object>)result[k];
MainConsole.Instance.OutputFormat("{0}) {1} rev. {2} {3}",
k,
plugin["name"],
plugin["version"],
plugin["repository"]);
}
return;
}
// List installed plugins
private void HandleConsoleListInstalledPlugin(string module, string[] cmd)
{
Dictionary<string, object> result = new Dictionary<string, object>();
PluginManager.ListInstalledAddins(out result);
ArrayList s = new ArrayList();
s.AddRange(result.Keys);
s.Sort();
var list = result.Keys.ToList();
list.Sort();
foreach (var k in list)
{
Dictionary<string, object> plugin = (Dictionary<string, object>)result[k];
bool enabled = (bool)plugin["enabled"];
MainConsole.Instance.OutputFormat("{0}) {1} {2} rev. {3}",
k,
enabled == true ? "[ ]" : "[X]",
plugin["name"], plugin["version"]);
}
return;
}
// List repositories
private void HandleConsoleListRepos(string module, string[] cmd)
{
Dictionary<string, object> result = new Dictionary<string, object>();
PluginManager.ListRepositories(out result);
var list = result.Keys.ToList();
list.Sort();
foreach (var k in list)
{
Dictionary<string, object> repo = (Dictionary<string, object>)result[k];
bool enabled = (bool)repo["enabled"];
MainConsole.Instance.OutputFormat("{0}) {1} {2}",
k,
enabled == true ? "[ ]" : "[X]",
repo["name"], repo["url"]);
}
return;
}
// List available updates **not ready
private void HandleConsoleListUpdates(string module, string[] cmd)
{
PluginManager.ListUpdates();
return;
}
// Remove registered repository
private void HandleConsoleRemoveRepo(string module, string[] cmd)
{
if (cmd.Length == 3)
PluginManager.RemoveRepository(cmd);
return;
}
// Show description information
private void HandleConsoleShowAddinInfo(string module, string[] cmd)
{
if (cmd.Length >= 3)
{
Dictionary<string, object> result = new Dictionary<string, object>();
int ndx = Convert.ToInt16(cmd[2]);
PluginManager.AddinInfo(ndx, out result);
MainConsole.Instance.OutputFormat("Name: {0}\nURL: {1}\nFile: {2}\nAuthor: {3}\nCategory: {4}\nDesc: {5}",
result["name"],
result["url"],
result["file_name"],
result["author"],
result["category"],
result["description"]);
return;
}
}
// Remove installed plugin
private void HandleConsoleUnInstallPlugin(string module, string[] cmd)
{
if (cmd.Length == 3)
{
int ndx = Convert.ToInt16(cmd[2]);
PluginManager.UnInstall(ndx);
}
return;
}
// Update plugin **not ready
private void HandleConsoleUpdatePlugin(string module, string[] cmd)
{
MainConsole.Instance.Output(PluginManager.Update());
return;
}
#endregion console handlers
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ReplicationProtectionContainerMappingsOperations operations.
/// </summary>
public partial interface IReplicationProtectionContainerMappingsOperations
{
/// <summary>
/// Remove protection container mapping.
/// </summary>
/// <remarks>
/// The operation to delete or remove a protection container mapping.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Protection container mapping name.
/// </param>
/// <param name='removalInput'>
/// Removal input.
/// </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>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput removalInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a protection container mapping/
/// </summary>
/// <remarks>
/// Gets the details of a protection container mapping.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Protection Container mapping name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ProtectionContainerMapping>> GetWithHttpMessagesAsync(string fabricName, string protectionContainerName, string mappingName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create protection container mapping.
/// </summary>
/// <remarks>
/// The operation to create a protection container mapping.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Protection container mapping name.
/// </param>
/// <param name='creationInput'>
/// Mapping creation input.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ProtectionContainerMapping>> CreateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput creationInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Purge protection container mapping.
/// </summary>
/// <remarks>
/// The operation to purge(force delete) a protection container mapping
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Protection container mapping name.
/// </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>
Task<AzureOperationResponse> PurgeWithHttpMessagesAsync(string fabricName, string protectionContainerName, string mappingName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the list of protection container mappings for a protection
/// container.
/// </summary>
/// <remarks>
/// Lists the protection container mappings for a protection container.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ProtectionContainerMapping>>> ListByReplicationProtectionContainersWithHttpMessagesAsync(string fabricName, string protectionContainerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the list of all protection container mappings in a vault.
/// </summary>
/// <remarks>
/// Lists the protection container mappings in the vault.
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ProtectionContainerMapping>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Remove protection container mapping.
/// </summary>
/// <remarks>
/// The operation to delete or remove a protection container mapping.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Protection container mapping name.
/// </param>
/// <param name='removalInput'>
/// Removal input.
/// </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>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput removalInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create protection container mapping.
/// </summary>
/// <remarks>
/// The operation to create a protection container mapping.
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Protection container mapping name.
/// </param>
/// <param name='creationInput'>
/// Mapping creation input.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ProtectionContainerMapping>> BeginCreateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput creationInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Purge protection container mapping.
/// </summary>
/// <remarks>
/// The operation to purge(force delete) a protection container mapping
/// </remarks>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Protection container mapping name.
/// </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>
Task<AzureOperationResponse> BeginPurgeWithHttpMessagesAsync(string fabricName, string protectionContainerName, string mappingName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the list of protection container mappings for a protection
/// container.
/// </summary>
/// <remarks>
/// Lists the protection container mappings for a protection container.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ProtectionContainerMapping>>> ListByReplicationProtectionContainersNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the list of all protection container mappings in a vault.
/// </summary>
/// <remarks>
/// Lists the protection container mappings in the vault.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ProtectionContainerMapping>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public static class GUIManager {
public static Text endText;
public static GameObject endMenu;
public static Button progressButton;
public static Button endButton;
public static Slider diffSlider;
public static Button startButton;
public static Button settingsButton;
public static Button exitButton;
public static Text difficultyLabel;
public static GameObject pauseMenu;
public static Button unpauseButton;
public static Button saveFromPauseButton;
public static Button loadFromPauseButton;
public static Button exitToLobbyFromPauseButton;
public static Button exitToMenuFromPauseButton;
public static GameObject menuCanvas;
public static GameObject settingsCanvas;
public static Button backSettingsButton;
public static GameObject startGameCanvas;
public static Button backStartGameButton;
public static Button startNewButton;
public static Button loadSavedButton;
public static GameObject saveLoadMenu;
public static Text saveLoadLabel;
public static Button backFromSaveLoadButton;
public static InputField saveNameField;
public static Button saveLoadButton;
public static GameObject textPrefab;
public static void Win () {
endMenu.SetActive (true);
endText.gameObject.SetActive (true);
endText.GetComponent<Text> ().text = "You win!";
progressButton.GetComponentInChildren<Text> ().text = "Next Level";
progressButton.GetComponent<Button> ().onClick.RemoveListener (GameManager.NextLevel);
progressButton.GetComponent<Button> ().onClick.AddListener (GameManager.NextLevel);
}
public static void Lose () {
endMenu.SetActive (true);
endText.gameObject.SetActive (true);
endText.GetComponent<Text> ().text = "You Lose!";
progressButton.GetComponentInChildren<Text> ().text = "Restart Level";
progressButton.GetComponent<Button> ().onClick.RemoveListener (GameManager.RestartLevel);
progressButton.GetComponent<Button> ().onClick.AddListener (GameManager.RestartLevel);
}
public static void InitEndMenu ()
{
endText = GameObject.Find ("EndCanvas/End Menu/endText").GetComponent<Text> ();
endMenu = GameObject.Find ("EndCanvas/End Menu");
progressButton = GameObject.Find ("EndCanvas/End Menu/Progress").GetComponent<Button> ();
endButton = GameObject.Find ("EndCanvas/End Menu/End").GetComponent<Button> ();
progressButton.onClick.RemoveAllListeners ();
endButton.onClick.AddListener (GameManager.ExitToMainMenu);
}
public static void InitPauseMenu ()
{
pauseMenu = GameObject.Find ("PauseCanvas/Pause Menu");
unpauseButton = GameObject.Find ("PauseCanvas/Pause Menu/Unpause").GetComponent<Button> ();
saveFromPauseButton = GameObject.Find ("PauseCanvas/Pause Menu/Save").GetComponent<Button> ();
loadFromPauseButton = GameObject.Find ("PauseCanvas/Pause Menu/Load").GetComponent<Button> ();
exitToLobbyFromPauseButton = GameObject.Find ("PauseCanvas/Pause Menu/ExitToLobby").GetComponent<Button> ();
exitToMenuFromPauseButton = GameObject.Find ("PauseCanvas/Pause Menu/ExitToMainMenu").GetComponent<Button> ();
unpauseButton.onClick.AddListener (GameManager.TogglePause);
saveFromPauseButton.onClick.AddListener (ToggleSaveCanvas);
loadFromPauseButton.onClick.AddListener (ToggleLoadCanvas);
exitToLobbyFromPauseButton.onClick.AddListener (GameManager.GotoLobby);
exitToMenuFromPauseButton.onClick.AddListener (GameManager.ExitToMainMenu);
pauseMenu.SetActive (false);
}
public static void InitMainMenu ()
{
menuCanvas = GameObject.Find ("MainMenuCanvas");
settingsButton = GameObject.Find ("MainMenuCanvas/settings").GetComponent<Button> ();
exitButton = GameObject.Find ("MainMenuCanvas/exit").GetComponent<Button> ();
startButton = GameObject.Find ("MainMenuCanvas/start").GetComponent<Button> ();
settingsCanvas = GameObject.Find ("SettingsCanvas");
backSettingsButton = GameObject.Find ("SettingsCanvas/back").GetComponent<Button> ();
startGameCanvas = GameObject.Find ("StartGameCanvas");
difficultyLabel = GameObject.Find ("StartGameCanvas/difficultySlider/Handle Slide Area/Handle/difficultyLabel").GetComponent<Text> ();
diffSlider = GameObject.Find ("StartGameCanvas/difficultySlider").GetComponent<Slider> ();
startNewButton = GameObject.Find ("StartGameCanvas/startnew").GetComponent<Button> ();
loadSavedButton = GameObject.Find ("StartGameCanvas/loadsaved").GetComponent<Button> ();
backStartGameButton = GameObject.Find ("StartGameCanvas/back").GetComponent<Button> ();
startButton.onClick.AddListener (ToggleStartCanvas);
exitButton.onClick.AddListener (GameManager.ExitGame);
settingsButton.onClick.AddListener (ToggleSettings);
backSettingsButton.onClick.AddListener (ToggleSettings);
startNewButton.onClick.AddListener (GameManager.StartGame);
loadSavedButton.onClick.AddListener (ToggleLoadCanvas);
backStartGameButton.onClick.AddListener (ToggleStartCanvas);
startGameCanvas.SetActive (false);
}
public static void InitSaveLoadMenu()
{
saveLoadMenu = GameObject.Find ("SaveLoadCanvas/SaveLoad Menu");
saveLoadLabel = GameObject.Find ("SaveLoadCanvas/SaveLoad Menu/SAVELOAD").GetComponent<Text> ();
backFromSaveLoadButton = GameObject.Find ("SaveLoadCanvas/SaveLoad Menu/Back").GetComponent<Button> ();
saveNameField = GameObject.Find ("SaveLoadCanvas/SaveLoad Menu/SaveName").GetComponent<InputField> ();
saveLoadButton = GameObject.Find ("SaveLoadCanvas/SaveLoad Menu/SaveLoad").GetComponent<Button> ();
backFromSaveLoadButton.onClick.AddListener (ToggleSaveLoadCanvas);
saveLoadButton.onClick.AddListener (ToggleSaveLoadCanvas);
saveLoadMenu.SetActive (false);
}
/// <summary>
/// Toggles the settings menu.
/// </summary>
public static void ToggleSettings ()
{
settingsCanvas.SetActive (!settingsCanvas.activeInHierarchy);
menuCanvas.SetActive (!menuCanvas.activeInHierarchy);
}
/// <summary>
/// Toggles the start canvas visibility.
/// </summary>
public static void ToggleStartCanvas ()
{
startGameCanvas.SetActive (!startGameCanvas.activeInHierarchy);
menuCanvas.SetActive (!menuCanvas.activeInHierarchy);
}
/// <summary>
/// Toggles the save canvas visibility.
/// </summary>
public static void ToggleSaveCanvas ()
{
saveLoadMenu.SetActive (!saveLoadMenu.activeInHierarchy);
if (saveLoadMenu.activeInHierarchy) {
saveLoadButton.onClick.RemoveListener (GameManager.LoadGameFromMenu);
saveLoadButton.onClick.RemoveListener (GameManager.SaveGameFromMenu);
saveLoadLabel.text = "SAVE";
saveLoadButton.GetComponentInChildren<Text> ().text = "Save";
saveLoadButton.onClick.AddListener (GameManager.SaveGameFromMenu);
}
}
/// <summary>
/// Toggles the load canvas visibility.
/// </summary>
public static void ToggleLoadCanvas ()
{
saveLoadMenu.SetActive (!saveLoadMenu.activeInHierarchy);
if (saveLoadMenu.activeInHierarchy) {
saveLoadButton.onClick.RemoveListener (GameManager.LoadGameFromMenu);
saveLoadButton.onClick.RemoveListener (GameManager.SaveGameFromMenu);
saveLoadLabel.text = "LOAD";
saveLoadButton.GetComponentInChildren<Text> ().text = "Load";
saveLoadButton.onClick.AddListener (GameManager.LoadGameFromMenu);
}
}
/// <summary>
/// Toggles the save or load canvas visibility.
/// </summary>
public static void ToggleSaveLoadCanvas ()
{
saveLoadMenu.SetActive (!saveLoadMenu.activeInHierarchy);
}
/// <summary>
/// Toggles the pause canvas visibility.
/// </summary>
public static void TogglePauseCanvas ()
{
pauseMenu.SetActive (!pauseMenu.activeInHierarchy);
}
/// <summary>
/// Gets the value of the difficulty slider on the main menu,
/// and sets the label of the slider.
/// </summary>
public static Difficulty GetDifficultyFromSlider ()
{
switch ((Difficulty)diffSlider.value) {
case Difficulty.EASY:
difficultyLabel.text = "EASY";
break;
case Difficulty.NORMAL:
difficultyLabel.text = "NORMAL";
break;
case Difficulty.HARD:
difficultyLabel.text = "HARD";
break;
}
return (Difficulty)diffSlider.value;
}
public static Text ShowText(string toShow) {
Text text = GameObject.Instantiate(textPrefab).GetComponentInChildren<Text>();
text.text = toShow;
return text;
}
public static void RemoveText(Text toRemove) {
Canvas canvas = toRemove.GetComponentInParent<Canvas>();
GameObject.Destroy(canvas.gameObject);
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using Aurora.Simulation.Base;
using OpenSim.Services.Interfaces;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using Aurora.Framework.Servers.HttpServer;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using Aurora.DataManager;
using Aurora.Framework;
using OpenMetaverse.StructuredData;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using BitmapProcessing;
using RegionFlags = Aurora.Framework.RegionFlags;
namespace OpenSim.Services
{
public class WireduxHandler : IService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public IHttpServer m_server = null;
public IHttpServer m_server2 = null;
string m_servernick = "hippogrid";
protected IRegistryCore m_registry;
public string Name
{
get { return GetType().Name; }
}
#region IService
public void Initialize(IConfigSource config, IRegistryCore registry)
{
}
public void Start(IConfigSource config, IRegistryCore registry)
{
if (config.Configs["GridInfoService"] != null)
m_servernick = config.Configs["GridInfoService"].GetString("gridnick", m_servernick);
m_registry = registry;
IConfig handlerConfig = config.Configs["Handlers"];
string name = handlerConfig.GetString("WireduxHandler", "");
if (name != Name)
return;
string Password = handlerConfig.GetString("WireduxHandlerPassword", String.Empty);
if (Password != "")
{
IConfig gridCfg = config.Configs["GridInfoService"];
OSDMap gridInfo = new OSDMap();
if (gridCfg != null)
{
if (gridCfg.GetString("gridname", "") != "" && gridCfg.GetString("gridnick", "") != "")
{
foreach (string k in gridCfg.GetKeys())
{
gridInfo[k] = gridCfg.GetString(k);
}
}
}
m_server = registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(handlerConfig.GetUInt("WireduxHandlerPort"));
//This handler allows sims to post CAPS for their sims on the CAPS server.
m_server.AddStreamHandler(new WireduxHTTPHandler(Password, registry, gridInfo, UUID.Zero));
m_server2 = registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(handlerConfig.GetUInt("WireduxTextureServerPort"));
m_server2.AddHTTPHandler("GridTexture", OnHTTPGetTextureImage);
m_server2.AddHTTPHandler("MapTexture", OnHTTPGetMapImage);
gridInfo["WireduxTextureServer"] = m_server2.ServerURI;
MainConsole.Instance.Commands.AddCommand("webui promote user", "Grants the specified user administrative powers within webui.", "webui promote user", PromoteUser);
MainConsole.Instance.Commands.AddCommand("webui demote user", "Revokes administrative powers for webui from the specified user.", "webui demote user", DemoteUser);
MainConsole.Instance.Commands.AddCommand("webui add user", "Deprecated alias for webui promote user.", "webui add user", PromoteUser);
MainConsole.Instance.Commands.AddCommand("webui remove user", "Deprecated alias for webui demote user.", "webui remove user", DemoteUser);
}
}
public void FinishedStartup()
{
}
#endregion
#region textures
public Hashtable OnHTTPGetTextureImage(Hashtable keysvals)
{
Hashtable reply = new Hashtable();
if (keysvals["method"].ToString() != "GridTexture")
return reply;
m_log.Debug("[WebUI]: Sending image jpeg");
const int statuscode = 200;
byte[] jpeg = new byte[0];
IAssetService m_AssetService = m_registry.RequestModuleInterface<IAssetService>();
MemoryStream imgstream = new MemoryStream();
Bitmap mapTexture = new Bitmap(1, 1);
Image image = mapTexture;
try
{
// Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data
imgstream = new MemoryStream();
// non-async because we know we have the asset immediately.
AssetBase mapasset = m_AssetService.Get(keysvals["uuid"].ToString());
// Decode image to System.Drawing.Image
ManagedImage managedImage;
if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image))
{
// Save to bitmap
mapTexture = ResizeBitmap(image, 128, 128);
EncoderParameters myEncoderParameters = new EncoderParameters();
myEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75L);
// Save bitmap to stream
mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters);
// Write the stream to a byte array for output
jpeg = imgstream.ToArray();
}
}
catch (Exception)
{
// Dummy!
m_log.Warn("[WebUI]: Unable to post image.");
}
finally
{
// Reclaim memory, these are unmanaged resources
// If we encountered an exception, one or more of these will be null
if (mapTexture != null)
mapTexture.Dispose();
if (image != null)
image.Dispose();
if (imgstream != null)
{
imgstream.Close();
imgstream.Dispose();
}
}
reply["str_response_string"] = Convert.ToBase64String(jpeg);
reply["int_response_code"] = statuscode;
reply["content_type"] = "image/jpeg";
return reply;
}
public Hashtable OnHTTPGetMapImage(Hashtable keysvals)
{
Hashtable reply = new Hashtable();
if (keysvals["method"].ToString() != "MapTexture")
return reply;
int zoom = 20;
int x = 0;
int y = 0;
if (keysvals.ContainsKey("zoom"))
zoom = int.Parse(keysvals["zoom"].ToString());
if (keysvals.ContainsKey("x"))
x = (int)float.Parse(keysvals["x"].ToString());
if (keysvals.ContainsKey("y"))
y = (int)float.Parse(keysvals["y"].ToString());
m_log.Debug("[WebUI]: Sending map image jpeg");
const int statuscode = 200;
byte[] jpeg = new byte[0];
MemoryStream imgstream = new MemoryStream();
Bitmap mapTexture = CreateZoomLevel(zoom, x, y);
EncoderParameters myEncoderParameters = new EncoderParameters();
myEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75L);
// Save bitmap to stream
mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters);
// Write the stream to a byte array for output
jpeg = imgstream.ToArray();
// Reclaim memory, these are unmanaged resources
// If we encountered an exception, one or more of these will be null
mapTexture.Dispose();
imgstream.Close();
imgstream.Dispose();
reply["str_response_string"] = Convert.ToBase64String(jpeg);
reply["int_response_code"] = statuscode;
reply["content_type"] = "image/jpeg";
return reply;
}
public Bitmap ResizeBitmap(Image b, int nWidth, int nHeight)
{
Bitmap newsize = new Bitmap(nWidth, nHeight);
Graphics temp = Graphics.FromImage(newsize);
temp.DrawImage(b, 0, 0, nWidth, nHeight);
temp.SmoothingMode = SmoothingMode.AntiAlias;
temp.DrawString(m_servernick, new Font("Arial", 8, FontStyle.Regular), new SolidBrush(Color.FromArgb(90, 255, 255, 50)), new Point(2, 115));
return newsize;
}
private Bitmap CreateZoomLevel(int zoomLevel, int centerX, int centerY)
{
if (!Directory.Exists("MapTiles"))
Directory.CreateDirectory("MapTiles");
string fileName = Path.Combine("MapTiles", "Zoom" + zoomLevel + "X" + centerX + "Y" + centerY + ".jpg");
if (File.Exists(fileName))
{
DateTime lastWritten = File.GetLastWriteTime(fileName);
if ((DateTime.Now - lastWritten).Minutes < 10) //10 min cache
return (Bitmap)Image.FromFile(fileName);
}
List<GridRegion> regions = m_registry.RequestModuleInterface<IGridService>().GetRegionRange(UUID.Zero,
centerX * Constants.RegionSize - (zoomLevel * Constants.RegionSize),
centerX * Constants.RegionSize + (zoomLevel * Constants.RegionSize),
centerY * Constants.RegionSize - (zoomLevel * Constants.RegionSize),
centerY * Constants.RegionSize + (zoomLevel * Constants.RegionSize));
List<Image> bitImages = new List<Image>();
List<FastBitmap> fastbitImages = new List<FastBitmap>();
foreach (GridRegion r in regions)
{
AssetBase texAsset = m_registry.RequestModuleInterface<IAssetService>().Get(r.TerrainImage.ToString());
if (texAsset != null)
{
ManagedImage managedImage;
Image image;
if (OpenJPEG.DecodeToImage(texAsset.Data, out managedImage, out image))
{
bitImages.Add(image);
fastbitImages.Add(new FastBitmap((Bitmap)image));
}
}
}
const int imageSize = 2560;
float zoomScale = (imageSize / zoomLevel);
Bitmap mapTexture = new Bitmap(imageSize, imageSize);
Graphics g = Graphics.FromImage(mapTexture);
Color seaColor = Color.FromArgb(29, 71, 95);
SolidBrush sea = new SolidBrush(seaColor);
g.FillRectangle(sea, 0, 0, imageSize, imageSize);
for (int i = 0; i < regions.Count; i++)
{
float x = ((regions[i].RegionLocX - (centerX * (float)Constants.RegionSize) + Constants.RegionSize / 2) / Constants.RegionSize);
float y = ((regions[i].RegionLocY - (centerY * (float)Constants.RegionSize) + Constants.RegionSize / 2) / Constants.RegionSize);
int regionWidth = regions[i].RegionSizeX / Constants.RegionSize;
int regionHeight = regions[i].RegionSizeY / Constants.RegionSize;
float posX = (x * zoomScale) + imageSize / 2;
float posY = (y * zoomScale) + imageSize / 2;
g.DrawImage(bitImages[i], posX, imageSize - posY, zoomScale * regionWidth, zoomScale * regionHeight); // y origin is top
}
mapTexture.Save(fileName, ImageFormat.Jpeg);
return mapTexture;
}
// From msdn
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
#endregion
#region Console Commands
private void PromoteUser(string[] cmd)
{
string name = MainConsole.Instance.Prompt("Name of user");
UserAccount acc = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, name);
if (acc == null)
{
m_log.Warn("You must create the user before promoting them.");
return;
}
IAgentConnector agents = DataManager.RequestPlugin<IAgentConnector>();
if (agents == null)
{
m_log.Warn("Could not get IAgentConnector plugin");
return;
}
IAgentInfo agent = agents.GetAgent(acc.PrincipalID);
if (agent == null)
{
m_log.Warn("Could not get IAgentInfo for " + name + ", try logging the user into your grid first.");
return;
}
agent.OtherAgentInformation["WebUIEnabled"] = true;
DataManager.RequestPlugin<IAgentConnector>().UpdateAgent(agent);
m_log.Warn("Admin added");
}
private void DemoteUser(string[] cmd)
{
string name = MainConsole.Instance.Prompt("Name of user");
UserAccount acc = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, name);
if (acc == null)
{
m_log.Warn("User does not exist, no action taken.");
return;
}
IAgentConnector agents = DataManager.RequestPlugin<IAgentConnector>();
if (agents == null)
{
m_log.Warn("Could not get IAgentConnector plugin");
return;
}
IAgentInfo agent = agents.GetAgent(acc.PrincipalID);
if (agent == null)
{
m_log.Warn("Could not get IAgentInfo for " + name + ", try logging the user into your grid first.");
return;
}
agent.OtherAgentInformation["WebUIEnabled"] = false;
DataManager.RequestPlugin<IAgentConnector>().UpdateAgent(agent);
m_log.Warn("Admin removed");
}
#endregion
}
public class WireduxHTTPHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_password;
protected IRegistryCore m_registry;
protected OSDMap GridInfo;
private readonly UUID AdminAgentID;
private readonly Dictionary<string, MethodInfo> APIMethods = new Dictionary<string, MethodInfo>();
public WireduxHTTPHandler(string pass, IRegistryCore reg, OSDMap gridInfo, UUID adminAgentID) :
base("POST", "/WIREDUX")
{
m_registry = reg;
m_password = Util.Md5Hash(pass);
GridInfo = gridInfo;
AdminAgentID = adminAgentID;
MethodInfo[] methods = GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
for (uint i = 0; i < methods.Length; ++i)
{
if (methods[i].IsPrivate && methods[i].ReturnType == typeof(OSDMap) && methods[i].GetParameters().Length == 1 && methods[i].GetParameters()[0].ParameterType == typeof(OSDMap))
{
APIMethods[methods[i].Name] = methods[i];
}
}
}
#region BaseStreamHandler
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
m_log.TraceFormat("[WebUI]: query String: {0}", body);
string method = string.Empty;
OSDMap resp = new OSDMap();
try
{
OSDMap map = (OSDMap)OSDParser.DeserializeJson(body);
//Make sure that the person who is calling can access the web service
if (map.ContainsKey("WebPassword") && (map["WebPassword"] == m_password))
{
method = map["Method"].AsString();
if (method == "Login")
{
resp = Login(map, false);
}
else if (method == "AdminLogin")
{
resp = Login(map, true);
}
else if (APIMethods.ContainsKey(method))
{
object[] args = new object[] { map };
resp = (OSDMap)APIMethods[method].Invoke(this, args);
}
else
{
m_log.TraceFormat("[WebUI] Unsupported method called ({0})", method);
}
}
else
{
m_log.Debug("Password does not match");
}
}
catch (Exception e)
{
m_log.TraceFormat("[WebUI] Exception thrown: " + e);
}
if (resp.Count == 0)
{
resp.Add("response", OSD.FromString("Failed"));
}
UTF8Encoding encoding = new UTF8Encoding();
httpResponse.ContentType = "application/json";
return encoding.GetBytes(OSDParser.SerializeJsonString(resp, true));
}
#endregion
#region WebUI API methods
#region Grid
private OSDMap OnlineStatus(OSDMap map)
{
ILoginService loginService = m_registry.RequestModuleInterface<ILoginService>();
bool LoginEnabled = loginService.MinLoginLevel == 0;
OSDMap resp = new OSDMap();
resp["Online"] = OSD.FromBoolean(true);
resp["LoginEnabled"] = OSD.FromBoolean(LoginEnabled);
return resp;
}
private OSDMap get_grid_info(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["GridInfo"] = GridInfo;
return resp;
}
#endregion
#region Account
#region Registration
private OSDMap CheckIfUserExists(OSDMap map)
{
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, map["Name"].AsString());
bool Verified = user != null;
OSDMap resp = new OSDMap();
resp["Verified"] = OSD.FromBoolean(Verified);
resp["UUID"] = OSD.FromUUID(Verified ? user.PrincipalID : UUID.Zero);
return resp;
}
private OSDMap CreateAccount(OSDMap map)
{
bool Verified = false;
string Name = map["Name"].AsString();
string PasswordHash = map["PasswordHash"].AsString();
//string PasswordSalt = map["PasswordSalt"].AsString();
string HomeRegion = map["HomeRegion"].AsString();
string Email = map["Email"].AsString();
string AvatarArchive = map["AvatarArchive"].AsString();
int userLevel = map["UserLevel"].AsInteger();
bool activationRequired = map.ContainsKey("ActivationRequired") && map["ActivationRequired"].AsBoolean();
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
if (accountService == null)
return null;
if (!PasswordHash.StartsWith("$1$"))
PasswordHash = "$1$" + Util.Md5Hash(PasswordHash);
PasswordHash = PasswordHash.Remove(0, 3); //remove $1$
accountService.CreateUser(Name, PasswordHash, Email);
UserAccount user = accountService.GetUserAccount(UUID.Zero, Name);
IAgentInfoService agentInfoService = m_registry.RequestModuleInterface<IAgentInfoService>();
IGridService gridService = m_registry.RequestModuleInterface<IGridService>();
if (agentInfoService != null && gridService != null)
{
GridRegion r = gridService.GetRegionByName(UUID.Zero, HomeRegion);
if (r != null)
{
agentInfoService.SetHomePosition(user.PrincipalID.ToString(), r.RegionID, new Vector3(r.RegionSizeX / 2, r.RegionSizeY / 2, 20), Vector3.Zero);
}
else
{
m_log.DebugFormat("[WebUI]: Could not set home position for user {0}, region \"{1}\" did not produce a result from the grid service", user.PrincipalID.ToString(), HomeRegion);
}
}
Verified = user != null;
UUID userID = UUID.Zero;
OSDMap resp = new OSDMap();
resp["Verified"] = OSD.FromBoolean(Verified);
if (Verified)
{
userID = user.PrincipalID;
user.UserLevel = userLevel;
// could not find a way to save this data here.
DateTime RLDOB = map["RLDOB"].AsDate();
string RLFirstName = map["RLFirstName"].AsString();
string RLLastName = map["RLLastName"].AsString();
string RLAddress = map["RLAddress"].AsString();
string RLCity = map["RLCity"].AsString();
string RLZip = map["RLZip"].AsString();
string RLCountry = map["RLCountry"].AsString();
string RLIP = map["RLIP"].AsString();
IAgentConnector con = DataManager.RequestPlugin<IAgentConnector>();
con.CreateNewAgent(userID);
IAgentInfo agent = con.GetAgent(userID);
agent.OtherAgentInformation["RLDOB"] = RLDOB;
agent.OtherAgentInformation["RLFirstName"] = RLFirstName;
agent.OtherAgentInformation["RLLastName"] = RLLastName;
agent.OtherAgentInformation["RLAddress"] = RLAddress;
agent.OtherAgentInformation["RLCity"] = RLCity;
agent.OtherAgentInformation["RLZip"] = RLZip;
agent.OtherAgentInformation["RLCountry"] = RLCountry;
agent.OtherAgentInformation["RLIP"] = RLIP;
if (activationRequired)
{
UUID activationToken = UUID.Random();
agent.OtherAgentInformation["WebUIActivationToken"] = Util.Md5Hash(activationToken.ToString() + ":" + PasswordHash);
resp["WebUIActivationToken"] = activationToken;
}
con.UpdateAgent(agent);
accountService.StoreUserAccount(user);
IProfileConnector profileData = DataManager.RequestPlugin<IProfileConnector>();
IUserProfileInfo profile = profileData.GetUserProfile(user.PrincipalID);
if (profile == null)
{
profileData.CreateNewProfile(user.PrincipalID);
profile = profileData.GetUserProfile(user.PrincipalID);
}
if (AvatarArchive.Length > 0)
profile.AArchiveName = AvatarArchive + ".database";
profile.IsNewUser = true;
profileData.UpdateUserProfile(profile);
}
resp["UUID"] = OSD.FromUUID(userID);
return resp;
}
private OSDMap GetAvatarArchives(OSDMap map)
{
OSDMap resp = new OSDMap();
List<AvatarArchive> temp = DataManager.RequestPlugin<IAvatarArchiverConnector>().GetAvatarArchives(true);
OSDArray names = new OSDArray();
OSDArray snapshot = new OSDArray();
m_log.DebugFormat("[WebUI] {0} avatar archives found", temp.Count);
foreach (AvatarArchive a in temp)
{
names.Add(OSD.FromString(a.Name));
snapshot.Add(OSD.FromUUID(UUID.Parse(a.Snapshot)));
}
resp["names"] = names;
resp["snapshot"] = snapshot;
return resp;
}
private OSDMap Authenticated(OSDMap map)
{
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, map["UUID"].AsUUID());
bool Verified = user != null;
OSDMap resp = new OSDMap();
resp["Verified"] = OSD.FromBoolean(Verified);
if (Verified)
{
user.UserLevel = map.ContainsKey("value") ? map["value"].AsInteger() : 0;
accountService.StoreUserAccount(user);
IAgentConnector con = DataManager.RequestPlugin<IAgentConnector>();
IAgentInfo agent = con.GetAgent(user.PrincipalID);
if (agent != null && agent.OtherAgentInformation.ContainsKey("WebUIActivationToken"))
{
agent.OtherAgentInformation.Remove("WebUIActivationToken");
con.UpdateAgent(agent);
}
}
return resp;
}
private OSDMap ActivateAccount(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["Verified"] = OSD.FromBoolean(false);
if (map.ContainsKey("UserName") && map.ContainsKey("PasswordHash") && map.ContainsKey("ActivationToken"))
{
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, map["UserName"].ToString());
if (user != null)
{
IAgentConnector con = DataManager.RequestPlugin<IAgentConnector>();
IAgentInfo agent = con.GetAgent(user.PrincipalID);
if (agent != null && agent.OtherAgentInformation.ContainsKey("WebUIActivationToken"))
{
UUID activationToken = map["ActivationToken"];
string WebUIActivationToken = agent.OtherAgentInformation["WebUIActivationToken"];
string PasswordHash = map["PasswordHash"];
if (!PasswordHash.StartsWith("$1$"))
{
PasswordHash = "$1$" + Util.Md5Hash(PasswordHash);
}
PasswordHash = PasswordHash.Remove(0, 3); //remove $1$
bool verified = Utils.MD5String(activationToken.ToString() + ":" + PasswordHash) == WebUIActivationToken;
resp["Verified"] = verified;
if (verified)
{
user.UserLevel = 0;
accountService.StoreUserAccount(user);
agent.OtherAgentInformation.Remove("WebUIActivationToken");
con.UpdateAgent(agent);
}
}
}
}
return resp;
}
#endregion
#region Login
private OSDMap Login(OSDMap map, bool asAdmin)
{
bool Verified = false;
string Name = map["Name"].AsString();
string Password = map["Password"].AsString();
ILoginService loginService = m_registry.RequestModuleInterface<ILoginService>();
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount account = null;
OSDMap resp = new OSDMap();
resp["Verified"] = OSD.FromBoolean(false);
if (accountService == null || CheckIfUserExists(map)["Verified"] != true)
{
return resp;
}
account = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, Name);
//Null means it went through without an errorz
if (loginService.VerifyClient(account.PrincipalID, Name, "UserAccount", Password, account.ScopeID))
{
if (asAdmin)
{
IAgentInfo agent = DataManager.RequestPlugin<IAgentConnector>().GetAgent(account.PrincipalID);
if (agent.OtherAgentInformation["WebUIEnabled"].AsBoolean() == false)
{
return resp;
}
}
resp["UUID"] = OSD.FromUUID(account.PrincipalID);
resp["FirstName"] = OSD.FromString(account.FirstName);
resp["LastName"] = OSD.FromString(account.LastName);
resp["Email"] = OSD.FromString(account.Email);
Verified = true;
}
resp["Verified"] = OSD.FromBoolean(Verified);
return resp;
}
private OSDMap SetWebLoginKey(OSDMap map)
{
OSDMap resp = new OSDMap();
UUID principalID = map["PrincipalID"].AsUUID();
UUID webLoginKey = UUID.Random();
IAuthenticationService authService = m_registry.RequestModuleInterface<IAuthenticationService>();
if (authService != null)
{
//Remove the old
DataManager.RequestPlugin<IAuthenticationData>().Delete(principalID, "WebLoginKey");
authService.SetPlainPassword(principalID, "WebLoginKey", webLoginKey.ToString());
resp["WebLoginKey"] = webLoginKey;
}
resp["Failed"] = OSD.FromString(String.Format("No auth service, cannot set WebLoginKey for user {0}.", map["PrincipalID"].AsUUID().ToString()));
return resp;
}
#endregion
#region Email
/// <summary>
/// After conformation the email is saved
/// </summary>
/// <param name="map">UUID, Email</param>
/// <returns>Verified</returns>
private OSDMap SaveEmail(OSDMap map)
{
string email = map["Email"].AsString();
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, map["UUID"].AsUUID());
OSDMap resp = new OSDMap();
bool verified = user != null;
resp["Verified"] = OSD.FromBoolean(verified);
if (verified)
{
user.Email = email;
user.UserLevel = 0;
accountService.StoreUserAccount(user);
}
return resp;
}
private OSDMap ConfirmUserEmailName(OSDMap map)
{
string Name = map["Name"].AsString();
string Email = map["Email"].AsString();
OSDMap resp = new OSDMap();
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, Name);
bool verified = user != null;
resp["Verified"] = OSD.FromBoolean(verified);
if (verified)
{
resp["UUID"] = OSD.FromUUID(user.PrincipalID);
if (user.UserLevel >= 0)
{
if (user.Email.ToLower() != Email.ToLower())
{
m_log.TraceFormat("User email for account \"{0}\" is \"{1}\" but \"{2}\" was specified.", Name, user.Email, Email);
resp["Error"] = OSD.FromString("Email does not match the user name.");
resp["ErrorCode"] = OSD.FromInteger(3);
}
}
else
{
resp["Error"] = OSD.FromString("This account is disabled.");
resp["ErrorCode"] = OSD.FromInteger(2);
}
}
else
{
resp["Error"] = OSD.FromString("No such user.");
resp["ErrorCode"] = OSD.FromInteger(1);
}
return resp;
}
#endregion
#region password
private OSDMap ChangePassword(OSDMap map)
{
string Password = map["Password"].AsString();
string newPassword = map["NewPassword"].AsString();
ILoginService loginService = m_registry.RequestModuleInterface<ILoginService>();
UUID userID = map["UUID"].AsUUID();
UserAccount account = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, userID);
IAuthenticationService auths = m_registry.RequestModuleInterface<IAuthenticationService>();
OSDMap resp = new OSDMap();
//Null means it went through without an error
bool Verified = loginService.VerifyClient(account.PrincipalID, account.Name, "UserAccount", Password, account.ScopeID);
resp["Verified"] = OSD.FromBoolean(Verified);
if ((auths.Authenticate(userID, "UserAccount", Util.Md5Hash(Password), 100) != string.Empty) && (Verified))
{
auths.SetPassword(userID, "UserAccount", newPassword);
}
return resp;
}
private OSDMap ForgotPassword(OSDMap map)
{
UUID UUDI = map["UUID"].AsUUID();
string Password = map["Password"].AsString();
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, UUDI);
OSDMap resp = new OSDMap();
bool verified = user != null;
resp["Verified"] = OSD.FromBoolean(verified);
resp["UserLevel"] = OSD.FromInteger(0);
if (verified)
{
resp["UserLevel"] = OSD.FromInteger(user.UserLevel);
if (user.UserLevel >= 0)
{
IAuthenticationService auths = m_registry.RequestModuleInterface<IAuthenticationService>();
auths.SetPassword(user.PrincipalID, "UserAccount", Password);
}
else
{
resp["Verified"] = OSD.FromBoolean(false);
}
}
return resp;
}
#endregion
/// <summary>
/// Changes user name
/// </summary>
/// <param name="map">UUID, FirstName, LastName</param>
/// <returns>Verified</returns>
private OSDMap ChangeName(OSDMap map)
{
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, map["UUID"].AsUUID());
OSDMap resp = new OSDMap();
bool verified = user != null;
resp["Verified"] = OSD.FromBoolean(verified);
if (verified)
{
user.Name = map["Name"].AsString();
resp["Stored"] = OSD.FromBoolean(accountService.StoreUserAccount(user));
}
return resp;
}
private OSDMap EditUser(OSDMap map)
{
bool editRLInfo = (map.ContainsKey("RLName") && map.ContainsKey("RLAddress") && map.ContainsKey("RLZip") && map.ContainsKey("RLCity") && map.ContainsKey("RLCountry"));
OSDMap resp = new OSDMap();
resp["agent"] = OSD.FromBoolean(!editRLInfo); // if we have no RLInfo, editing account is assumed to be successful.
resp["account"] = OSD.FromBoolean(false);
UUID principalID = map["UserID"].AsUUID();
UserAccount account = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, principalID);
if (account != null)
{
account.Email = map["Email"];
if (m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, map["Name"].AsString()) == null)
{
account.Name = map["Name"];
}
if (editRLInfo)
{
IAgentConnector agentConnector = DataManager.RequestPlugin<IAgentConnector>();
IAgentInfo agent = agentConnector.GetAgent(account.PrincipalID);
if (agent == null)
{
agentConnector.CreateNewAgent(account.PrincipalID);
agent = agentConnector.GetAgent(account.PrincipalID);
}
if (agent != null)
{
agent.OtherAgentInformation["RLName"] = map["RLName"];
agent.OtherAgentInformation["RLAddress"] = map["RLAddress"];
agent.OtherAgentInformation["RLZip"] = map["RLZip"];
agent.OtherAgentInformation["RLCity"] = map["RLCity"];
agent.OtherAgentInformation["RLCountry"] = map["RLCountry"];
agentConnector.UpdateAgent(agent);
resp["agent"] = OSD.FromBoolean(true);
}
}
resp["account"] = OSD.FromBoolean(m_registry.RequestModuleInterface<IUserAccountService>().StoreUserAccount(account));
}
return resp;
}
#endregion
#region Users
/// <summary>
/// Gets user information for change user info page on site
/// </summary>
/// <param name="map">UUID</param>
/// <returns>Verified, HomeName, HomeUUID, Online, Email, FirstName, LastName</returns>
private OSDMap GetGridUserInfo(OSDMap map)
{
string uuid = String.Empty;
uuid = map["UUID"].AsString();
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, map["UUID"].AsUUID());
IAgentInfoService agentService = m_registry.RequestModuleInterface<IAgentInfoService>();
OSDMap resp = new OSDMap();
bool verified = user != null;
resp["Verified"] = OSD.FromBoolean(verified);
if (verified)
{
UserInfo userinfo = agentService.GetUserInfo(uuid);
IGridService gs = m_registry.RequestModuleInterface<IGridService>();
GridRegion gr = null;
if (userinfo != null)
{
gr = gs.GetRegionByUUID(UUID.Zero, userinfo.HomeRegionID);
}
resp["UUID"] = OSD.FromUUID(user.PrincipalID);
resp["HomeUUID"] = OSD.FromUUID((userinfo == null) ? UUID.Zero : userinfo.HomeRegionID);
resp["HomeName"] = OSD.FromString((userinfo == null) ? "" : gr.RegionName);
resp["Online"] = OSD.FromBoolean(userinfo != null && userinfo.IsOnline);
resp["Email"] = OSD.FromString(user.Email);
resp["Name"] = OSD.FromString(user.Name);
resp["FirstName"] = OSD.FromString(user.FirstName);
resp["LastName"] = OSD.FromString(user.LastName);
}
return resp;
}
private OSDMap GetProfile(OSDMap map)
{
OSDMap resp = new OSDMap();
string Name = map["Name"].AsString();
UUID userID = map["UUID"].AsUUID();
UserAccount account = Name != "" ?
m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, Name) :
m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, userID);
if (account != null)
{
OSDMap accountMap = new OSDMap();
accountMap["Created"] = account.Created;
accountMap["Name"] = account.Name;
accountMap["PrincipalID"] = account.PrincipalID;
accountMap["Email"] = account.Email;
TimeSpan diff = DateTime.Now - Util.ToDateTime(account.Created);
int years = (int)diff.TotalDays / 356;
int days = years > 0 ? (int)diff.TotalDays / years : (int)diff.TotalDays;
accountMap["TimeSinceCreated"] = years + " years, " + days + " days"; // if we're sending account.Created do we really need to send this string ?
IProfileConnector profileConnector = DataManager.RequestPlugin<IProfileConnector>();
IUserProfileInfo profile = profileConnector.GetUserProfile(account.PrincipalID);
if (profile != null)
{
resp["profile"] = profile.ToOSD(false);//not trusted, use false
if (account.UserFlags == 0)
account.UserFlags = 2; //Set them to no info given
string flags = ((IUserProfileInfo.ProfileFlags)account.UserFlags).ToString();
IUserProfileInfo.ProfileFlags.NoPaymentInfoOnFile.ToString();
accountMap["AccountInfo"] = (profile.CustomType != "" ? profile.CustomType :
account.UserFlags == 0 ? "Resident" : "Admin") + "\n" + flags;
UserAccount partnerAccount = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, profile.Partner);
if (partnerAccount != null)
{
accountMap["Partner"] = partnerAccount.Name;
accountMap["PartnerUUID"] = partnerAccount.PrincipalID;
}
else
{
accountMap["Partner"] = "";
accountMap["PartnerUUID"] = UUID.Zero;
}
}
IAgentConnector agentConnector = DataManager.RequestPlugin<IAgentConnector>();
IAgentInfo agent = agentConnector.GetAgent(account.PrincipalID);
if (agent != null)
{
OSDMap agentMap = new OSDMap();
agentMap["RLName"] = agent.OtherAgentInformation["RLName"].AsString();
agentMap["RLAddress"] = agent.OtherAgentInformation["RLAddress"].AsString();
agentMap["RLZip"] = agent.OtherAgentInformation["RLZip"].AsString();
agentMap["RLCity"] = agent.OtherAgentInformation["RLCity"].AsString();
agentMap["RLCountry"] = agent.OtherAgentInformation["RLCountry"].AsString();
resp["agent"] = agentMap;
}
resp["account"] = accountMap;
}
return resp;
}
private OSDMap DeleteUser(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["Finished"] = OSD.FromBoolean(true);
UUID agentID = map["UserID"].AsUUID();
IAgentInfo GetAgent = DataManager.RequestPlugin<IAgentConnector>().GetAgent(agentID);
if (GetAgent != null)
{
GetAgent.Flags &= ~IAgentFlags.PermBan;
DataManager.RequestPlugin<IAgentConnector>().UpdateAgent(GetAgent);
}
return resp;
}
#region banning
private void doBan(UUID agentID, DateTime? until)
{
IAgentInfo GetAgent = DataManager.RequestPlugin<IAgentConnector>().GetAgent(agentID);
if (GetAgent != null)
{
GetAgent.Flags &= (until.HasValue) ? ~IAgentFlags.TempBan : ~IAgentFlags.PermBan;
if (until.HasValue)
{
GetAgent.OtherAgentInformation["TemperaryBanInfo"] = until.Value.ToString("s");
m_log.TraceFormat("Temp ban for {0} until {1}", agentID, until.Value.ToString("s"));
}
DataManager.RequestPlugin<IAgentConnector>().UpdateAgent(GetAgent);
}
}
private OSDMap BanUser(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["Finished"] = OSD.FromBoolean(true);
UUID agentID = map["UserID"].AsUUID();
doBan(agentID, null);
return resp;
}
private OSDMap TempBanUser(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["Finished"] = OSD.FromBoolean(true);
UUID agentID = map["UserID"].AsUUID();
DateTime until = map["BannedUntil"].AsDate();
doBan(agentID, until);
return resp;
}
private OSDMap UnBanUser(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["Finished"] = OSD.FromBoolean(true);
UUID agentID = map["UserID"].AsUUID();
IAgentInfo GetAgent = DataManager.RequestPlugin<IAgentConnector>().GetAgent(agentID);
if (GetAgent != null)
{
GetAgent.Flags &= IAgentFlags.PermBan;
GetAgent.Flags &= IAgentFlags.TempBan;
if (GetAgent.OtherAgentInformation.ContainsKey("TemperaryBanInfo"))
{
GetAgent.OtherAgentInformation.Remove("TemperaryBanInfo");
}
DataManager.RequestPlugin<IAgentConnector>().UpdateAgent(GetAgent);
}
return resp;
}
#endregion
private OSDMap FindUsers(OSDMap map)
{
OSDMap resp = new OSDMap();
int start = map["Start"].AsInteger();
int end = map["End"].AsInteger();
string Query = map["Query"].AsString();
List<UserAccount> accounts = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccounts(UUID.Zero, Query);
OSDArray users = new OSDArray();
m_log.TraceFormat("{0} accounts found", accounts.Count);
for (int i = start; i < end && i < accounts.Count; i++)
{
UserAccount acc = accounts[i];
OSDMap userInfo = new OSDMap();
userInfo["PrincipalID"] = acc.PrincipalID;
userInfo["UserName"] = acc.Name;
userInfo["Created"] = acc.Created;
userInfo["UserFlags"] = acc.UserFlags;
users.Add(userInfo);
}
resp["Users"] = users;
resp["Start"] = OSD.FromInteger(start);
resp["End"] = OSD.FromInteger(end);
resp["Query"] = OSD.FromString(Query);
return resp;
}
private OSDMap GetFriends(OSDMap map)
{
OSDMap resp = new OSDMap();
if (map.ContainsKey("UserID") == false)
{
resp["Failed"] = OSD.FromString("User ID not specified.");
return resp;
}
IFriendsService friendService = m_registry.RequestModuleInterface<IFriendsService>();
if (friendService == null)
{
resp["Failed"] = OSD.FromString("No friend service found.");
return resp;
}
List<FriendInfo> friendsList = new List<FriendInfo>(friendService.GetFriends(map["UserID"].AsUUID()));
OSDArray friends = new OSDArray(friendsList.Count);
foreach (FriendInfo friendInfo in friendsList)
{
UserAccount account = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, UUID.Parse(friendInfo.Friend));
OSDMap friend = new OSDMap(4);
friend["PrincipalID"] = friendInfo.Friend;
friend["Name"] = account.Name;
friend["MyFlags"] = friendInfo.MyFlags;
friend["TheirFlags"] = friendInfo.TheirFlags;
friends.Add(friend);
}
resp["Friends"] = friends;
return resp;
}
#endregion
#region IAbuseReports
private OSDMap GetAbuseReports(OSDMap map)
{
OSDMap resp = new OSDMap();
IAbuseReports ar = m_registry.RequestModuleInterface<IAbuseReports>();
int start = map["Start"].AsInteger();
int count = map["Count"].AsInteger();
bool active = map["Active"].AsBoolean();
List<AbuseReport> lar = ar.GetAbuseReports(start, count, active);
OSDArray AbuseReports = new OSDArray();
foreach (AbuseReport tar in lar)
{
AbuseReports.Add(tar.ToOSD());
}
resp["AbuseReports"] = AbuseReports;
resp["Start"] = OSD.FromInteger(start);
resp["Count"] = OSD.FromInteger(count); // we're not using the AbuseReports.Count because client implementations of the WebUI API can check the count themselves. This is just for showing the input.
resp["Active"] = OSD.FromBoolean(active);
return resp;
}
private OSDMap AbuseReportMarkComplete(OSDMap map)
{
OSDMap resp = new OSDMap();
IAbuseReports ar = m_registry.RequestModuleInterface<IAbuseReports>();
AbuseReport tar = ar.GetAbuseReport(map["Number"].AsInteger(), map["WebPassword"].AsString());
if (tar != null)
{
tar.Active = false;
ar.UpdateAbuseReport(tar, map["WebPassword"].AsString());
resp["Finished"] = OSD.FromBoolean(true);
}
else
{
resp["Finished"] = OSD.FromBoolean(false);
resp["Failed"] = OSD.FromString(String.Format("No abuse report found with specified number {0}", map["Number"].AsInteger()));
}
return resp;
}
private OSDMap AbuseReportSaveNotes(OSDMap map)
{
OSDMap resp = new OSDMap();
IAbuseReports ar = m_registry.RequestModuleInterface<IAbuseReports>();
AbuseReport tar = ar.GetAbuseReport(map["Number"].AsInteger(), map["WebPassword"].AsString());
if (tar != null)
{
tar.Notes = map["Notes"].ToString();
ar.UpdateAbuseReport(tar, map["WebPassword"].AsString());
resp["Finished"] = OSD.FromBoolean(true);
}
else
{
resp["Finished"] = OSD.FromBoolean(false);
resp["Failed"] = OSD.FromString(String.Format("No abuse report found with specified number {0}", map["Number"].AsInteger()));
}
return resp;
}
#endregion
#region Places
#region Regions
private OSDMap GetRegions(OSDMap map)
{
OSDMap resp = new OSDMap();
RegionFlags type = map.Keys.Contains("RegionFlags") ? (RegionFlags)map["RegionFlags"].AsInteger() : RegionFlags.RegionOnline;
int start = map.Keys.Contains("Start") ? map["Start"].AsInteger() : 0;
if (start < 0)
{
start = 0;
}
int count = map.Keys.Contains("Count") ? map["Count"].AsInteger() : 10;
if (count < 0)
{
count = 1;
}
IRegionData regiondata = DataManager.RequestPlugin<IRegionData>();
Dictionary<string, bool> sort = new Dictionary<string, bool>();
string[] supportedSort = new[]{
"SortRegionName",
"SortLocX",
"SortLocY"
};
foreach (string sortable in supportedSort)
{
if (map.ContainsKey(sortable))
{
sort[sortable.Substring(4)] = map[sortable].AsBoolean();
}
}
List<GridRegion> regions = regiondata.Get(type, sort);
OSDArray Regions = new OSDArray();
if (start < regions.Count)
{
int i = 0;
int j = regions.Count <= (start + count) ? regions.Count : (start + count);
for (i = start; i < j; ++i)
{
Regions.Add(regions[i].ToOSD());
}
}
resp["Start"] = OSD.FromInteger(start);
resp["Count"] = OSD.FromInteger(count);
resp["Total"] = OSD.FromInteger(regions.Count);
resp["Regions"] = Regions;
return resp;
}
private OSDMap GetRegion(OSDMap map)
{
OSDMap resp = new OSDMap();
IRegionData regiondata = DataManager.RequestPlugin<IRegionData>();
if (regiondata != null && (map.ContainsKey("RegionID") || map.ContainsKey("Region")))
{
string regionName = map.ContainsKey("Region") ? map["Region"].ToString().Trim() : "";
UUID regionID = map.ContainsKey("RegionID") ? UUID.Parse(map["RegionID"].ToString()) : UUID.Zero;
UUID scopeID = map.ContainsKey("ScopeID") ? UUID.Parse(map["ScopeID"].ToString()) : UUID.Zero;
GridRegion region = null;
if (regionID != UUID.Zero)
{
region = regiondata.Get(regionID, scopeID);
}
else if (regionName != string.Empty)
{
region = regiondata.Get(regionName, scopeID)[0];
}
if (region != null)
{
resp["Region"] = region.ToOSD();
}
}
return resp;
}
#endregion
#region Parcels
private static OSDMap LandData2WebOSD(LandData parcel)
{
OSDMap parcelOSD = parcel.ToOSD();
parcelOSD["GenericData"] = parcelOSD.ContainsKey("GenericData") ? (parcelOSD["GenericData"].Type == OSDType.Map ? parcelOSD["GenericData"] : OSDParser.DeserializeLLSDXml(parcelOSD["GenericData"].ToString())) : new OSDMap();
parcelOSD["Bitmap"] = OSD.FromBinary(parcelOSD["Bitmap"]).ToString();
return parcelOSD;
}
private OSDMap GetParcelsByRegion(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["Parcels"] = new OSDArray();
resp["Total"] = OSD.FromInteger(0);
IDirectoryServiceConnector directory = DataManager.RequestPlugin<IDirectoryServiceConnector>();
if (directory != null && map.ContainsKey("Region"))
{
UUID RegionID = UUID.Parse(map["Region"]);
UUID ScopeID = map.ContainsKey("ScopeID") ? UUID.Parse(map["ScopeID"].ToString()) : UUID.Zero;
UUID owner = map.ContainsKey("Owner") ? UUID.Parse(map["Owner"].ToString()) : UUID.Zero;
uint start = map.ContainsKey("Start") ? uint.Parse(map["Start"].ToString()) : 0;
uint count = map.ContainsKey("Count") ? uint.Parse(map["Count"].ToString()) : 10;
ParcelFlags flags = map.ContainsKey("Flags") ? (ParcelFlags)int.Parse(map["Flags"].ToString()) : ParcelFlags.None;
ParcelCategory category = map.ContainsKey("Category") ? (ParcelCategory)uint.Parse(map["Flags"].ToString()) : ParcelCategory.Any;
uint total = directory.GetNumberOfParcelsByRegion(RegionID, ScopeID, owner, flags, category);
if (total > 0)
{
resp["Total"] = OSD.FromInteger((int)total);
if (count == 0)
{
return resp;
}
List<LandData> parcels = directory.GetParcelsByRegion(start, count, RegionID, ScopeID, owner, flags, category);
OSDArray Parcels = new OSDArray(parcels.Count);
#if(!ISWIN)
parcels.ForEach(delegate(LandData parcel)
{
Parcels.Add(LandData2WebOSD(parcel));
});
#else
parcels.ForEach(parcel => Parcels.Add(LandData2WebOSD(parcel)));
#endif
resp["Parcels"] = Parcels;
}
}
return resp;
}
private OSDMap GetParcel(OSDMap map)
{
OSDMap resp = new OSDMap();
UUID regionID = map.ContainsKey("RegionID") ? UUID.Parse(map["RegionID"].ToString()) : UUID.Zero;
UUID scopeID = map.ContainsKey("ScopeID") ? UUID.Parse(map["ScopeID"].ToString()) : UUID.Zero;
UUID parcelID = map.ContainsKey("ParcelInfoUUID") ? UUID.Parse(map["ParcelInfoUUID"].ToString()) : UUID.Zero;
string parcelName = map.ContainsKey("Parcel") ? map["Parcel"].ToString().Trim() : string.Empty;
IDirectoryServiceConnector directory = DataManager.RequestPlugin<IDirectoryServiceConnector>();
if (directory != null && (parcelID != UUID.Zero || (regionID != UUID.Zero && parcelName != string.Empty)))
{
LandData parcel = null;
if (parcelID != UUID.Zero)
{
parcel = directory.GetParcelInfo(parcelID);
}
else if (regionID != UUID.Zero && parcelName != string.Empty)
{
parcel = directory.GetParcelInfo(regionID, scopeID, parcelName);
}
if (parcel != null)
{
resp["Parcel"] = LandData2WebOSD(parcel);
}
}
return resp;
}
#endregion
#endregion
#region GroupRecord
private static OSDMap GroupRecord2OSDMap(GroupRecord group)
{
OSDMap resp = new OSDMap();
resp["GroupID"] = group.GroupID;
resp["GroupName"] = group.GroupName;
resp["AllowPublish"] = group.AllowPublish;
resp["MaturePublish"] = group.MaturePublish;
resp["Charter"] = group.Charter;
resp["FounderID"] = group.FounderID;
resp["GroupPicture"] = group.GroupPicture;
resp["MembershipFee"] = group.MembershipFee;
resp["OpenEnrollment"] = group.OpenEnrollment;
resp["OwnerRoleID"] = group.OwnerRoleID;
resp["ShowInList"] = group.ShowInList;
return resp;
}
private OSDMap GetGroups(OSDMap map)
{
OSDMap resp = new OSDMap();
uint start = map.ContainsKey("Start") ? map["Start"].AsUInteger() : 0;
resp["Start"] = start;
resp["Total"] = 0;
IGroupsServiceConnector groups = DataManager.RequestPlugin<IGroupsServiceConnector>();
OSDArray Groups = new OSDArray();
if (groups != null)
{
Dictionary<string, bool> sort = new Dictionary<string, bool>();
Dictionary<string, bool> boolFields = new Dictionary<string, bool>();
if (map.ContainsKey("Sort") && map["Sort"].Type == OSDType.Map)
{
OSDMap fields = (OSDMap)map["Sort"];
foreach (string field in fields.Keys)
{
sort[field] = int.Parse(fields[field]) != 0;
}
}
if (map.ContainsKey("BoolFields") && map["BoolFields"].Type == OSDType.Map)
{
OSDMap fields = (OSDMap)map["BoolFields"];
foreach (string field in fields.Keys)
{
boolFields[field] = int.Parse(fields[field]) != 0;
}
}
List<GroupRecord> reply = groups.GetGroupRecords(
AdminAgentID,
start,
map.ContainsKey("Count") ? map["Count"].AsUInteger() : 10,
sort,
boolFields
);
if (reply.Count > 0)
{
foreach (GroupRecord groupReply in reply)
{
Groups.Add(GroupRecord2OSDMap(groupReply));
}
}
resp["Total"] = groups.GetNumberOfGroups(AdminAgentID, boolFields);
}
resp["Groups"] = Groups;
return resp;
}
private OSDMap GetGroup(OSDMap map)
{
OSDMap resp = new OSDMap();
IGroupsServiceConnector groups = DataManager.RequestPlugin<IGroupsServiceConnector>();
resp["Group"] = false;
if (groups != null && (map.ContainsKey("Name") || map.ContainsKey("UUID")))
{
UUID groupID = map.ContainsKey("UUID") ? UUID.Parse(map["UUID"].ToString()) : UUID.Zero;
string name = map.ContainsKey("Name") ? map["Name"].ToString() : "";
GroupRecord reply = groups.GetGroupRecord(AdminAgentID, groupID, name);
if (reply != null)
{
resp["Group"] = GroupRecord2OSDMap(reply);
}
}
return resp;
}
#region GroupNoticeData
private OSDMap GroupAsNewsSource(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["Verified"] = OSD.FromBoolean(false);
IGenericsConnector generics = DataManager.RequestPlugin<IGenericsConnector>();
UUID groupID;
if (generics != null && map.ContainsKey("Group") && map.ContainsKey("Use") && UUID.TryParse(map["Group"], out groupID))
{
if (map["Use"].AsBoolean())
{
OSDMap useValue = new OSDMap();
useValue["Use"] = OSD.FromBoolean(true);
generics.AddGeneric(groupID, "Group", "WebUI_newsSource", useValue);
}
else
{
generics.RemoveGeneric(groupID, "Group", "WebUI_newsSource");
}
resp["Verified"] = OSD.FromBoolean(true);
}
return resp;
}
private OSDMap GroupNotices(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["GroupNotices"] = new OSDArray();
resp["Total"] = 0;
IGroupsServiceConnector groups = DataManager.RequestPlugin<IGroupsServiceConnector>();
if (map.ContainsKey("Groups") && groups != null && map["Groups"].Type.ToString() == "Array")
{
OSDArray groupIDs = (OSDArray)map["Groups"];
List<UUID> GroupIDs = new List<UUID>();
foreach (string groupID in groupIDs)
{
UUID foo;
if (UUID.TryParse(groupID, out foo))
{
GroupIDs.Add(foo);
}
}
if (GroupIDs.Count > 0)
{
uint start = map.ContainsKey("Start") ? uint.Parse(map["Start"]) : 0;
uint count = map.ContainsKey("Count") ? uint.Parse(map["Count"]) : 10;
List<GroupNoticeData> groupNotices = groups.GetGroupNotices(AdminAgentID, start, count, GroupIDs);
OSDArray GroupNotices = new OSDArray(groupNotices.Count);
foreach (GroupNoticeData GND in groupNotices)
{
OSDMap gnd = new OSDMap();
gnd["GroupID"] = OSD.FromUUID(GND.GroupID);
gnd["NoticeID"] = OSD.FromUUID(GND.NoticeID);
gnd["Timestamp"] = OSD.FromInteger((int)GND.Timestamp);
gnd["FromName"] = OSD.FromString(GND.FromName);
gnd["Subject"] = OSD.FromString(GND.Subject);
gnd["HasAttachment"] = OSD.FromBoolean(GND.HasAttachment);
gnd["ItemID"] = OSD.FromUUID(GND.ItemID);
gnd["AssetType"] = OSD.FromInteger((int)GND.AssetType);
gnd["ItemName"] = OSD.FromString(GND.ItemName);
gnd["Message"] = OSD.FromString(groups.GetGroupNotice(AdminAgentID, GND.NoticeID).Message);
GroupNotices.Add(gnd);
}
resp["GroupNotices"] = GroupNotices;
resp["Total"] = (int)groups.GetNumberOfGroupNotices(AdminAgentID, GroupIDs);
}
}
return resp;
}
private OSDMap NewsFromGroupNotices(OSDMap map)
{
OSDMap resp = new OSDMap();
resp["GroupNotices"] = new OSDArray();
resp["Total"] = 0;
IGenericsConnector generics = DataManager.RequestPlugin<IGenericsConnector>();
IGroupsServiceConnector groups = DataManager.RequestPlugin<IGroupsServiceConnector>();
if (generics == null || groups == null)
{
return resp;
}
OSDMap useValue = new OSDMap();
useValue["Use"] = OSD.FromBoolean(true);
List<UUID> GroupIDs = generics.GetOwnersByGeneric("Group", "WebUI_newsSource", useValue);
if (GroupIDs.Count <= 0)
{
return resp;
}
foreach (UUID groupID in GroupIDs)
{
GroupRecord group = groups.GetGroupRecord(AdminAgentID, groupID, "");
if (!group.ShowInList)
{
GroupIDs.Remove(groupID);
}
}
uint start = map.ContainsKey("Start") ? uint.Parse(map["Start"].ToString()) : 0;
uint count = map.ContainsKey("Count") ? uint.Parse(map["Count"].ToString()) : 10;
OSDMap args = new OSDMap();
args["Start"] = OSD.FromString(start.ToString());
args["Count"] = OSD.FromString(count.ToString());
args["Groups"] = new OSDArray(GroupIDs.ConvertAll(x => OSD.FromString(x.ToString())));
return GroupNotices(args);
}
#endregion
#endregion
#endregion
}
}
| |
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using Irony.Interpreter.Ast;
using iSukces.Code;
using iSukces.Code.Compatibility.System.Windows.Data;
using X=Bitbrains.AmmyParser.AmmyGrammar;
namespace Bitbrains.AmmyParser
{
public partial class AmmyGrammarAutogeneratorInfo
{
private static IEnumerable<object> GetItemsInternal()
{
yield return new AmmyGrammarAutogeneratorInfo("comma_opt")
.AsOptional(null, "comma");
yield return new AmmyGrammarAutogeneratorInfo("int_number_optional")
.AsOptional(null, nameof(X.Number));
yield return new AmmyGrammarAutogeneratorInfo(nameof(X.boolean))
{
BaseClass = nameof(AstNode)
};
yield return new AmmyGrammarAutogeneratorInfo("literal").AsOneOf();
yield return "qual_name_segment";
yield return "qual_name_segments_opt2";
yield return "qual_name_with_targs";
yield return "identifier_or_builtin";
yield return
new AmmyGrammarAutogeneratorInfo("using_ns_directive").AsAlternative(0); // , "using_ns_directive");
{
var el = new AmmyGrammarAutogeneratorInfo("using_directive")
.AsOneOf("using_ns_directive");
// yield return new AmmyGrammarAutogeneratorInfo("using_directives").AsListOf("UsingStatement");
// yield return "using_directives_opt,AstOptNode,false";
var list = el.GetList();
yield return el;
yield return list;
yield return list.GetOptional();
}
yield return new AmmyGrammarAutogeneratorInfo(nameof(X.mixin_definition));
{
var el = new AmmyGrammarAutogeneratorInfo("object_setting")
.AsOneOf("object_property_setting");
var list = el.GetList();
yield return el;
yield return list;
yield return list.GetOptional();
}
{
yield return new AmmyGrammarAutogeneratorInfo("ammy_bind");
var el = new AmmyGrammarAutogeneratorInfo("ammy_bind_source").Single();
yield return el;
yield return el.GetOptional();
yield return new AmmyGrammarAutogeneratorInfo("ammy_bind_source_source")
.AsAlternative(0,
"ammy_bind_source_ancestor",
"ammy_bind_source_element_name",
"ammy_bind_source_this").Single();
yield return new AmmyGrammarAutogeneratorInfo("ammy_bind_source_ancestor");
yield return new AmmyGrammarAutogeneratorInfo("ammy_bind_source_element_name").Single();
yield return new AmmyGrammarAutogeneratorInfo("ammy_bind_source_this");
{
var set = new AmmyGrammarAutogeneratorInfo("ammy_bind_set");
yield return set;
yield return set.GetOptional();
}
{
var item = new AmmyGrammarAutogeneratorInfo("ammy_bind_set_item")
.WithMap(0);
var bindingSettings = GetBindingSettings()
.Select(a => a.ToArray()).ToArray();
foreach (var i in bindingSettings)
{
foreach (var j in i)
yield return j;
}
var alts = bindingSettings.Select(a => a.Last().TerminalName);
item.Alternatives = alts.ToArray();
var list = item.GetList(true);
yield return item;
yield return list;
yield return list.GetOptional();
}
}
yield return new AmmyGrammarAutogeneratorInfo("object_property_setting");
yield return new AmmyGrammarAutogeneratorInfo("ammy_property_name").AsOneOf("identifier");
yield return new AmmyGrammarAutogeneratorInfo("ammy_property_value")
.AsOneOf("primary_expression", "ammy_bind");
yield return new AmmyGrammarAutogeneratorInfo("primary_expression").AsOneOf("literal");
yield return new AmmyGrammarAutogeneratorInfo("expression").AsOneOf("primary_expression");
{
var el = new AmmyGrammarAutogeneratorInfo("mixin_or_alias_argument").AsOneOf("identifier");
//var list = el.GetList();
var list = new AmmyGrammarAutogeneratorInfo(el.TerminalName + "s").AsListOf<object>();
yield return el;
yield return list;
yield return list.GetOptional();
}
// ========================================== objects
{
yield return new AmmyGrammarAutogeneratorInfo("object_definition");
var el =new AmmyGrammarAutogeneratorInfo("object_name").Single();
yield return el;
yield return el.GetOptional();
}
{
var el = new AmmyGrammarAutogeneratorInfo("statement")
.AsOneOf(
nameof(X.mixin_definition),
nameof(X.object_definition)
);
var list = el.GetList();
yield return el;
yield return list;
yield return list.GetOptional();
}
yield return new AmmyGrammarAutogeneratorInfo("ammyCode")
.AsListOf<object>();
}
public static AmmyGrammarAutogeneratorInfo[] Items()
{
var nt = GetItemsInternal().Select(a =>
{
switch (a)
{
case string s:
return new AmmyGrammarAutogeneratorInfo(s);
case AmmyGrammarAutogeneratorInfo i:
return i;
default:
throw new NotSupportedException();
}
}).ToArray();
return nt;
}
private static IEnumerable<IEnumerable<AmmyGrammarAutogeneratorInfo>> GetBindingSettings()
{
string GetValueToken(Type t)
{
if (t == typeof(string))
return nameof(X.TheStringLiteral);
if (t == typeof(bool))
return nameof(X.boolean);
if (t == typeof(int))
return nameof(X.Number);
return null;
}
IEnumerable<AmmyGrammarAutogeneratorInfo> Build<T>(string name, string rule=null)
{
var type = typeof(T);
var el = new AmmyGrammarAutogeneratorInfo("ammy_bind_set_" + name);
var valueToken = GetValueToken(type);
if (valueToken is null)
{
if (type.IsEnum)
{
var names = Enum.GetNames(type);
var items = names.Select(a => "ToTerm(" + a.CsEncode() + ")");
var enums = new AmmyGrammarAutogeneratorInfo("ammy_bind_set_" + name + "_enum_values")
{
BaseClass = nameof(EnumValueNode),
Rule = string.Join(" | ", items)
};
yield return enums;
valueToken = enums.TerminalName;
}
}
el.Rule = rule;
if (valueToken != null)
{
var a = new[]
{
$"ToTerm({name.CsEncode()})",
":".CsEncode(),
valueToken,
nameof(X.comma_opt)
};
el.Rule = string.Join(" + ", a);
el.Punctuations.Add(name);
el.Punctuations.Add(":");
el.Map = new[] {0};
el.Keyword = name;
}
yield return el;
}
/*yield return Build<string>("BindingGroupName");
yield return Build<bool>("BindsDirectlyToSource");
yield return Build<object>("Mode", "");
*/
yield return Build<XBindingMode>("Mode");
// yield return Build<object>("Converter");
// yield return Build<object>("ConverterCulture");
// yield return Build<object>("ConverterParameter");
yield return Build<bool>("NotifyOnSourceUpdated");
yield return Build<bool>("NotifyOnTargetUpdated");
yield return Build<bool>("NotifyOnValidationError");
yield return Build<bool>("ValidatesOnExceptions");
yield return Build<bool>("ValidatesOnDataErrors");
yield return Build<bool>("ValidatesOnNotifyDataErrors");
yield return Build<string>("StringFormat");
yield return Build<string>("BindingGroupName");
yield return Build<int>("FallbackValue");
yield return Build<bool>("IsAsync");
// yield return Build<XUpdateSourceTrigger>("UpdateSourceTrigger");
// yield return Build<object>(ValidationRules);
// yield return Build<object>("TargetNullValue");
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UIKit;
using static zsquared.C_MessageBox;
using zsquared;
namespace vitavol
{
public partial class VC_SCAddVolHours : UIViewController
{
C_Global Global;
C_VitaUser LoggedInUser;
C_VitaSite SelectedSite;
C_ItemPicker<C_VitaUser> UserItemPicker;
C_ItemPicker<C_YMD> DatePicker;
public VC_SCAddVolHours (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
Global = myAppDelegate.Global;
LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId);
SelectedSite = Global.GetSiteFromSlugNoFetch(Global.SelectedSiteSlug);
UITapGestureRecognizer labelTap = new UITapGestureRecognizer(() =>
{
C_Common.DropFirstResponder(View);
});
L_Title.UserInteractionEnabled = true;
L_Title.AddGestureRecognizer(labelTap);
L_SiteName.UserInteractionEnabled = true;
L_SiteName.AddGestureRecognizer(labelTap);
B_Back.TouchUpInside += (sender, e) =>
PerformSegue("Segue_SCAddVolHoursToSCVolHours", this);
B_Cancel.TouchUpInside += (sender, e) =>
PerformSegue("Segue_SCAddVolHoursToSCVolHours", this);
B_Save.TouchUpInside += (sender, e) =>
{
double hours = 0.0f;
double.TryParse(TB_Hours.Text, out hours);
C_VitaUser userPicked = UserItemPicker.Selection;
C_IOResult ior = null;
AI_Busy.StartAnimating();
EnableUI(false);
Task.Run(async () =>
{
if (Global.SelectedWorkItem == null)
{
// we are to create a new workitem
C_WorkLogItem wi = new C_WorkLogItem(userPicked.id);
wi.Date = DatePicker.Selection;
wi.SiteSlug = SelectedSite.Slug;
wi.Hours = (float)hours;
//SelectedSite.WorkLogItems.Add(wi);
ior = await Global.AddWorkLogItem(userPicked, LoggedInUser.Token, wi);
}
else
{
// if the user is changed, then we need to delete the old work item (since these are under users)
C_VitaUser originalUser = FindUserForWorkItem(Global.SelectedWorkItem);
if (originalUser.id != UserItemPicker.Selection.id)
{
C_VitaUser oldUser = FindUserForWorkItem(Global.SelectedWorkItem);
if (oldUser != null)
ior = await Global.RemoveWorkLogItem(oldUser, LoggedInUser.Token, Global.SelectedWorkItem);
Global.SelectedWorkItem.Hours = (float)hours;
Global.SelectedWorkItem.Date = DatePicker.Selection;
ior = await Global.AddWorkLogItem(userPicked, LoggedInUser.Token, Global.SelectedWorkItem);
}
else
{
Global.SelectedWorkItem.Hours = (float)hours;
Global.SelectedWorkItem.Date = DatePicker.Selection;
ior = await Global.UpdateWorkLogItem(userPicked, LoggedInUser.Token, Global.SelectedWorkItem);
}
}
async void p()
{
if (!ior.Success)
{
E_MessageBoxResults mbres = await MessageBox(this,
"Error",
"Unable to save the work items.",
E_MessageBoxButtons.Ok);
}
AI_Busy.StopAnimating();
EnableUI(true);
PerformSegue("Segue_SCAddVolHoursToSCVolHours", this);
}
UIApplication.SharedApplication.InvokeOnMainThread(p);
});
};
TB_Hours.AddTarget((sender, e) =>
{
SetSaveEnabled();
}, UIControlEvent.AllEditingEvents);
TB_Volunteer.AddTarget((sender, e) =>
{
SetSaveEnabled();
}, UIControlEvent.AllEditingEvents);
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
C_Common.SetUIColors(View);
L_SiteName.Text = SelectedSite.Name;
// build the list of volunteers to choose from
List<C_VitaUser> users = Global.GetAllUsersNoCache();
List<C_VitaUser> volunteers = new List<C_VitaUser>();
foreach (C_VitaUser user in users)
if (user.HasVolunteer) volunteers.Add(user);
volunteers.Sort(C_VitaUser.CompareByNameToLower);
UserItemPicker = new C_ItemPicker<C_VitaUser>(TB_Volunteer, volunteers);
List<C_YMD> dates = new List<C_YMD>();
foreach (C_CalendarEntry ce in SelectedSite.SiteCalendar)
{
if (ce.SiteIsOpen && !dates.Contains(ce.Date))
dates.Add(ce.Date);
}
dates.Sort(C_YMD.CompareYMD);
DatePicker = new C_ItemPicker<C_YMD>(TB_Date, dates);
if (Global.CalendarDate < dates[0])
Global.CalendarDate = dates[0];
if (Global.SelectedWorkItem == null)
DatePicker.SetSelection(Global.CalendarDate);
if (Global.SelectedWorkItem != null)
{
TB_Hours.Text = Global.SelectedWorkItem.Hours.ToString();
C_VitaUser suser = Global.GetUserFromCacheNoFetch(Global.SelectedWorkItem.UserId);
if (suser == null)
suser = FindUserForWorkItem(Global.SelectedWorkItem);
if (suser != null)
UserItemPicker.SetSelection(suser);
DatePicker.SetSelection(Global.SelectedWorkItem.Date);
}
SetSaveEnabled();
}
private void EnableUI(bool en)
{
C_Common.EnableUI(View, en);
B_Save.Enabled = en && !(string.IsNullOrWhiteSpace(TB_Hours.Text) || string.IsNullOrWhiteSpace(TB_Volunteer.Text));
}
private void SetSaveEnabled()
{
bool en = !(string.IsNullOrWhiteSpace(TB_Hours.Text) || string.IsNullOrWhiteSpace(TB_Volunteer.Text));
B_Save.Enabled = en;
}
private C_VitaUser FindUserForWorkItem(C_WorkLogItem wi)
{
C_VitaUser user = null;
// the backend is supposed to store the UserId; in the case where it doesn't we do another search for the user
foreach (C_VitaUser u in Global.UserCache)
{
bool found = false;
foreach (C_WorkLogItem wx in u.WorkItems)
{
if (wx.id == wi.id)
{
found = true;
user = u;
}
}
if (found)
break;
}
return user;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace RemoteEventReceiverWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Dos.Common
{
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
/// </summary>
internal sealed class JsonParser
{
enum Token
{
None = -1, // Used to denote no Lookahead available
Curly_Open,
Curly_Close,
Squared_Open,
Squared_Close,
Colon,
Comma,
String,
Number,
True,
False,
Null,
NoQuotes // by itdos.com 2016-05-10
}
readonly string json;
readonly StringBuilder s = new StringBuilder(); // used for inner string parsing " \"\r\n\u1234\'\t "
Token lookAheadToken = Token.None;
int index;
internal JsonParser(string json)
{
this.json = json;
}
public object Decode()
{
return ParseValue();
}
private Dictionary<string, object> ParseObject()
{
Dictionary<string, object> table = new Dictionary<string, object>();
ConsumeToken(); // {
while (true)
{
switch (LookAhead())
{
case Token.Comma:
ConsumeToken();
break;
case Token.Curly_Close:
ConsumeToken();
return table;
#region by itdos.com 2016-05-10
case Token.NoQuotes:
{
// name
string name = "";//ParseString();
index--;
ConsumeToken();
s.Length = 0;
int runIndex = -1;
while (index < json.Length)
{
var c = json[index++];
if (c == ' ' || c == ':')
{
if (runIndex != -1)
{
if (s.Length == 0)
name = json.Substring(runIndex, index - runIndex - 1);
s.Append(json, runIndex, index - runIndex - 1);
}
name = s.ToString();
index--;
break;
}
if (c != '\\')
{
if (runIndex == -1)
runIndex = index - 1;
continue;
}
}
//index++;
// :
if (NextToken() != Token.Colon)
{
throw new Exception("Expected colon at index " + index);
}
// value
object value = ParseValue();
table[name] = value;
}
break;
#endregion
default:
{
// name
string name = ParseString();
// :
if (NextToken() != Token.Colon)
{
throw new Exception("Expected colon at index " + index);
}
// value
object value = ParseValue();
table[name] = value;
}
break;
}
}
}
private List<object> ParseArray()
{
List<object> array = new List<object>();
ConsumeToken(); // [
while (true)
{
switch (LookAhead())
{
case Token.Comma:
ConsumeToken();
break;
case Token.Squared_Close:
ConsumeToken();
return array;
default:
array.Add(ParseValue());
break;
}
}
}
private object ParseValue()
{
switch (LookAhead())
{
case Token.Number:
return ParseNumber();
case Token.String:
return ParseString();
case Token.Curly_Open:
return ParseObject();
case Token.Squared_Open:
return ParseArray();
case Token.True:
ConsumeToken();
return true;
case Token.False:
ConsumeToken();
return false;
case Token.Null:
ConsumeToken();
return null;
}
throw new Exception("Unrecognized token at index" + index);
}
private string ParseString()
{
ConsumeToken(); // "
s.Length = 0;
int runIndex = -1;
while (index < json.Length)
{
var c = json[index++];
if (c == '"')
{
if (runIndex != -1)
{
if (s.Length == 0)
return json.Substring(runIndex, index - runIndex - 1);
s.Append(json, runIndex, index - runIndex - 1);
}
return s.ToString();
}
if (c != '\\')
{
if (runIndex == -1)
runIndex = index - 1;
continue;
}
if (index == json.Length) break;
if (runIndex != -1)
{
s.Append(json, runIndex, index - runIndex - 1);
runIndex = -1;
}
switch (json[index++])
{
case '"':
s.Append('"');
break;
case '\\':
s.Append('\\');
break;
case '/':
s.Append('/');
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
{
int remainingLength = json.Length - index;
if (remainingLength < 4) break;
// parse the 32 bit hex into an integer codepoint
uint codePoint = ParseUnicode(json[index], json[index + 1], json[index + 2], json[index + 3]);
s.Append((char)codePoint);
// skip 4 chars
index += 4;
}
break;
}
}
throw new Exception("Unexpectedly reached end of string");
}
private uint ParseSingleChar(char c1, uint multipliyer)
{
uint p1 = 0;
if (c1 >= '0' && c1 <= '9')
p1 = (uint)(c1 - '0') * multipliyer;
else if (c1 >= 'A' && c1 <= 'F')
p1 = (uint)((c1 - 'A') + 10) * multipliyer;
else if (c1 >= 'a' && c1 <= 'f')
p1 = (uint)((c1 - 'a') + 10) * multipliyer;
return p1;
}
private uint ParseUnicode(char c1, char c2, char c3, char c4)
{
uint p1 = ParseSingleChar(c1, 0x1000);
uint p2 = ParseSingleChar(c2, 0x100);
uint p3 = ParseSingleChar(c3, 0x10);
uint p4 = ParseSingleChar(c4, 1);
return p1 + p2 + p3 + p4;
}
private long CreateLong(string s)
{
long num = 0;
bool neg = false;
foreach (char cc in s)
{
if (cc == '-')
neg = true;
else if (cc == '+')
neg = false;
else
{
num *= 10;
num += (int)(cc - '0');
}
}
return neg ? -num : num;
}
private object ParseNumber()
{
ConsumeToken();
// Need to start back one place because the first digit is also a token and would have been consumed
var startIndex = index - 1;
bool dec = false;
do
{
if (index == json.Length)
break;
var c = json[index];
if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')
{
if (c == '.' || c == 'e' || c == 'E')
dec = true;
if (++index == json.Length)
break;//throw new Exception("Unexpected end of string whilst parsing number");
continue;
}
break;
} while (true);
if (dec)
{
string s = json.Substring(startIndex, index - startIndex);
return double.Parse(s, NumberFormatInfo.InvariantInfo);
}
long num;
#region by itdos.com 2016-04-26
var str = json.Substring(startIndex, index - startIndex).TrimStart('-');
if (str.Length >= 19)
{
return ulong.Parse(str);
//var ul = ulong.Parse(str);
//if (ul > long.MaxValue)
//{
// return ul;
//}
}
#endregion
return JSON.CreateLong(out num, json, startIndex, index - startIndex);
}
private Token LookAhead()
{
if (lookAheadToken != Token.None) return lookAheadToken;
return lookAheadToken = NextTokenCore();
}
private void ConsumeToken()
{
lookAheadToken = Token.None;
}
private Token NextToken()
{
var result = lookAheadToken != Token.None ? lookAheadToken : NextTokenCore();
lookAheadToken = Token.None;
return result;
}
private Token NextTokenCore()
{
char c;
// Skip past whitespace
do
{
c = json[index];
if (c > ' ') break;
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break;
} while (++index < json.Length);
if (index == json.Length)
{
throw new Exception("Reached end of string unexpectedly");
}
c = json[index];
index++;
switch (c)
{
default:
return Token.NoQuotes;
case '{':
return Token.Curly_Open;
case '}':
return Token.Curly_Close;
case '[':
return Token.Squared_Open;
case ']':
return Token.Squared_Close;
case ',':
return Token.Comma;
case '"':
return Token.String;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '+':
case '.':
return Token.Number;
case ':':
return Token.Colon;
case 'f':
if (json.Length - index >= 4 &&
json[index + 0] == 'a' &&
json[index + 1] == 'l' &&
json[index + 2] == 's' &&
json[index + 3] == 'e')
{
index += 4;
return Token.False;
}
break;
case 't':
if (json.Length - index >= 3 &&
json[index + 0] == 'r' &&
json[index + 1] == 'u' &&
json[index + 2] == 'e')
{
index += 3;
return Token.True;
}
break;
case 'n':
if (json.Length - index >= 3 &&
json[index + 0] == 'u' &&
json[index + 1] == 'l' &&
json[index + 2] == 'l')
{
index += 3;
return Token.Null;
}
break;
}
throw new Exception("Could not find token at index " + --index);
}
}
}
| |
/*
* CKEditor Html Editor Provider for DotNetNuke
* ========
* http://dnnckeditor.codeplex.com/
* Copyright (C) Ingo Herbote
*
* The software, this file and its contents are subject to the CKEditor Provider
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of the CKEditor Provider.
*/
namespace WatchersNET.CKEditor.Browser
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.FileSystem;
using WatchersNET.CKEditor.Objects;
using WatchersNET.CKEditor.Utilities;
/// <summary>
/// The File Upload Handler
/// </summary>
public class FileUploader : IHttpHandler
{
/// <summary>
/// The JavaScript Serializer
/// </summary>
private readonly JavaScriptSerializer js = new JavaScriptSerializer();
/// <summary>
/// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance.
/// </summary>
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether [override files].
/// </summary>
/// <value>
/// <c>true</c> if [override files]; otherwise, <c>false</c>.
/// </value>
private bool OverrideFiles
{
get
{
return HttpContext.Current.Request["overrideFiles"].Equals("1")
|| HttpContext.Current.Request["overrideFiles"].Equals(
"true",
StringComparison.InvariantCultureIgnoreCase);
}
}
/// <summary>
/// Gets the storage folder.
/// </summary>
/// <value>
/// The storage folder.
/// </value>
private IFolderInfo StorageFolder
{
get
{
return FolderManager.Instance.GetFolder(Convert.ToInt32(HttpContext.Current.Request["storageFolderID"]));
}
}
/// <summary>
/// Gets the storage folder.
/// </summary>
/// <value>
/// The storage folder.
/// </value>
private PortalSettings PortalSettings
{
get
{
return new PortalSettings(Convert.ToInt32(HttpContext.Current.Request["portalID"]));
}
}
/// <summary>
/// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
/// </summary>
/// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("Pragma", "no-cache");
context.Response.AddHeader("Cache-Control", "private, no-cache");
this.HandleMethod(context);
}
/// <summary>
/// Returns the options.
/// </summary>
/// <param name="context">The context.</param>
private static void ReturnOptions(HttpContext context)
{
context.Response.AddHeader("Allow", "DELETE,GET,HEAD,POST,PUT,OPTIONS");
context.Response.StatusCode = 200;
}
/// <summary>
/// Handle request based on method
/// </summary>
/// <param name="context">The context.</param>
private void HandleMethod(HttpContext context)
{
switch (context.Request.HttpMethod)
{
case "HEAD":
case "GET":
/*if (GivenFilename(context))
{
this.DeliverFile(context);
}
else
{
ListCurrentFiles(context);
}*/
break;
case "POST":
case "PUT":
this.UploadFile(context);
break;
case "OPTIONS":
ReturnOptions(context);
break;
default:
context.Response.ClearHeaders();
context.Response.StatusCode = 405;
break;
}
}
/// <summary>
/// Uploads the file.
/// </summary>
/// <param name="context">The context.</param>
private void UploadFile(HttpContext context)
{
var statuses = new List<FilesUploadStatus>();
this.UploadWholeFile(context, statuses);
this.WriteJsonIframeSafe(context, statuses);
}
/// <summary>
/// Uploads the whole file.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="statuses">The statuses.</param>
private void UploadWholeFile(HttpContext context, List<FilesUploadStatus> statuses)
{
for (int i = 0; i < context.Request.Files.Count; i++)
{
var file = context.Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
if (!string.IsNullOrEmpty(fileName))
{
// Replace dots in the name with underscores (only one dot can be there... security issue).
fileName = Regex.Replace(fileName, @"\.(?![^.]*$)", "_", RegexOptions.None);
// Check for Illegal Chars
if (Utility.ValidateFileName(fileName))
{
fileName = Utility.CleanFileName(fileName);
}
// Convert Unicode Chars
fileName = Utility.ConvertUnicodeChars(fileName);
}
else
{
throw new HttpRequestValidationException("File does not have a name");
}
if (fileName.Length > 220)
{
fileName = fileName.Substring(fileName.Length - 220);
}
var fileNameNoExtenstion = Path.GetFileNameWithoutExtension(fileName);
// Rename File if Exists
if (!this.OverrideFiles)
{
var counter = 0;
while (File.Exists(Path.Combine(this.StorageFolder.PhysicalPath, fileName)))
{
counter++;
fileName = string.Format(
"{0}_{1}{2}",
fileNameNoExtenstion,
counter,
Path.GetExtension(file.FileName));
}
}
FileManager.Instance.AddFile(this.StorageFolder, fileName, file.InputStream, this.OverrideFiles);
var fullName = Path.GetFileName(fileName);
statuses.Add(new FilesUploadStatus(fullName, file.ContentLength));
}
}
/// <summary>
/// Writes the JSON iFrame safe.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="statuses">The statuses.</param>
private void WriteJsonIframeSafe(HttpContext context, List<FilesUploadStatus> statuses)
{
context.Response.AddHeader("Vary", "Accept");
try
{
context.Response.ContentType = context.Request["HTTP_ACCEPT"].Contains("application/json")
? "application/json"
: "text/plain";
}
catch
{
context.Response.ContentType = "text/plain";
}
var jsonObj = this.js.Serialize(statuses.ToArray());
context.Response.Write(jsonObj);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Orleans.Runtime.Scheduler
{
[DebuggerDisplay("WorkItemGroup Name={Name} State={state}")]
internal class WorkItemGroup : IWorkItem
{
private enum WorkGroupStatus
{
Waiting = 0,
Runnable = 1,
Running = 2,
Shutdown = 3
}
private readonly ILogger log;
private readonly OrleansTaskScheduler masterScheduler;
private WorkGroupStatus state;
private readonly Object lockable;
private readonly Queue<Task> workItems;
private long totalItemsEnQueued; // equals total items queued, + 1
private long totalItemsProcessed;
private readonly QueueTrackingStatistic queueTracking;
private TimeSpan totalQueuingDelay;
private readonly long quantumExpirations;
private readonly int workItemGroupStatisticsNumber;
internal ActivationTaskScheduler TaskRunner { get; private set; }
public DateTime TimeQueued { get; set; }
public TimeSpan TimeSinceQueued
{
get { return Utils.Since(TimeQueued); }
}
public ISchedulingContext SchedulingContext { get; set; }
public bool IsSystemPriority
{
get { return SchedulingUtils.IsSystemPriorityContext(SchedulingContext); }
}
internal bool IsSystemGroup
{
get { return SchedulingUtils.IsSystemContext(SchedulingContext); }
}
public string Name { get { return SchedulingContext == null ? "unknown" : SchedulingContext.Name; } }
internal int ExternalWorkItemCount
{
get { lock (lockable) { return WorkItemCount; } }
}
private int WorkItemCount
{
get { return workItems.Count; }
}
internal float AverageQueueLenght
{
get
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectShedulerQueuesStats)
{
return queueTracking.AverageQueueLength;
}
#endif
return 0;
}
}
internal float NumEnqueuedRequests
{
get
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectShedulerQueuesStats)
{
return queueTracking.NumEnqueuedRequests;
}
#endif
return 0;
}
}
internal float ArrivalRate
{
get
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectShedulerQueuesStats)
{
return queueTracking.ArrivalRate;
}
#endif
return 0;
}
}
private bool IsActive
{
get
{
return WorkItemCount != 0;
}
}
// This is the maximum number of work items to be processed in an activation turn.
// If this is set to zero or a negative number, then the full work queue is drained (MaxTimePerTurn allowing).
private const int MaxWorkItemsPerTurn = 0; // Unlimited
// This is a soft time limit on the duration of activation macro-turn (a number of micro-turns).
// If a activation was running its micro-turns longer than this, we will give up the thread.
// If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing).
public static TimeSpan ActivationSchedulingQuantum { get; set; }
// This is the maximum number of waiting threads (blocked in WaitForResponse) allowed
// per ActivationWorker. An attempt to wait when there are already too many threads waiting
// will result in a TooManyWaitersException being thrown.
//private static readonly int MaxWaitingThreads = 500;
internal WorkItemGroup(OrleansTaskScheduler sched, ISchedulingContext schedulingContext, ILoggerFactory loggerFactory)
{
masterScheduler = sched;
SchedulingContext = schedulingContext;
state = WorkGroupStatus.Waiting;
workItems = new Queue<Task>();
lockable = new Object();
totalItemsEnQueued = 0;
totalItemsProcessed = 0;
totalQueuingDelay = TimeSpan.Zero;
quantumExpirations = 0;
TaskRunner = new ActivationTaskScheduler(this, loggerFactory);
log = IsSystemPriority ? loggerFactory.CreateLogger($"{this.GetType().Namespace} {Name}.{this.GetType().Name}") : loggerFactory.CreateLogger<WorkItemGroup>();
if (StatisticsCollector.CollectShedulerQueuesStats)
{
queueTracking = new QueueTrackingStatistic("Scheduler." + SchedulingContext.Name);
queueTracking.OnStartExecution();
}
if (StatisticsCollector.CollectPerWorkItemStats)
{
workItemGroupStatisticsNumber = SchedulerStatisticsGroup.RegisterWorkItemGroup(SchedulingContext.Name, SchedulingContext,
() =>
{
var sb = new StringBuilder();
lock (lockable)
{
sb.Append("QueueLength = " + WorkItemCount);
sb.Append(String.Format(", State = {0}", state));
if (state == WorkGroupStatus.Runnable)
sb.Append(String.Format("; oldest item is {0} old", workItems.Count >= 0 ? workItems.Peek().ToString() : "null"));
}
return sb.ToString();
});
}
}
/// <summary>
/// Adds a task to this activation.
/// If we're adding it to the run list and we used to be waiting, now we're runnable.
/// </summary>
/// <param name="task">The work item to add.</param>
public void EnqueueTask(Task task)
{
lock (lockable)
{
#if DEBUG
if (log.IsEnabled(LogLevel.Trace)) log.Trace("EnqueueWorkItem {0} into {1} when TaskScheduler.Current={2}", task, SchedulingContext, TaskScheduler.Current);
#endif
if (state == WorkGroupStatus.Shutdown)
{
ReportWorkGroupProblem(
String.Format("Enqueuing task {0} to a stopped work item group. Going to ignore and not execute it. "
+ "The likely reason is that the task is not being 'awaited' properly.", task),
ErrorCode.SchedulerNotEnqueuWorkWhenShutdown);
task.Ignore(); // Ignore this Task, so in case it is faulted it will not cause UnobservedException.
return;
}
long thisSequenceNumber = totalItemsEnQueued++;
int count = WorkItemCount;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectShedulerQueuesStats)
queueTracking.OnEnQueueRequest(1, count);
if (StatisticsCollector.CollectGlobalShedulerStats)
SchedulerStatisticsGroup.OnWorkItemEnqueue();
#endif
workItems.Enqueue(task);
int maxPendingItemsLimit = masterScheduler.MaxPendingItemsLimit.SoftLimitThreshold;
if (maxPendingItemsLimit > 0 && count > maxPendingItemsLimit)
{
log.Warn(ErrorCode.SchedulerTooManyPendingItems, String.Format("{0} pending work items for group {1}, exceeding the warning threshold of {2}",
count, Name, maxPendingItemsLimit));
}
if (state != WorkGroupStatus.Waiting) return;
state = WorkGroupStatus.Runnable;
#if DEBUG
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Add to RunQueue {0}, #{1}, onto {2}", task, thisSequenceNumber, SchedulingContext);
#endif
masterScheduler.RunQueue.Add(this);
}
}
/// <summary>
/// Shuts down this work item group so that it will not process any additional work items, even if they
/// have already been queued.
/// </summary>
internal void Stop()
{
lock (lockable)
{
if (IsActive)
{
ReportWorkGroupProblem(
String.Format("WorkItemGroup is being stoped while still active. workItemCount = {0}."
+ "The likely reason is that the task is not being 'awaited' properly.", WorkItemCount),
ErrorCode.SchedulerWorkGroupStopping);
}
if (state == WorkGroupStatus.Shutdown)
{
log.Warn(ErrorCode.SchedulerWorkGroupShuttingDown, "WorkItemGroup is already shutting down {0}", this.ToString());
return;
}
state = WorkGroupStatus.Shutdown;
if (StatisticsCollector.CollectPerWorkItemStats)
SchedulerStatisticsGroup.UnRegisterWorkItemGroup(workItemGroupStatisticsNumber);
if (StatisticsCollector.CollectGlobalShedulerStats)
SchedulerStatisticsGroup.OnWorkItemDrop(WorkItemCount);
if (StatisticsCollector.CollectShedulerQueuesStats)
queueTracking.OnStopExecution();
foreach (Task task in workItems)
{
// Ignore all queued Tasks, so in case they are faulted they will not cause UnobservedException.
task.Ignore();
}
workItems.Clear();
}
}
#region IWorkItem Members
public WorkItemType ItemType
{
get { return WorkItemType.WorkItemGroup; }
}
// Execute one or more turns for this activation.
// This method is always called in a single-threaded environment -- that is, no more than one
// thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc.
public void Execute()
{
lock (lockable)
{
if (state == WorkGroupStatus.Shutdown)
{
if (!IsActive) return; // Don't mind if no work has been queued to this work group yet.
ReportWorkGroupProblemWithBacktrace(
"Cannot execute work items in a work item group that is in a shutdown state.",
ErrorCode.SchedulerNotExecuteWhenShutdown); // Throws InvalidOperationException
return;
}
state = WorkGroupStatus.Running;
}
var thread = WorkerPoolThread.CurrentWorkerThread;
try
{
// Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation
int count = 0;
var stopwatch = new Stopwatch();
stopwatch.Start();
do
{
lock (lockable)
{
if (state == WorkGroupStatus.Shutdown)
{
if (WorkItemCount > 0)
log.Warn(ErrorCode.SchedulerSkipWorkStopping, "Thread {0} is exiting work loop due to Shutdown state {1} while still having {2} work items in the queue.",
thread.ToString(), this.ToString(), WorkItemCount);
else
if(log.IsEnabled(LogLevel.Debug)) log.Debug("Thread {0} is exiting work loop due to Shutdown state {1}. Has {2} work items in the queue.",
thread.ToString(), this.ToString(), WorkItemCount);
break;
}
// Check the cancellation token (means that the silo is stopping)
if (thread.CancelToken.IsCancellationRequested)
{
log.Warn(ErrorCode.SchedulerSkipWorkCancelled, "Thread {0} is exiting work loop due to cancellation token. WorkItemGroup: {1}, Have {2} work items in the queue.",
thread.ToString(), this.ToString(), WorkItemCount);
break;
}
}
// Get the first Work Item on the list
Task task;
lock (lockable)
{
if (workItems.Count > 0)
task = workItems.Dequeue();
else // If the list is empty, then we're done
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectGlobalShedulerStats)
SchedulerStatisticsGroup.OnWorkItemDequeue();
#endif
#if DEBUG
if (log.IsEnabled(LogLevel.Trace)) log.Trace("About to execute task {0} in SchedulingContext={1}", task, SchedulingContext);
#endif
var taskStart = stopwatch.Elapsed;
try
{
thread.CurrentTask = task;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectTurnsStats)
SchedulerStatisticsGroup.OnTurnExecutionStartsByWorkGroup(workItemGroupStatisticsNumber, thread.WorkerThreadStatisticsNumber, SchedulingContext);
#endif
TaskRunner.RunTask(task);
}
catch (Exception ex)
{
log.Error(ErrorCode.SchedulerExceptionFromExecute, String.Format("Worker thread caught an exception thrown from Execute by task {0}", task), ex);
throw;
}
finally
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectTurnsStats)
SchedulerStatisticsGroup.OnTurnExecutionEnd(Utils.Since(thread.CurrentStateStarted));
if (StatisticsCollector.CollectThreadTimeTrackingStats)
thread.threadTracking.IncrementNumberOfProcessed();
#endif
totalItemsProcessed++;
var taskLength = stopwatch.Elapsed - taskStart;
if (taskLength > OrleansTaskScheduler.TurnWarningLengthThreshold)
{
SchedulerStatisticsGroup.NumLongRunningTurns.Increment();
log.Warn(ErrorCode.SchedulerTurnTooLong3, "Task {0} in WorkGroup {1} took elapsed time {2:g} for execution, which is longer than {3}. Running on thread {4}",
OrleansTaskExtentions.ToString(task), SchedulingContext.ToString(), taskLength, OrleansTaskScheduler.TurnWarningLengthThreshold, thread.ToString());
}
thread.CurrentTask = null;
}
count++;
}
while (((MaxWorkItemsPerTurn <= 0) || (count <= MaxWorkItemsPerTurn)) &&
((ActivationSchedulingQuantum <= TimeSpan.Zero) || (stopwatch.Elapsed < ActivationSchedulingQuantum)));
stopwatch.Stop();
}
catch (Exception ex)
{
log.Error(ErrorCode.Runtime_Error_100032, String.Format("Worker thread {0} caught an exception thrown from IWorkItem.Execute", thread), ex);
}
finally
{
// Now we're not Running anymore.
// If we left work items on our run list, we're Runnable, and need to go back on the silo run queue;
// If our run list is empty, then we're waiting.
lock (lockable)
{
if (state != WorkGroupStatus.Shutdown)
{
if (WorkItemCount > 0)
{
state = WorkGroupStatus.Runnable;
masterScheduler.RunQueue.Add(this);
}
else
{
state = WorkGroupStatus.Waiting;
}
}
}
}
}
#endregion
public override string ToString()
{
return String.Format("{0}WorkItemGroup:Name={1},WorkGroupStatus={2}",
IsSystemGroup ? "System*" : "",
Name,
state);
}
public string DumpStatus()
{
lock (lockable)
{
var sb = new StringBuilder();
sb.Append(this);
sb.AppendFormat(". Currently QueuedWorkItems={0}; Total EnQueued={1}; Total processed={2}; Quantum expirations={3}; ",
WorkItemCount, totalItemsEnQueued, totalItemsProcessed, quantumExpirations);
if (AverageQueueLenght > 0)
{
sb.AppendFormat("average queue length at enqueue: {0}; ", AverageQueueLenght);
if (!totalQueuingDelay.Equals(TimeSpan.Zero) && totalItemsProcessed > 0)
{
sb.AppendFormat("average queue delay: {0}ms; ", totalQueuingDelay.Divide(totalItemsProcessed).TotalMilliseconds);
}
}
sb.AppendFormat("TaskRunner={0}; ", TaskRunner);
if (SchedulingContext != null)
{
sb.AppendFormat("Detailed SchedulingContext=<{0}>", SchedulingContext.DetailedStatus());
}
return sb.ToString();
}
}
private void ReportWorkGroupProblemWithBacktrace(string what, ErrorCode errorCode)
{
var st = Utils.GetStackTrace();
var msg = string.Format("{0} {1}", what, DumpStatus());
log.Warn(errorCode, msg + Environment.NewLine + " Called from " + st);
}
private void ReportWorkGroupProblem(string what, ErrorCode errorCode)
{
var msg = string.Format("{0} {1}", what, DumpStatus());
log.Warn(errorCode, msg);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
namespace System.Data.SqlClient
{
/// <devdoc> Class of variables for the Tds connection.
/// </devdoc>
internal static class TdsEnums
{
// internal tdsparser constants
public const string SQL_PROVIDER_NAME = Common.DbConnectionStringDefaults.ApplicationName;
public static readonly decimal SQL_SMALL_MONEY_MIN = new decimal(-214748.3648);
public static readonly decimal SQL_SMALL_MONEY_MAX = new decimal(214748.3647);
// HACK!!!
// Constant for SqlDbType.SmallVarBinary... store internal variable here instead of on
// SqlDbType so that it is not surfaced to the user!!! Related to dtc and the fact that
// the TransactionManager TDS stream is the only token left that uses VarBinarys instead of
// BigVarBinarys.
public const SqlDbType SmallVarBinary = (SqlDbType)(SqlDbType.Variant) + 1;
// network protocol string constants
public const string TCP = "tcp";
public const string NP = "np";
public const string RPC = "rpc";
public const string BV = "bv";
public const string ADSP = "adsp";
public const string SPX = "spx";
public const string VIA = "via";
public const string LPC = "lpc";
public const string ADMIN = "admin";
// network function string constants
public const string INIT_SSPI_PACKAGE = "InitSSPIPackage";
public const string INIT_SESSION = "InitSession";
public const string CONNECTION_GET_SVR_USER = "ConnectionGetSvrUser";
public const string GEN_CLIENT_CONTEXT = "GenClientContext";
// tdsparser packet handling constants
public const byte SOFTFLUSH = 0;
public const byte HARDFLUSH = 1;
public const byte IGNORE = 2;
// header constants
public const int HEADER_LEN = 8;
public const int HEADER_LEN_FIELD_OFFSET = 2;
public const int YUKON_HEADER_LEN = 12; //Yukon headers also include a MARS session id
public const int MARS_ID_OFFSET = 8;
public const int HEADERTYPE_QNOTIFICATION = 1;
public const int HEADERTYPE_MARS = 2;
public const int HEADERTYPE_TRACE = 3;
// other various constants
public const int SUCCEED = 1;
public const int FAIL = 0;
public const short TYPE_SIZE_LIMIT = 8000;
public const int MIN_PACKET_SIZE = 512;
// Login packet can be no greater than 4k until server sends us env-change
// increasing packet size.
public const int DEFAULT_LOGIN_PACKET_SIZE = 4096;
public const int MAX_PRELOGIN_PAYLOAD_LENGTH = 1024;
public const int MAX_PACKET_SIZE = 32768;
public const int MAX_SERVER_USER_NAME = 256; // obtained from luxor
// Severity 0 - 10 indicates informational (non-error) messages
// Severity 11 - 16 indicates errors that can be corrected by user (syntax errors, etc...)
// Severity 17 - 19 indicates failure due to insufficient resources in the server
// (max locks exceeded, not enough memory, other internal server limits reached, etc..)
// Severity 20 - 25 Severe problems with the server, connection terminated.
public const byte MIN_ERROR_CLASS = 11; // webdata 100667: This should actually be 11
public const byte MAX_USER_CORRECTABLE_ERROR_CLASS = 16;
public const byte FATAL_ERROR_CLASS = 20;
// Message types
public const byte MT_SQL = 1; // SQL command batch
public const byte MT_LOGIN = 2; // Login message for pre-Sphinx (before version 7.0)
public const byte MT_RPC = 3; // Remote procedure call
public const byte MT_TOKENS = 4; // Table response data stream
public const byte MT_BINARY = 5; // Unformatted binary response data (UNUSED)
public const byte MT_ATTN = 6; // Attention (break) signal
public const byte MT_BULK = 7; // Bulk load data
public const byte MT_OPEN = 8; // Set up subchannel (UNUSED)
public const byte MT_CLOSE = 9; // Close subchannel (UNUSED)
public const byte MT_ERROR = 10; // Protocol error detected
public const byte MT_ACK = 11; // Protocol acknowledgement (UNUSED)
public const byte MT_ECHO = 12; // Echo data (UNUSED)
public const byte MT_LOGOUT = 13; // Logout message (UNUSED)
public const byte MT_TRANS = 14; // Transaction Manager Interface
public const byte MT_OLEDB = 15; // ? (UNUSED)
public const byte MT_LOGIN7 = 16; // Login message for Sphinx (version 7) or later
public const byte MT_SSPI = 17; // SSPI message
public const byte MT_PRELOGIN = 18; // Pre-login handshake
// Message status bits
public const byte ST_EOM = 0x1; // Packet is end-of-message
public const byte ST_AACK = 0x2; // Packet acknowledges attention (server to client)
public const byte ST_IGNORE = 0x2; // Ignore this event (client to server)
public const byte ST_BATCH = 0x4; // Message is part of a batch.
public const byte ST_RESET_CONNECTION = 0x8; // Exec sp_reset_connection prior to processing message
public const byte ST_RESET_CONNECTION_PRESERVE_TRANSACTION = 0x10; // reset prior to processing, with preserving local tx
// TDS control tokens
public const byte SQLCOLFMT = 0xa1;
public const byte SQLPROCID = 0x7c;
public const byte SQLCOLNAME = 0xa0;
public const byte SQLTABNAME = 0xa4;
public const byte SQLCOLINFO = 0xa5;
public const byte SQLALTNAME = 0xa7;
public const byte SQLALTFMT = 0xa8;
public const byte SQLERROR = 0xaa;
public const byte SQLINFO = 0xab;
public const byte SQLRETURNVALUE = 0xac;
public const byte SQLRETURNSTATUS = 0x79;
public const byte SQLRETURNTOK = 0xdb;
public const byte SQLALTCONTROL = 0xaf;
public const byte SQLROW = 0xd1;
public const byte SQLNBCROW = 0xd2; // same as ROW with null-bit-compression support
public const byte SQLALTROW = 0xd3;
public const byte SQLDONE = 0xfd;
public const byte SQLDONEPROC = 0xfe;
public const byte SQLDONEINPROC = 0xff;
public const byte SQLOFFSET = 0x78;
public const byte SQLORDER = 0xa9;
public const byte SQLDEBUG_CMD = 0x60;
public const byte SQLLOGINACK = 0xad;
public const byte SQLFEATUREEXTACK = 0xae; // TDS 7.4 - feature ack
public const byte SQLSESSIONSTATE = 0xe4; // TDS 7.4 - connection resiliency session state
public const byte SQLENVCHANGE = 0xe3; // Environment change notification
public const byte SQLSECLEVEL = 0xed; // Security level token ???
public const byte SQLROWCRC = 0x39; // ROWCRC datastream???
public const byte SQLCOLMETADATA = 0x81; // Column metadata including name
public const byte SQLALTMETADATA = 0x88; // Alt column metadata including name
public const byte SQLSSPI = 0xed; // SSPI data
// Environment change notification streams
// TYPE on TDS ENVCHANGE token stream (from sql\ntdbms\include\odsapi.h)
//
public const byte ENV_DATABASE = 1; // Database changed
public const byte ENV_LANG = 2; // Language changed
public const byte ENV_CHARSET = 3; // Character set changed
public const byte ENV_PACKETSIZE = 4; // Packet size changed
public const byte ENV_LOCALEID = 5; // Unicode data sorting locale id
public const byte ENV_COMPFLAGS = 6; // Unicode data sorting comparison flags
public const byte ENV_COLLATION = 7; // SQL Collation
// The following are environment change tokens valid for Yukon or later.
public const byte ENV_BEGINTRAN = 8; // Transaction began
public const byte ENV_COMMITTRAN = 9; // Transaction committed
public const byte ENV_ROLLBACKTRAN = 10; // Transaction rolled back
public const byte ENV_ENLISTDTC = 11; // Enlisted in Distributed Transaction
public const byte ENV_DEFECTDTC = 12; // Defected from Distributed Transaction
public const byte ENV_LOGSHIPNODE = 13; // Realtime Log shipping primary node
public const byte ENV_PROMOTETRANSACTION = 15; // Promote Transaction
public const byte ENV_TRANSACTIONMANAGERADDRESS = 16; // Transaction Manager Address
public const byte ENV_TRANSACTIONENDED = 17; // Transaction Ended
public const byte ENV_SPRESETCONNECTIONACK = 18; // SP_Reset_Connection ack
public const byte ENV_USERINSTANCE = 19; // User Instance
public const byte ENV_ROUTING = 20; // Routing (ROR) information
public enum EnvChangeType : byte
{
ENVCHANGE_DATABASE = ENV_DATABASE,
ENVCHANGE_LANG = ENV_LANG,
ENVCHANGE_CHARSET = ENV_CHARSET,
ENVCHANGE_PACKETSIZE = ENV_PACKETSIZE,
ENVCHANGE_LOCALEID = ENV_LOCALEID,
ENVCHANGE_COMPFLAGS = ENV_COMPFLAGS,
ENVCHANGE_COLLATION = ENV_COLLATION,
ENVCHANGE_BEGINTRAN = ENV_BEGINTRAN,
ENVCHANGE_COMMITTRAN = ENV_COMMITTRAN,
ENVCHANGE_ROLLBACKTRAN = ENV_ROLLBACKTRAN,
ENVCHANGE_ENLISTDTC = ENV_ENLISTDTC,
ENVCHANGE_DEFECTDTC = ENV_DEFECTDTC,
ENVCHANGE_LOGSHIPNODE = ENV_LOGSHIPNODE,
ENVCHANGE_PROMOTETRANSACTION = ENV_PROMOTETRANSACTION,
ENVCHANGE_TRANSACTIONMANAGERADDRESS = ENV_TRANSACTIONMANAGERADDRESS,
ENVCHANGE_TRANSACTIONENDED = ENV_TRANSACTIONENDED,
ENVCHANGE_SPRESETCONNECTIONACK = ENV_SPRESETCONNECTIONACK,
ENVCHANGE_USERINSTANCE = ENV_USERINSTANCE,
ENVCHANGE_ROUTING = ENV_ROUTING
}
// done status stream bit masks
public const int DONE_MORE = 0x0001; // more command results coming
public const int DONE_ERROR = 0x0002; // error in command batch
public const int DONE_INXACT = 0x0004; // transaction in progress
public const int DONE_PROC = 0x0008; // done from stored proc
public const int DONE_COUNT = 0x0010; // count in done info
public const int DONE_ATTN = 0x0020; // oob ack
public const int DONE_INPROC = 0x0040; // like DONE_PROC except proc had error
public const int DONE_RPCINBATCH = 0x0080; // Done from RPC in batch
public const int DONE_SRVERROR = 0x0100; // Severe error in which resultset should be discarded
public const int DONE_FMTSENT = 0x8000; // fmt message sent, done_inproc req'd
// Feature Extension
public const byte FEATUREEXT_TERMINATOR = 0xFF;
public const byte FEATUREEXT_SRECOVERY = 0x01;
[Flags]
public enum FeatureExtension : uint
{
None = 0,
SessionRecovery = 1,
}
// Loginrec defines
public const byte MAX_LOG_NAME = 30; // TDS 4.2 login rec max name length
public const byte MAX_PROG_NAME = 10; // max length of loginrec program name
public const byte SEC_COMP_LEN = 8; // length of security compartments
public const byte MAX_PK_LEN = 6; // max length of TDS packet size
public const byte MAX_NIC_SIZE = 6; // The size of a MAC or client address
public const byte SQLVARIANT_SIZE = 2; // size of the fixed portion of a sql variant (type, cbPropBytes)
public const byte VERSION_SIZE = 4; // size of the tds version (4 unsigned bytes)
public const int CLIENT_PROG_VER = 0x06000000; // Client interface version
public const int YUKON_LOG_REC_FIXED_LEN = 0x5e;
// misc
public const int TEXT_TIME_STAMP_LEN = 8;
public const int COLLATION_INFO_LEN = 4;
/*
public const byte INT4_LSB_HI = 0; // lsb is low byte (e.g. 68000)
// public const byte INT4_LSB_LO = 1; // lsb is low byte (e.g. VAX)
public const byte INT2_LSB_HI = 2; // lsb is low byte (e.g. 68000)
// public const byte INT2_LSB_LO = 3; // lsb is low byte (e.g. VAX)
public const byte FLT_IEEE_HI = 4; // lsb is low byte (e.g. 68000)
public const byte CHAR_ASCII = 6; // ASCII character set
public const byte TWO_I4_LSB_HI = 8; // lsb is low byte (e.g. 68000
// public const byte TWO_I4_LSB_LO = 9; // lsb is low byte (e.g. VAX)
// public const byte FLT_IEEE_LO = 10; // lsb is low byte (e.g. MSDOS)
public const byte FLT4_IEEE_HI = 12; // IEEE 4-byte floating point -lsb is high byte
// public const byte FLT4_IEEE_LO = 13; // IEEE 4-byte floating point -lsb is low byte
public const byte TWO_I2_LSB_HI = 16; // lsb is high byte
// public const byte TWO_I2_LSB_LO = 17; // lsb is low byte
public const byte LDEFSQL = 0; // server sends its default
public const byte LDEFUSER = 0; // regular old user
public const byte LINTEGRATED = 8; // integrated security login
*/
/* Versioning scheme table:
Client sends:
0x70000000 -> Sphinx
0x71000000 -> Shiloh RTM
0x71000001 -> Shiloh SP1
0x72xx0002 -> Yukon RTM
Server responds:
0x07000000 -> Sphinx // Notice server response format is different for bwd compat
0x07010000 -> Shiloh RTM // Notice server response format is different for bwd compat
0x71000001 -> Shiloh SP1
0x72xx0002 -> Yukon RTM
*/
// Shiloh SP1 and beyond versioning scheme:
// Majors:
public const int YUKON_MAJOR = 0x72; // the high-byte is sufficient to distinguish later versions
public const int KATMAI_MAJOR = 0x73;
public const int DENALI_MAJOR = 0x74;
// Increments:
public const int YUKON_INCREMENT = 0x09;
public const int KATMAI_INCREMENT = 0x0b;
public const int DENALI_INCREMENT = 0x00;
// Minors:
public const int YUKON_RTM_MINOR = 0x0002;
public const int KATMAI_MINOR = 0x0003;
public const int DENALI_MINOR = 0x0004;
public const int ORDER_68000 = 1;
public const int USE_DB_ON = 1;
public const int INIT_DB_FATAL = 1;
public const int SET_LANG_ON = 1;
public const int INIT_LANG_FATAL = 1;
public const int ODBC_ON = 1;
public const int SSPI_ON = 1;
public const int REPL_ON = 3;
// send the read-only intent to the server
public const int READONLY_INTENT_ON = 1;
// Token masks
public const byte SQLLenMask = 0x30; // mask to check for length tokens
public const byte SQLFixedLen = 0x30; // Mask to check for fixed token
public const byte SQLVarLen = 0x20; // Value to check for variable length token
public const byte SQLZeroLen = 0x10; // Value to check for zero length token
public const byte SQLVarCnt = 0x00; // Value to check for variable count token
// Token masks for COLINFO status
public const byte SQLDifferentName = 0x20; // column name different than select list name
public const byte SQLExpression = 0x4; // column was result of an expression
public const byte SQLKey = 0x8; // column is part of the key for the table
public const byte SQLHidden = 0x10; // column not part of select list but added because part of key
// Token masks for COLMETADATA flags
// first byte
public const byte Nullable = 0x1;
public const byte Identity = 0x10;
public const byte Updatability = 0xb; // mask off bits 3 and 4
// second byte
public const byte ClrFixedLen = 0x1; // Fixed length CLR type
public const byte IsColumnSet = 0x4; // Column is an XML representation of an aggregation of other columns
// null values
public const uint VARLONGNULL = 0xffffffff; // null value for text and image types
public const int VARNULL = 0xffff; // null value for character and binary types
public const int MAXSIZE = 8000; // max size for any column
public const byte FIXEDNULL = 0;
public const ulong UDTNULL = 0xffffffffffffffff;
// SQL Server Data Type Tokens.
public const int SQLVOID = 0x1f;
public const int SQLTEXT = 0x23;
public const int SQLVARBINARY = 0x25;
public const int SQLINTN = 0x26;
public const int SQLVARCHAR = 0x27;
public const int SQLBINARY = 0x2d;
public const int SQLIMAGE = 0x22;
public const int SQLCHAR = 0x2f;
public const int SQLINT1 = 0x30;
public const int SQLBIT = 0x32;
public const int SQLINT2 = 0x34;
public const int SQLINT4 = 0x38;
public const int SQLMONEY = 0x3c;
public const int SQLDATETIME = 0x3d;
public const int SQLFLT8 = 0x3e;
public const int SQLFLTN = 0x6d;
public const int SQLMONEYN = 0x6e;
public const int SQLDATETIMN = 0x6f;
public const int SQLFLT4 = 0x3b;
public const int SQLMONEY4 = 0x7a;
public const int SQLDATETIM4 = 0x3a;
public const int SQLDECIMALN = 0x6a;
public const int SQLNUMERICN = 0x6c;
public const int SQLUNIQUEID = 0x24;
public const int SQLBIGCHAR = 0xaf;
public const int SQLBIGVARCHAR = 0xa7;
public const int SQLBIGBINARY = 0xad;
public const int SQLBIGVARBINARY = 0xa5;
public const int SQLBITN = 0x68;
public const int SQLNCHAR = 0xef;
public const int SQLNVARCHAR = 0xe7;
public const int SQLNTEXT = 0x63;
public const int SQLUDT = 0xF0;
// aggregate operator type TDS tokens, used by compute statements:
public const int AOPCNTB = 0x09;
public const int AOPSTDEV = 0x30;
public const int AOPSTDEVP = 0x31;
public const int AOPVAR = 0x32;
public const int AOPVARP = 0x33;
public const int AOPCNT = 0x4b;
public const int AOPSUM = 0x4d;
public const int AOPAVG = 0x4f;
public const int AOPMIN = 0x51;
public const int AOPMAX = 0x52;
public const int AOPANY = 0x53;
public const int AOPNOOP = 0x56;
// SQL Server user-defined type tokens we care about
public const int SQLTIMESTAMP = 0x50;
public const int MAX_NUMERIC_LEN = 0x11; // 17 bytes of data for max numeric/decimal length
public const int DEFAULT_NUMERIC_PRECISION = 0x1D; // 29 is the default max numeric precision(Decimal.MaxValue) if not user set
public const int SPHINX_DEFAULT_NUMERIC_PRECISION = 0x1C; // 28 is the default max numeric precision for Sphinx(Decimal.MaxValue doesn't work for sphinx)
public const int MAX_NUMERIC_PRECISION = 0x26; // 38 is max numeric precision;
public const byte UNKNOWN_PRECISION_SCALE = 0xff; // -1 is value for unknown precision or scale
// The following datatypes are specific to SHILOH (version 8) and later.
public const int SQLINT8 = 0x7f;
public const int SQLVARIANT = 0x62;
// The following datatypes are specific to Yukon (version 9) or later
public const int SQLXMLTYPE = 0xf1;
public const int XMLUNICODEBOM = 0xfeff;
public static readonly byte[] XMLUNICODEBOMBYTES = { 0xff, 0xfe };
// The following datatypes are specific to Katmai (version 10) or later
public const int SQLTABLE = 0xf3;
public const int SQLDATE = 0x28;
public const int SQLTIME = 0x29;
public const int SQLDATETIME2 = 0x2a;
public const int SQLDATETIMEOFFSET = 0x2b;
public const int DEFAULT_VARTIME_SCALE = 7;
//Partially length prefixed datatypes constants. These apply to XMLTYPE, BIGVARCHRTYPE,
// NVARCHARTYPE, and BIGVARBINTYPE. Valid for Yukon or later
public const ulong SQL_PLP_NULL = 0xffffffffffffffff; // Represents null value
public const ulong SQL_PLP_UNKNOWNLEN = 0xfffffffffffffffe; // Data coming in chunks, total length unknown
public const int SQL_PLP_CHUNK_TERMINATOR = 0x00000000; // Represents end of chunked data.
public const ushort SQL_USHORTVARMAXLEN = 0xffff; // Second ushort in TDS stream is this value if one of max types
// TVPs require some new in-value control tokens:
public const byte TVP_ROWCOUNT_ESTIMATE = 0x12;
public const byte TVP_ROW_TOKEN = 0x01;
public const byte TVP_END_TOKEN = 0x00;
public const ushort TVP_NOMETADATA_TOKEN = 0xFFFF;
public const byte TVP_ORDER_UNIQUE_TOKEN = 0x10;
// TvpColumnMetaData flags
public const int TVP_DEFAULT_COLUMN = 0x200;
// TVP_ORDER_UNIQUE_TOKEN flags
public const byte TVP_ORDERASC_FLAG = 0x1;
public const byte TVP_ORDERDESC_FLAG = 0x2;
public const byte TVP_UNIQUE_FLAG = 0x4;
// RPC function names
public const string SP_EXECUTESQL = "sp_executesql"; // used against 7.0 servers
public const string SP_PREPEXEC = "sp_prepexec"; // used against 7.5 servers
public const string SP_PREPARE = "sp_prepare"; // used against 7.0 servers
public const string SP_EXECUTE = "sp_execute";
public const string SP_UNPREPARE = "sp_unprepare";
public const string SP_PARAMS = "sp_procedure_params_rowset";
public const string SP_PARAMS_MANAGED = "sp_procedure_params_managed";
public const string SP_PARAMS_MGD10 = "sp_procedure_params_100_managed";
// RPC ProcID's
// NOTE: It is more efficient to call these procs using ProcID's instead of names
public const ushort RPC_PROCID_CURSOR = 1;
public const ushort RPC_PROCID_CURSOROPEN = 2;
public const ushort RPC_PROCID_CURSORPREPARE = 3;
public const ushort RPC_PROCID_CURSOREXECUTE = 4;
public const ushort RPC_PROCID_CURSORPREPEXEC = 5;
public const ushort RPC_PROCID_CURSORUNPREPARE = 6;
public const ushort RPC_PROCID_CURSORFETCH = 7;
public const ushort RPC_PROCID_CURSOROPTION = 8;
public const ushort RPC_PROCID_CURSORCLOSE = 9;
public const ushort RPC_PROCID_EXECUTESQL = 10;
public const ushort RPC_PROCID_PREPARE = 11;
public const ushort RPC_PROCID_EXECUTE = 12;
public const ushort RPC_PROCID_PREPEXEC = 13;
public const ushort RPC_PROCID_PREPEXECRPC = 14;
public const ushort RPC_PROCID_UNPREPARE = 15;
// For Transactions
public const string TRANS_BEGIN = "BEGIN TRANSACTION";
public const string TRANS_COMMIT = "COMMIT TRANSACTION";
public const string TRANS_ROLLBACK = "ROLLBACK TRANSACTION";
public const string TRANS_IF_ROLLBACK = "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION";
public const string TRANS_SAVE = "SAVE TRANSACTION";
// For Transactions - isolation levels
public const string TRANS_READ_COMMITTED = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED";
public const string TRANS_READ_UNCOMMITTED = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
public const string TRANS_REPEATABLE_READ = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ";
public const string TRANS_SERIALIZABLE = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE";
public const string TRANS_SNAPSHOT = "SET TRANSACTION ISOLATION LEVEL SNAPSHOT";
// Batch RPC flags
public const byte SHILOH_RPCBATCHFLAG = 0x80;
public const byte YUKON_RPCBATCHFLAG = 0xFF;
// RPC flags
public const byte RPC_RECOMPILE = 0x1;
public const byte RPC_NOMETADATA = 0x2;
// RPC parameter class
public const byte RPC_PARAM_BYREF = 0x1;
public const byte RPC_PARAM_DEFAULT = 0x2;
public const byte RPC_PARAM_IS_LOB_COOKIE = 0x8;
// SQL parameter list text
public const string PARAM_OUTPUT = "output";
// SQL Parameter constants
public const int MAX_PARAMETER_NAME_LENGTH = 128;
// metadata options (added around an existing sql statement)
// prefixes
public const string FMTONLY_ON = " SET FMTONLY ON;";
public const string FMTONLY_OFF = " SET FMTONLY OFF;";
// suffixes
public const string BROWSE_ON = " SET NO_BROWSETABLE ON;";
public const string BROWSE_OFF = " SET NO_BROWSETABLE OFF;";
// generic table name
public const string TABLE = "Table";
public const int EXEC_THRESHOLD = 0x3; // if the number of commands we execute is > than this threshold, than do prep/exec/unprep instead
// of executesql.
// dbnetlib error values
public const short TIMEOUT_EXPIRED = -2;
public const short ENCRYPTION_NOT_SUPPORTED = 20;
// CAUTION: These are not error codes returned by SNI. This is used for backward compatibility
// since netlib (now removed from sqlclient) returned these codes.
// SQL error values (from sqlerrorcodes.h)
public const int LOGON_FAILED = 18456;
public const int PASSWORD_EXPIRED = 18488;
public const int IMPERSONATION_FAILED = 1346;
public const int P_TOKENTOOLONG = 103;
// SNI\Win32 error values
// NOTE: these are simply windows system error codes, not SNI specific
public const uint SNI_UNINITIALIZED = unchecked((uint)-1);
public const uint SNI_SUCCESS = 0; // The operation completed successfully.
public const uint SNI_ERROR = 1; // Error
public const uint SNI_WAIT_TIMEOUT = 258; // The wait operation timed out.
public const uint SNI_SUCCESS_IO_PENDING = 997; // Overlapped I/O operation is in progress.
// Windows Sockets Error Codes
public const short SNI_WSAECONNRESET = 10054; // An existing connection was forcibly closed by the remote host.
// SNI internal errors (shouldn't overlap with Win32 / socket errors)
public const uint SNI_QUEUE_FULL = 1048576; // Packet queue is full
// SNI flags
public const uint SNI_SSL_VALIDATE_CERTIFICATE = 1; // This enables validation of server certificate
public const uint SNI_SSL_USE_SCHANNEL_CACHE = 2; // This enables schannel session cache
public const uint SNI_SSL_IGNORE_CHANNEL_BINDINGS = 0x10; // Used with SSL Provider, sent to SNIAddProvider in case of SQL Authentication & Encrypt.
public const string DEFAULT_ENGLISH_CODE_PAGE_STRING = "iso_1";
public const short DEFAULT_ENGLISH_CODE_PAGE_VALUE = 1252;
public const short CHARSET_CODE_PAGE_OFFSET = 2;
internal const int MAX_SERVERNAME = 255;
// Sql Statement Tokens in the DONE packet
// (see ntdbms\ntinc\tokens.h)
//
internal const ushort SELECT = 0xc1;
internal const ushort INSERT = 0xc3;
internal const ushort DELETE = 0xc4;
internal const ushort UPDATE = 0xc5;
internal const ushort ABORT = 0xd2;
internal const ushort BEGINXACT = 0xd4;
internal const ushort ENDXACT = 0xd5;
internal const ushort BULKINSERT = 0xf0;
internal const ushort OPENCURSOR = 0x20;
internal const ushort MERGE = 0x117;
// Login data validation Rules
//
internal const ushort MAXLEN_HOSTNAME = 128; // the client machine name
internal const ushort MAXLEN_USERNAME = 128; // the client user id
internal const ushort MAXLEN_PASSWORD = 128; // the password supplied by the client
internal const ushort MAXLEN_APPNAME = 128; // the client application name
internal const ushort MAXLEN_SERVERNAME = 128; // the server name
internal const ushort MAXLEN_CLIENTINTERFACE = 128; // the interface library name
internal const ushort MAXLEN_LANGUAGE = 128; // the initial language
internal const ushort MAXLEN_DATABASE = 128; // the initial database
internal const ushort MAXLEN_ATTACHDBFILE = 260; // the filename for a database that is to be attached during the connection process
internal const ushort MAXLEN_NEWPASSWORD = 128; // new password for the specified login.
// array copied directly from tdssort.h from luxor
public static readonly ushort[] CODE_PAGE_FROM_SORT_ID = {
0, /* 0 */
0, /* 1 */
0, /* 2 */
0, /* 3 */
0, /* 4 */
0, /* 5 */
0, /* 6 */
0, /* 7 */
0, /* 8 */
0, /* 9 */
0, /* 10 */
0, /* 11 */
0, /* 12 */
0, /* 13 */
0, /* 14 */
0, /* 15 */
0, /* 16 */
0, /* 17 */
0, /* 18 */
0, /* 19 */
0, /* 20 */
0, /* 21 */
0, /* 22 */
0, /* 23 */
0, /* 24 */
0, /* 25 */
0, /* 26 */
0, /* 27 */
0, /* 28 */
0, /* 29 */
437, /* 30 */
437, /* 31 */
437, /* 32 */
437, /* 33 */
437, /* 34 */
0, /* 35 */
0, /* 36 */
0, /* 37 */
0, /* 38 */
0, /* 39 */
850, /* 40 */
850, /* 41 */
850, /* 42 */
850, /* 43 */
850, /* 44 */
0, /* 45 */
0, /* 46 */
0, /* 47 */
0, /* 48 */
850, /* 49 */
1252, /* 50 */
1252, /* 51 */
1252, /* 52 */
1252, /* 53 */
1252, /* 54 */
850, /* 55 */
850, /* 56 */
850, /* 57 */
850, /* 58 */
850, /* 59 */
850, /* 60 */
850, /* 61 */
0, /* 62 */
0, /* 63 */
0, /* 64 */
0, /* 65 */
0, /* 66 */
0, /* 67 */
0, /* 68 */
0, /* 69 */
0, /* 70 */
1252, /* 71 */
1252, /* 72 */
1252, /* 73 */
1252, /* 74 */
1252, /* 75 */
0, /* 76 */
0, /* 77 */
0, /* 78 */
0, /* 79 */
1250, /* 80 */
1250, /* 81 */
1250, /* 82 */
1250, /* 83 */
1250, /* 84 */
1250, /* 85 */
1250, /* 86 */
1250, /* 87 */
1250, /* 88 */
1250, /* 89 */
1250, /* 90 */
1250, /* 91 */
1250, /* 92 */
1250, /* 93 */
1250, /* 94 */
1250, /* 95 */
1250, /* 96 */
1250, /* 97 */
1250, /* 98 */
0, /* 99 */
0, /* 100 */
0, /* 101 */
0, /* 102 */
0, /* 103 */
1251, /* 104 */
1251, /* 105 */
1251, /* 106 */
1251, /* 107 */
1251, /* 108 */
0, /* 109 */
0, /* 110 */
0, /* 111 */
1253, /* 112 */
1253, /* 113 */
1253, /* 114 */
0, /* 115 */
0, /* 116 */
0, /* 117 */
0, /* 118 */
0, /* 119 */
1253, /* 120 */
1253, /* 121 */
1253, /* 122 */
0, /* 123 */
1253, /* 124 */
0, /* 125 */
0, /* 126 */
0, /* 127 */
1254, /* 128 */
1254, /* 129 */
1254, /* 130 */
0, /* 131 */
0, /* 132 */
0, /* 133 */
0, /* 134 */
0, /* 135 */
1255, /* 136 */
1255, /* 137 */
1255, /* 138 */
0, /* 139 */
0, /* 140 */
0, /* 141 */
0, /* 142 */
0, /* 143 */
1256, /* 144 */
1256, /* 145 */
1256, /* 146 */
0, /* 147 */
0, /* 148 */
0, /* 149 */
0, /* 150 */
0, /* 151 */
1257, /* 152 */
1257, /* 153 */
1257, /* 154 */
1257, /* 155 */
1257, /* 156 */
1257, /* 157 */
1257, /* 158 */
1257, /* 159 */
1257, /* 160 */
0, /* 161 */
0, /* 162 */
0, /* 163 */
0, /* 164 */
0, /* 165 */
0, /* 166 */
0, /* 167 */
0, /* 168 */
0, /* 169 */
0, /* 170 */
0, /* 171 */
0, /* 172 */
0, /* 173 */
0, /* 174 */
0, /* 175 */
0, /* 176 */
0, /* 177 */
0, /* 178 */
0, /* 179 */
0, /* 180 */
0, /* 181 */
0, /* 182 */
1252, /* 183 */
1252, /* 184 */
1252, /* 185 */
1252, /* 186 */
0, /* 187 */
0, /* 188 */
0, /* 189 */
0, /* 190 */
0, /* 191 */
932, /* 192 */
932, /* 193 */
949, /* 194 */
949, /* 195 */
950, /* 196 */
950, /* 197 */
936, /* 198 */
936, /* 199 */
932, /* 200 */
949, /* 201 */
950, /* 202 */
936, /* 203 */
874, /* 204 */
874, /* 205 */
874, /* 206 */
0, /* 207 */
0, /* 208 */
0, /* 209 */
1252, /* 210 */
1252, /* 211 */
1252, /* 212 */
1252, /* 213 */
1252, /* 214 */
1252, /* 215 */
1252, /* 216 */
1252, /* 217 */
0, /* 218 */
0, /* 219 */
0, /* 220 */
0, /* 221 */
0, /* 222 */
0, /* 223 */
0, /* 224 */
0, /* 225 */
0, /* 226 */
0, /* 227 */
0, /* 228 */
0, /* 229 */
0, /* 230 */
0, /* 231 */
0, /* 232 */
0, /* 233 */
0, /* 234 */
0, /* 235 */
0, /* 236 */
0, /* 237 */
0, /* 238 */
0, /* 239 */
0, /* 240 */
0, /* 241 */
0, /* 242 */
0, /* 243 */
0, /* 244 */
0, /* 245 */
0, /* 246 */
0, /* 247 */
0, /* 248 */
0, /* 249 */
0, /* 250 */
0, /* 251 */
0, /* 252 */
0, /* 253 */
0, /* 254 */
0, /* 255 */
};
internal enum TransactionManagerRequestType
{
Begin = 5,
Commit = 7,
Rollback = 8,
Save = 9
};
internal enum TransactionManagerIsolationLevel
{
Unspecified = 0x00,
ReadUncommitted = 0x01,
ReadCommitted = 0x02,
RepeatableRead = 0x03,
Serializable = 0x04,
Snapshot = 0x05
}
internal enum GenericType
{
MultiSet = 131,
};
// Date, Time, DateTime2, DateTimeOffset specific constants
internal static readonly long[] TICKS_FROM_SCALE = {
10000000,
1000000,
100000,
10000,
1000,
100,
10,
1,
};
internal const int WHIDBEY_DATE_LENGTH = 10;
internal static readonly int[] WHIDBEY_TIME_LENGTH = { 8, 10, 11, 12, 13, 14, 15, 16 };
internal static readonly int[] WHIDBEY_DATETIME2_LENGTH = { 19, 21, 22, 23, 24, 25, 26, 27 };
internal static readonly int[] WHIDBEY_DATETIMEOFFSET_LENGTH = { 26, 28, 29, 30, 31, 32, 33, 34 };
}
internal enum SniContext
{
Undefined = 0,
Snix_Connect,
Snix_PreLoginBeforeSuccessfullWrite,
Snix_PreLogin,
Snix_LoginSspi,
Snix_ProcessSspi,
Snix_Login,
Snix_EnableMars,
Snix_AutoEnlist,
Snix_GetMarsSession,
Snix_Execute,
Snix_Read,
Snix_Close,
Snix_SendRows,
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.